Compare commits

...
45 Commits
Author SHA1 Message Date
shinyobjectz bd5efdc0d4 Small caps synthesised, flex lines with a 1/64 px tolerance, and a table's stray text in anonymous cells
Three layout misses 0.1.11 shipped, each from its issue's own repro.

Times, Helvetica: most system faces) the text drew in normal case. blitz-dom now checks the face a text's lower-case
letters are drawn in for an smcp GSUB feature (once per face, layout/small_caps.rs) and, where it has none, draws each
run of lower-case letters as their capitals at 70% of the font size, as Chrome synthesises them.

gaps come out a few ulps over 658.8 px, so the third item wrapped (rows of 2, 2, 1). Chrome lays out in 1/64 px units
and keeps them on one line. Taffy 0.15.0 is vendored with a line that overflows by less than 1/64 px still fitting,
greedy and balanced wrapping alike.

element around its text had no cells and drew nothing, not even its background. The table's runs of other children
(text, blocks, inline elements) are now wrapped in an anonymous block that the table lays out as an anonymous row
holding one anonymous cell, as css-tables-3 wraps them: the element is laid out shrink-to-fit around its text.

The regression tests (systems/page/tests/layout_0112.rs) lay out each repro; all four fail on main and pass here.
2026-11-27 12:29:47 -08:00
shaneandshinyobjectz 6f96c78a8b Paint fixes for 0.1.11's reports: nested masks in a faded group, inline background images, empty clip-paths, svg overflow: visible (#256)
#247: two nested mask-image layers inside an opacity group refused the frame as past Vello's bump buffers. The scene
was small; its layers nested seven deep, and every layer past the fourth spills each tile's 16x16 pixels into Vello's
blend spill buffer, whose fixed size (1 << 20 pixels, raea-page's 1 << 18) holds 4096 spills, fewer than a 1080x1920
page's 8160 tiles. vello_encoding's resolve now measures how deep the scene's layers nest (layer_depth) and the
render's config sizes the blend spill for every tile to spill that deep (blend_spill_for), within the largest buffer
the device binds (set_max_buffer_size, given by raea-page).

#248: an inline element's background-image wasn't drawn (only its colour was). text.rs draw_inline_backgrounds now
draws its image layers on each line fragment, laid out over the fragments side by side as box-decoration-break: slice
does, so a background-size sweep crosses the lines in turn.

#250: clip-path: inset() that clips to no area (inset(0 0 0 100%)) returned no shape, which meant no clip-path, and
the element was drawn whole. It is now an empty clip, and an element whose clip-path has no area isn't drawn.

#251: an inline <svg> was always clipped to its viewport. The UA sheet now gives svg:not(:root) overflow: clip (as
Chrome's hidden, without making it a scroll container, so layout is unchanged), and draw_svg clips only when the
svg's overflow isn't visible.

Regression tests: vello_encoding's resolve and config tests for the blend spill; systems/page/tests/paint_repros.rs
paints each of #248, #250 and #251's repros into a recording scene and checks what is filled and under which clips.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-27 12:29:15 -08:00
shaneandshinyobjectz e70d9c79c1 A loaded new Image() has the picture's size (#253) (#255)
A composition's Image (sdk/raea frame-globals.ts, installed where the runtime has none) fired load but kept width,
height, naturalWidth and naturalHeight at 0, so code sizing a canvas from it made a 0-high canvas, and a
CanvasTexture made from that was refused as an undetermined image format.

Now, when its load fires, naturalWidth and naturalHeight are the picture's size: a data: URL's from its header
(@raea/ui's sniffSize), any other src's from the host's asset.load, which finds staticFile's /media/ paths as <Img>
does (media/, assets/, public/) and fetches http URLs through raea's cache. width and height are the ones given (the
constructor's, or set) else the natural size, as in a browser. A file the host can't find fires error and onerror
instead of load, and only the last src set fires. The manual's web-components guide says so.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-27 10:19:31 -08:00
shinyobjectz f4db12c1d0 CI's size and dupes gates on 0.1.11: the mixer's output device (the stream and following the system's output) in its own crate, raea-sys-mix-device, so raea-sys-mix is under 2000 lines and live.rs under 500; one make::Gate in raea-core-brief for a cut's and a goal's gates (cut-plan and goal-plan had the same struct, and status.rs the same closure twice); the CTA's best line found without a copy of hands-audit's fold 2026-11-26 17:26:59 -08:00
shinyobjectz cd159fe0be promoted-from: the layers gate's files (tools/layers.sh, layers.toml, layers.allow) may differ between an rc and its release, as no build reads them (0.1.11-rc2's one-line layers fix would otherwise force a rebuild) 2026-11-26 16:57:39 -08:00
shinyobjectz 316b612d70 layers: raea-runtime-goal-plan is in the runtime layer (MK28's crate had none, and main's CI gates failed on it from c41ec580 on) 2026-11-26 16:57:08 -08:00
shinyobjectz aa40a2fa86 #82: the ARM64 build (it compiles: raea.exe is AA64 and runs) is packed and checked without drawing (release-check.sh RAEA_CHECK_NO_GPU=1 keeps plugins, guides, song map and bin\'s files; the windows-11-arm runner has only WARP, which segfaults in Bevy as on x64, and lavapipe has no ARM64 build), and it uses the release's compile cache 2026-11-26 14:01:28 -08:00
shinyobjectz 48705982b6 windows-arm.yml runs on v* tags too, beside release.yml, and attaches raea-VERSION-windows-arm64.zip to that release (skills-passed from the tag, as release.yml reads it); an ARM64 failure never holds up the release 2026-11-26 14:01:28 -08:00
shinyobjectz 7580433cd2 windows-arm.yml: metis-sys alone on windows-latest's x64 MSVC too, which release.yml builds with 2026-11-26 14:01:28 -08:00
shinyobjectz 28f3fd814b #82: metis-sys vendored with GKlib's stdint.h/inttypes.h stand-ins only before Visual Studio 2013 (Visual Studio 18's stdint.h types int_fast16_t differently, and the windows-11-arm build failed on every GKlib file); its graphs, manual and programs left out 2026-11-26 14:01:28 -08:00
shinyobjectz 1905dc723c #82: a windows-arm64 zip: RAEA_WIN_ARCH=arm64 has onnxruntime.sh and win-bundle.sh take the ARM64 runtime, VC++ CRT, uv and DXC (FFmpeg stays x64, run emulated), release.sh names and packs raea-VERSION-windows-arm64.zip, and windows-arm.yml packs and checks it on WARP 2026-11-26 14:01:28 -08:00
shinyobjectz c41dd64516 #82: raea built natively for Windows on ARM in CI (windows-arm.yml on windows-11-arm: the release's four binaries, raea --version, a 2D still on WARP); rav1d's assembly off there, where MSVC skips its GNU .S files 2026-11-26 14:01:28 -08:00
shinyobjectz 1fc3a07655 Merge branch 'whats-new-0111' 2026-11-26 14:01:28 -08:00
shinyobjectz 986bd33463 whats-new 0.1.11: goals as make jobs, live sound following the output, tall pictures (#245), Windows on ARM (#82), and in the app typed Ideate on your own agent, one Settings, voice with Studio, Codex on Windows (#244) 2026-11-26 14:01:27 -08:00
shane c41ec580a9 Merge pull request #246 from shinyobjectz/skills-0111
skills: CLI reference for 0.1.11
2026-11-26 11:23:26 -08:00
shane 7e25dcc56e skills: the CLI reference as 0.1.11 prints it (raea-skills 98de983: make judge, make status's goal kind) 2026-11-26 11:23:10 -08:00
shinyobjectz 561e7a569c An image larger than Vello's atlas is decoded at a size that fits it (#245: a 1080x18000 site capture drawn 880 wide was refused; fit to the atlas's side, 16384, not the device's 32768); a Snapdragon's Adreno runs on DX12 on Windows, where Vulkan drew Vello's 2D pages striped (#82) 2026-11-26 11:21:27 -08:00
shinyobjectz 0649788f7f MK25: a rotated CTA, cta.also
Dutch's and The Body Shop's briefs each rotate two host CTAs. The cut lands on any one of them. Each also line is held to the brief's text like any other quote. Test: a rotated Dutch line lands, and a line the brief doesn't have holds the job.
2026-11-26 10:36:58 -08:00
shinyobjectz 1a77da4980 box.sh latest: every box in raea cloud's list onto a release, and box.sh up takes the newest release by default
Shane, 11-26: "make sure that release pipeline automatically updates boxes for raea cloud to the latest". Both live boxes were still on 0.1.9, because box.sh's default was a pinned version. box.sh latest [VERSION] waits on the tag's release.yml run (gh run watch) until the Linux archive is attached, then rebuilds each listed box with raea at that version and sdk/cloud's server from the release's own commit. Each box goes only after its running agents finish, as box.sh up already does. A box that can't be rebuilt is named, and the others still go. RAEA_BOX_DRY=1 prints the plan: on 0.1.10 it named raea-2 and raea-3 onto 22834de9b1. tools/agents/release-go.sh (private) starts it after every publish.
2026-11-26 10:29:22 -08:00
shinyobjectz 1a913e6b06 raea frames check on raea cloud boxes: what a cut's pictures get wrong that a viewer sees at once, measured (11-25, Shane on StreetTalk's cuts: "it cuts out faces all the time and also does split frame shots when they make no sense", "it makes text too small on some things, we should have a text/glyph readability check and measurement").
Faces: the export's frames, two a second, go through the farm's new POST /v1/faces (OpenCV's YuNet, 232 KB on CPU, pinned by hash). A box has no vision backend (raea-perceive isn't in raea's Linux build), so raea frame and framing="face" refuse there. A face of someone in the shot touching the frame's edge or a split screen's seam for a second or more is an error; a split screen showing a face in only one half is a warning. Seams are lone lines where the picture jumps across 70% of the frame, held a second, in its middle 60% (a caption's box is two lines close together and doesn't count).

Text: every text's font size from the render's manifest, scaled to a 1080-wide frame: under 40 px is an error, under 48 px a warning.

offload.ts adds --manifest OUT.render.json to a video render that has none and runs the check after the words pass; an error fails the render. OUT.despite.txt says why a face at the edge is meant and turns its errors to warnings. image/raea.sh routes raea frames.

Checked on StreetTalk's delivered cuts: The Body Shop 5 and 6 and Dutch 2, 3 and 4 fail on faces cut at the edge (1 to 6.5 s each), and Dutch 4 on a face cut by a split's seam; a 28 px disclaimer fails a render on raea-2. test/units.ts covers the rules. Farm deployed; the three files copied onto raea-2.
2026-11-26 10:29:22 -08:00
shinyobjectz 7db0e7e149 raea cloud: a render's output outside the project goes back as .raea-cloud-out-N-NAME at the project's top, not inside a .raea-cloud-out folder. The folder is never sent to the farm, and a still's writer (unlike a video's encoder) doesn't make one, so every PNG made outside the project failed with "no frame was written" (11-25, StreetTalk's storyboards: raea render board.html -o out/board.png). Checked through the farm: an HTML storyboard to PNG, written and moved into place; test/units.ts updated. 2026-11-26 10:29:22 -08:00
shinyobjectz ab63120653 raea words: a dip in a word counts as a crossfade only when it comes back up inside the word (Whisper's spans take in the quiet after a word, so a sentence trailing off was flagged on raea-2's first real take); Whisper's joined words ("for $60") split before comparing; edge words flagged only when the sound is at speech level on the first or last 30 ms. Checked on raea-2 (box updated) and on the finished Dutch cut (passes, one warning), the crossfaded and mid-word cuts (still fail). 2026-11-26 10:29:22 -08:00
shinyobjectz 8938819947 raea words on raea cloud boxes: a take's or an export's words by Whisper large-v3 on the farm (POST /v1/words, the model raea cloud's library index transcribes with, OpenRouter's key in Modal secret raea-farm-words), as TAKE.words.json; raea words check VIDEO --expect LINES.txt holds an export to the lines its cut should say: a word missing or cut short is an error, a word heard differently, speech dipping under a crossfade or a word cut by the first or last frame a warning. A box had no transcriber (raea's is parakeet-mlx, Mac only), so agents cut on guessed frames and shipped words clipped by cuts and faded under crossfades (11-25, Shane: "before exporting the audio requires a transcription pass to be sure it matches"). Every video render (offload.ts) now runs the pass on its output, and fails the render when OUT.lines.txt is beside it and a word is missing or clipped. raea transcribe is the same command. Checked: test/words.ts; on StreetTalk's finished Dutch cut (passes), the same cut joined mid-word (fails: vaccines heard as exam, tests missing) and with a 1.5 s crossfade over speech (fails: five words lost). Farm deployed. 2026-11-26 10:29:22 -08:00
shinyobjectz 79cda1dc8c raea cloud boxes keep an agent's socket from going idle, and stop what a stopped agent left running. Between raea cloud and a box a socket is closed after about two minutes without traffic, and an agent waiting on a long render sends nothing: five of StreetTalk's seven "socket closed" ends on 11-25 came 114-125 s into a silence. The box sends a _raea/keepalive notification every 20 s (raea cloud skips notifications it doesn't know; the agent never sees it). An agent now runs in its own process group, stopped whole when its socket closes or it exits: a killed agent's background renders went on as orphans, 4 GB of them on raea-2. 2026-11-26 10:29:22 -08:00
shinyobjectz f0a266718e raea farm: a render that names its own --manifest renders. The probe ran it with two --manifest and raea wrote its own where the render's went, so frame 0 said no length and the job stopped with exit 1 and no reason (StreetTalk's four cuts, 11-25). The render's --manifest is kept from every GPU run and written from frame 0's at the end; a probe with no length says so. A video's sound run finishes before the reload that brings the GPUs' frames (its open files in the job's folder refused it). Farm deployed. 2026-11-26 10:29:22 -08:00
shinyobjectz c8af179033 raea cloud boxes stop a runaway before it takes the box down: StreetTalk's agent rendered two cuts of 4K interviews on raea-2's CPU and the 8 GB box stopped answering, every agent's socket with it (11-25). A box's processes share one cgroup that can't be split, so there's no kernel cap; server/memguard.ts, like earlyoom, looks at free memory each second and below 700 MB (or 8%) kills the largest process the server's agents started over 1 GB (never an agent or the server), and says so in the box's log and each agent's trace. RAEA_CLOUD_MEMGUARD=0 turns it off. Tested offline and on raea-2 (a real 1.5 GB runaway stopped). 2026-11-26 10:29:22 -08:00
shinyobjectz a0f6a95fe7 raea farm: a video's GPU runs find the footage, and two renders at once don't fail each other. The coordinator linked a job's media from the cache but committed only after rendering, so a still (on the coordinator) found the footage and every GPU run of a video said "No such file" (StreetTalk, 11-25: four full cuts refused). It commits right after linking. The web container serves many requests at once, and a volume reload there refused while another request had a file open (GET out: 500, losing a finished render) or took /farm away from one making a job's folder (POST jobs: 500); requests that touch the volume now share it and a reload waits until none is in it (Gate), and a reload that still won't go answers 503, which the box's jobFiles asks again on. A render that fails on a file under out/ says out/ isn't sent and where its inputs go. Farm deployed. 2026-11-26 10:29:22 -08:00
shinyobjectz afaeaa0a7a raea cloud renders know a project's footage by the file, not its path: a thread started again links the same files into a new folder (StreetTalk's restart hard-linked 1.9 GB of interviews), and keyed by path they were hashed again before its first render. media.ts keys its hash cache by device and inode, with size and time 2026-11-26 10:29:22 -08:00
shinyobjectz 65f2a6ae1e box.sh builds a box on raea 0.1.9 unless RAEA_VERSION says otherwise: its default was still 0.1.6, so a plain rebuild of raea-2 (11-25) took it from 0.1.9 back to 0.1.6 2026-11-26 10:29:22 -08:00
shinyobjectz 00deff035c raea cloud renders send a project's footage once: a project not in raea's LFS (every raea cloud project: its repo is on Cloudflare's Git) put all its media in every render's tar, so one frame of StreetTalk's Dutch edit packed and sent 1.9 GB of interviews, read whole into the box's memory (2-4 GB a render); with three agents rendering at once the 15 GB box ran out and every agent's socket dropped. The farm now keeps media by hash (POST /v1/blobs/have, PUT /v1/blobs/OID, streamed and checked against its hash, farm.py); offload.ts sends each footage or large file once (media.ts farmInputs: hashes kept by path, size and time) and names it in the job's .raea-cloud-media.json with no href, and farm_media links it into the job from the cache instead of copying it. Trial on raea-2: the first frame 144 s (hashing and sending 2 GB once), the next 17 s with nothing sent; it had timed out at 60 s. RAEA_CLOUD_GPU_BLOBS=0 puts the media back in the tar; a farm without the cache does too. Tests: test/farm-blobs.ts, test/farm_media.py. Farm deployed (raea-farm). (farm.py and offload.ts also carry the games lane's kits/ fixes that were already on the box.) 11-25, Shane: "if there's an issue with big files ... some kind of r2 streaming thing, I'm happy to have you own the changes" 2026-11-26 10:29:22 -08:00
shinyobjectz 7611a96e34 raea cloud's box sends each agent's stderr along its socket (_raea/stderr), so the run's trace keeps it instead of only the box's disk; box.sh up won't rebuild a box whose server can't say whether agents are running (11-25, Shane: "make sure for cloud runs we are getting all the session traces and logs ... all recoverable") 2026-11-26 10:29:22 -08:00
shinyobjectz 6fb27ef9e8 raea cloud's boxes are stamped and managed: box.sh up stamps every build (BUILD.json: an id from the packed files, the commit, whether the tree was dirty and which files; the tarball kept in ~/.config/raea-cloud/builds so RAEA_CLOUD_BUILD=ID makes another box from exactly it), waits for a box's running agents to finish before rebuilding it (RAEA_BOX_FORCE=1 to cut them off), and promote/list put a box into raea cloud's list (POST /v1/admin/boxes). The box's health says its build and how many agents run. setup.sh installs raea's skills by raea's own agent names (claude-acp had never matched: no box had them), and each client's socket links them into its own config folders. (box.sh's hunks also carry the games lane's raea-games tarball put, which sat beside them.) 11-25, Shane: "make sure this mix up of boxes and versions are all managed effectively" 2026-11-26 10:29:22 -08:00
shinyobjectz 0c0de9b3d6 raea cloud ingest: a fingerprint's model on the GPU: fingerprint_fit trains a linear head per modality on EmbeddingGemma 2's vectors with torch (good against bad and the workspace's files, k-fold AUC) into the volume raea-fingerprints, fingerprint_score scores a file's segments; POST /v1/fingerprints/fit, GET /v1/fingerprints/jobs/{id}, POST /v1/fingerprints/score 2026-11-26 10:29:22 -08:00
shinyobjectz 84f6c59dd0 raea cloud ingest: index jobs transcribe with Whisper large-v3 on OpenRouter when the raea-ingest secret has OPENROUTER_API_KEY (words.ts RAEA_LIBRARY_WORDS=openrouter), and have the secret 2026-11-26 10:29:22 -08:00
shinyobjectz 96adb3ecfb raea cloud ingest: index jobs on Modal (ingest.py index_job, POST/GET /v1/index-jobs) on an L4 (EmbeddingGemma 2 at fp16 on CUDA 13; build/Dockerfile.gpu), the search-words server on the CPU, gpu_probe to check the GPU; docs/cloud-ingest.feature IG8 now raea's indexer into turbopuffer, Enterprise only (raea cloud is Enterprise only, Shane 11-24), with IG6 and IG9 marked built 2026-11-26 10:29:22 -08:00
shinyobjectz 4e12541984 raea cloud ingest: docs/cloud-ingest.feature IG1-IG13 (a synced folder pictured, understood, embedded and organized; Shane 11-24), and raea-ingest on Modal (sdk/cloud/deploy/modal/ingest.py): POST /v1/frame makes a JPEG frame of a video at an address, for synced files with no picture in their tool (IG4). Deployed on profile raea; secret raea-ingest 2026-11-26 10:29:22 -08:00
shinyobjectz 4cc8f58e0a The Google sign-in's screen is handed out once Chrome's window is up (a fresh profile takes about 20 s on the box's CPU, and the viewer showed black till then), and a display left by an X server that's gone (a service restart leaves their sockets) is reclaimed. setup.sh adds xdotool for the window check 2026-11-26 10:29:22 -08:00
shinyobjectz 1873676251 The sign-in's Chrome shows no warning bar across Google's page (--test-type beside --no-sandbox) 2026-11-26 10:29:22 -08:00
shinyobjectz 374426411e raea cloud's Google sign-in can run in a browser on the box, which the person works from the dashboard: Chrome on a virtual display of its own (google-screen.ts), its profile in the sign-in's folder so the Google session goes with it, served over VNC on WS /v1/google-token/ID/screen. Google's last step lands on Antigravity's listener on the box, so the sign-in finishes with nothing pasted; POST /v1/google-token/ID with no address waits for it ({pending} after 25 s). A box without Chrome falls back to the pasted address. setup.sh installs Chrome, Xvfb and x11vnc 2026-11-26 10:29:22 -08:00
shinyobjectz e435bff43e raea cloud's box runs an agent only when it's named, by the request (?agent=) or the box's RAEA_AGENT: no default from whichever is installed first (it had made antigravity-acp the default on raea-1), so a run is never on a model nobody picked. With neither, the socket is refused and says which agents are installed 2026-11-26 10:29:22 -08:00
shinyobjectz 4b2b39edd3 raea cloud's box: with no agent named, Claude when it's installed (antigravity-acp sorts first and became the default on raea-1's refresh) 2026-11-26 10:29:22 -08:00
shinyobjectz 063ae93f30 raea cloud's box signs agents in to a Google AI subscription: Antigravity's Google sign-in runs on the box, the person pastes back the address Google sent them to, and the token file comes back once (POST /v1/google-token, google-token.ts); an agent socket given it (RAEA_GOOGLE_CREDENTIAL) has it written into its own GEMINI_HOME. With the box's Claude sign-in (claude-token.ts, per-socket keys and homes), live on raea-1 since 11-21 and committed here; antigravity-acp joins the box's default agents 2026-11-26 10:29:22 -08:00
shinyobjectz 2a63d75e1b Live sound follows the system's output: a changed default device (headphones, AirPods, a display) or a broken stream reopens the mixer's stream on the one in use 2026-11-26 10:29:12 -08:00
shinyobjectz 2a005e0e30 MK28-MK29: a goal as a fifth kind of make job, held by its commands and a fresh critic, never the agent's word
make: goal({ goal, rules }) on brief.ts: each rule a command that must exit 0 (run, with a timeout), a file that must exist (a deliverable) or words a fresh critic must find true (says). raea make status runs the commands at every status (the Stop hook's too); raea make judge [--by claude|kimi] asks a read-only critic and keeps its verdict in review/goal.judge.json, which clears a says rule only while it is no older than the work's newest file. Make also gets previews (what a job shows but never delivers: review/ and previews/ by default), and status lists files.deliverables and files.previews. runtime/goal-plan holds the gates (raea-app-make was at its size cap).

Test: goal-plan's six (a command passes or says why, a timeout, a stale and a fresh verdict, file rules left to deliverables, the doctor); end to end on a scratch brief, a curt greeting.txt was refused by the critic and a warm one passed, with both commands passing.
2026-11-26 09:41:28 -08:00
shinyobjectz 04098af5af README: the release note says releases are experimental and the app is unstable (Linux and Windows most), with no version or date to go stale 2026-11-26 09:26:36 -08:00
261 changed files with 82080 additions and 253 deletions

No files matched your search

+175
View File
@@ -0,0 +1,175 @@
# raea built natively for Windows on ARM (#82: a Snapdragon X runs the x64 build under emulation, and asked for its
# own). GitHub's windows-11-arm runner builds what release.yml's windows job builds, for aarch64-pc-windows-msvc, runs
# `raea --version`, packs and checks raea-VERSION-windows-arm64.zip with tools/release.sh (RAEA_WIN_ARCH=arm64)
# without drawing (RAEA_CHECK_NO_GPU=1: WARP segfaults in Bevy's compute shaders here as on x64, and Mesa's lavapipe has
# no ARM64 build; a Snapdragon PC is what draws, #82), and on a v* tag attaches it to that
# release. It runs beside release.yml, not in it, so a release never waits on or fails with the ARM64 build; a
# promoted release (release-go.sh) builds it again from the tag. install.ps1 takes it on an ARM64 PC when it's there.
name: windows-arm
on:
workflow_dispatch:
inputs:
ref:
description: "commit, branch or tag to build"
required: false
version:
description: "the version the zip is named for (raea-VERSION-windows-arm64.zip)"
required: false
push:
branches: [windows-arm64]
tags: ["v*"]
permissions:
contents: write
jobs:
build:
runs-on: windows-11-arm
timeout-minutes: 350
env:
# the release builds' compile cache (tools/release/compile-cache.sh), under this OS and architecture's own prefix
RELEASE_CACHE_ENDPOINT: ${{ secrets.RELEASE_CACHE_ENDPOINT }}
AWS_ACCESS_KEY_ID: ${{ secrets.RELEASE_CACHE_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.RELEASE_CACHE_SECRET }}
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.ref || github.sha }}
submodules: true
lfs: false
- name: Toolchain (rust-toolchain.toml's pin)
run: |
if ! command -v rustup >/dev/null; then
curl -fsSL --retry 3 -o "$RUNNER_TEMP/rustup-init.exe" https://static.rust-lang.org/rustup/dist/aarch64-pc-windows-msvc/rustup-init.exe
"$RUNNER_TEMP/rustup-init.exe" -y --default-toolchain none --profile minimal
echo "$USERPROFILE/.cargo/bin" >> "$GITHUB_PATH"
export PATH="$USERPROFILE/.cargo/bin:$PATH"
fi
rustup show active-toolchain || rustup toolchain install
rustc -vV
# ring builds its aarch64 assembly with clang (and only clang) on Windows
- name: clang (ring's assembly)
run: |
if ! command -v clang >/dev/null; then
for d in "/c/Program Files/LLVM/bin" "/c/Program Files/Microsoft Visual Studio"/*/*/VC/Tools/Llvm/ARM64/bin; do
[ -x "$d/clang.exe" ] && { echo "$d" >> "$GITHUB_PATH"; export PATH="$d:$PATH"; break; }
done
fi
command -v clang >/dev/null || { winget install -e --id LLVM.LLVM --accept-source-agreements --accept-package-agreements --silent; echo "/c/Program Files/LLVM/bin" >> "$GITHUB_PATH"; export PATH="/c/Program Files/LLVM/bin:$PATH"; }
clang --version
- name: jq that writes LF
run: |
mkdir -p "$RUNNER_TEMP/jq"
printf '#!/bin/bash\nexec "%s" -b "$@"\n' "$(command -v jq)" > "$RUNNER_TEMP/jq/jq"
chmod +x "$RUNNER_TEMP/jq/jq"
echo "$RUNNER_TEMP/jq" >> "$GITHUB_PATH"
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.2
- name: The runtime's packages
run: for d in sdk/react/js sdk/react/tw; do (cd "$d" && bun install --frozen-lockfile); done
# (an sccache the action can't fetch for ARM64 Windows leaves the build uncached, as compile-cache.sh does)
- name: Compile cache (sccache, as release.yml's)
if: env.AWS_ACCESS_KEY_ID != ''
continue-on-error: true
uses: mozilla-actions/[email protected]
- name: Use the compile cache
if: env.AWS_ACCESS_KEY_ID != ''
run: bash tools/release/compile-cache.sh
- name: Build
run: |
feat=$(bash tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)
t() { s=$SECONDS; "$@"; echo "::notice::Windows ARM64 $(( (SECONDS - s) / 60 )) min: ${*:7}"; }
t cargo build --profile dist --locked -p raea-cli --bin raea --no-default-features --features "$feat"
t cargo build --profile dist --locked -p raea-rune-host
t cargo build --profile dist --locked -p raea-page-host --features window
t cargo build --profile dist --locked -p raea-perceive
- name: What raea.exe is and imports
run: |
file target/dist/raea.exe || true
dumpbin=$(ls "/c/Program Files/Microsoft Visual Studio"/*/*/VC/Tools/MSVC/*/bin/Hostarm64/arm64/dumpbin.exe 2>/dev/null | head -1)
[ -n "$dumpbin" ] && "$dumpbin" -nologo -headers -dependents target/dist/raea.exe | grep -iE 'machine|\.dll$' | sed 's/^ *//' | tee -a "$GITHUB_STEP_SUMMARY" || true
target/dist/raea.exe --version | tee -a "$GITHUB_STEP_SUMMARY"
- name: Models (pinned by URL and sha256 in tools/release/models.tsv)
run: |
while IFS=$'\t' read -r path url sha; do
case $path in ''|'#'*) continue ;; esac
mkdir -p "$HOME/.local/share/raea-models/$(dirname "$path")"
curl -fsSL "$url" -o "$HOME/.local/share/raea-models/$path"
echo "$sha $HOME/.local/share/raea-models/$path" | sha256sum -c -
done < <(tr -d '\r' < tools/release/models.tsv)
# bin\ as release.yml's windows job fills it, with the ARM64 runtime, uv and DXC (RAEA_WIN_ARCH=arm64), then the
# zip packed and checked by tools/release.sh as raea-VERSION-windows-arm64.zip. The skills gate is this commit's
# (public raea has no feed app; cli.md is still checked against this build's help); nothing is drawn
- name: Pack and check (tools/release.sh)
env:
RAEA_WIN_ARCH: arm64
RAEA_CHECK_DIR: ${{ runner.temp }}/release-check
RAEA_CHECK_NO_GPU: "1"
run: |
bash tools/release/onnxruntime.sh target/dist
bash tools/release/win-bundle.sh target/dist
v="${{ inputs.version }}"
case $GITHUB_REF in
refs/tags/v*)
v=${v:-${GITHUB_REF_NAME#v}}
# where the skills gate passed, as release.yml reads it (the tag's skills-passed line)
eval "$(GITHUB_ENV= bash tools/release/skills-passed.sh "$GITHUB_REF_NAME" | grep '^RAEA_SKILLS_PASSED=')" ;;
*) RAEA_SKILLS_PASSED=$(git rev-parse HEAD) ;;
esac
export RAEA_SKILLS_PASSED
bash tools/release.sh "${v:-0.0.0-arm64}" target/dist HEAD
# on a v* tag, beside release.yml's archives (the release made here if release.yml hasn't yet)
- name: Attach to the release
if: startsWith(github.ref, 'refs/tags/v')
env:
GH_TOKEN: ${{ github.token }}
run: |
pre=; case $GITHUB_REF_NAME in *-*) pre=--prerelease ;; esac
gh release view "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" >/dev/null 2>&1 ||
gh release create "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" $pre --title "raea ${GITHUB_REF_NAME#v}" --notes "Built by .github/workflows/release.yml; notes follow." ||
gh release view "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" >/dev/null
gh release upload "$GITHUB_REF_NAME" -R "$GITHUB_REPOSITORY" dist/raea-*-windows-arm64.zip dist/raea-*-windows-arm64.zip.sha256 --clobber
- uses: actions/upload-artifact@v4
if: always()
with:
name: windows-arm64-zip
path: dist/raea-*-windows-arm64.zip*
retention-days: 7
compression-level: 0
if-no-files-found: ignore
- uses: actions/upload-artifact@v4
if: always()
with:
name: windows-arm64-bins
path: |
target/dist/raea.exe
target/dist/raea_bundle.dll
target/dist/raea-rune-host.exe
target/dist/raea-page-host.exe
target/dist/raea-perceive.exe
retention-days: 7
if-no-files-found: ignore
# vendor/metis-sys's header change reaches release.yml's x64 build too (windows-latest's Visual Studio): metis-sys
# alone, in a scratch crate, compiled there
metis-x64:
runs-on: windows-latest
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.ref || github.sha }}
sparse-checkout: vendor/metis-sys
- name: metis-sys on x64 MSVC
run: |
c="$RUNNER_TEMP/metis-x64"; mkdir -p "$c/src" && : > "$c/src/lib.rs"
printf '[package]\nname = "metis-x64"\nversion = "0.0.0"\nedition = "2021"\n[dependencies]\nmetis-sys = { path = "%s" }\n[workspace]\n' "$(cygpath -m "$GITHUB_WORKSPACE/vendor/metis-sys")" > "$c/Cargo.toml"
cl 2>&1 | head -1 || true
cd "$c" && cargo build
Generated
+20 -4
View File
@@ -10263,8 +10263,6 @@ dependencies = [
[[package]]
name = "metis-sys"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "769ee6be814b21c52afcc631f07051f578487d642f3e89a45f2a086fd94fffa9"
dependencies = [
"cc",
]
@@ -13897,6 +13895,7 @@ dependencies = [
"raea-core-review",
"raea-io-home",
"raea-runtime-cut-plan",
"raea-runtime-goal-plan",
"raea-runtime-lod-plan",
"resvg 0.48.1",
"serde_json",
@@ -15427,6 +15426,14 @@ dependencies = [
"wgpu",
]
[[package]]
name = "raea-runtime-goal-plan"
version = "0.1.0"
dependencies = [
"raea-core-brief",
"serde_json",
]
[[package]]
name = "raea-runtime-gpuframe"
version = "0.1.0"
@@ -16429,11 +16436,22 @@ dependencies = [
"raea-io-home",
"raea-io-media",
"raea-io-trace",
"raea-sys-mix-device",
"raea-sys-mix-level",
"raea-sys-tone",
"serde_json",
]
[[package]]
name = "raea-sys-mix-device"
version = "0.1.0"
dependencies = [
"audioadapter-buffers",
"cpal 0.15.3",
"firewheel",
"raea-io-trace",
]
[[package]]
name = "raea-sys-mix-level"
version = "0.1.0"
@@ -20409,8 +20427,6 @@ dependencies = [
[[package]]
name = "taffy"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c8480887e8803986d96a7173729565520d4bbb721ad6b7ad6941a22897207aa"
dependencies = [
"serde",
"slotmap",
+10
View File
@@ -86,6 +86,7 @@ members = [
"systems/tone",
"systems/mix",
"systems/mix/level",
"systems/mix/device",
"systems/ml",
"systems/mlx",
"systems/kimodo",
@@ -195,6 +196,7 @@ members = [
"runtime/endchecks",
"runtime/lod-plan",
"runtime/cut-plan",
"runtime/goal-plan",
"runtime/live",
"runtime/page",
"runtime/appscreen",
@@ -345,6 +347,10 @@ split-debuginfo = "packed"
[patch.crates-io]
# the MP4 muxer, vendored
muxide = { path = "vendor/muxide" }
# metis-sys 0.3.2 (bevy_pbr's meshlets) with GKlib's own stdint.h and inttypes.h stand-ins used only before Visual
# Studio 2013: Visual Studio 18's stdint.h types int_fast16_t differently, and every C file failed (raea#82; the change
# is marked "raea:" in vendor/GKlib/gk_arch.h). Its test graphs, manual and programs are left out
metis-sys = { path = "vendor/metis-sys" }
# usvg 0.48.1 spacing a chunk's last letter as Chrome does (changes marked "raea:", docs/layout-reads.feature LR10)
usvg = { path = "vendor/usvg" }
# bevy_seedling 0.8.0 without its cpal 0.18 paths, ported to Bevy 0.20 (changes marked "raea:")
@@ -401,6 +407,10 @@ vello_encoding = { path = "vendor/vello_encoding" }
# (changes marked "raea:"): raea-page blends a bevy_ui page as Bevy does (bevy_ui on Blitz). No upstream
# equivalent yet (linebender/vello blends the encoded values).
vello_shaders = { path = "vendor/vello_shaders" }
# taffy 0.15.0 (Blitz's, Bevy UI's, rune-taffy's) with a flex line whose items overflow its container by less than
# Chrome's layout unit, 1/64 px, kept on one line: f32 rounding wrapped items that add up to the container's width
# (changes marked "raea:", raea #252). Back to upstream once Taffy breaks flex lines with a tolerance.
taffy = { path = "vendor/taffy" }
# Firewheel 0.12 on Bevy 0.20: bevy_reflect 0.20 and a glam-33 feature (BillyDM/Firewheel#144; changes marked "raea:")
firewheel = { path = "vendor/firewheel" }
firewheel-core = { path = "vendor/firewheel-core" }
+4 -4
View File
@@ -32,10 +32,10 @@
---
> **0.1.6** (17 November 2026) is the latest release: the engine and the desktop app on macOS (Apple Silicon), Linux
> (x86_64) and, newest and least tested, Windows 10 and 11 (x86_64). raea is young and moves fast, with a release most
> days since 0.1.1 on 11 November: expect rough edges, and tell us what you hit in an
> [issue](https://github.com/shinyobjectz/raea/issues), or from your agent with `raea bug`.
> raea releases experimentally and often, so the newest release is always on
> [Releases](https://github.com/shinyobjectz/raea/releases). The app is unstable for now, especially on Linux and
> Windows: expect rough edges, and tell us what you hit in an [issue](https://github.com/shinyobjectz/raea/issues), or
> from your agent with `raea bug`.
## The app
+2
View File
@@ -15,6 +15,8 @@ raea-core-facts = { path = "../../core/facts" }
raea-runtime-lod-plan = { path = "../../runtime/lod-plan" }
# a cut job's gates: its client's brief as rules, held over the delivered files (MK25-MK27)
raea-runtime-cut-plan = { path = "../../runtime/cut-plan" }
# a goal job's gates: its commands and a fresh critic's verdict on its words (/goal)
raea-runtime-goal-plan = { path = "../../runtime/goal-plan" }
# the judge's rounds, passes and blocking defects, read as it keeps them
raea-app-judge = { path = "../judge" }
# the make questions, their calibrations and a sheet's ident, as raea ask keeps them (MK4)
+4 -2
View File
@@ -19,7 +19,8 @@ use std::path::{Path, PathBuf};
use raea_core_brief::make::Make;
use serde_json::Value;
pub const USAGE: &str = "raea make status [DIR] [--json] [--plan] (a scene, kit or shot held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
pub const USAGE: &str = "raea make status [DIR] [--json] [--plan] (a scene, kit, shot, cut or goal held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
raea make judge [DIR] [--by claude|kimi] (a goal job: a fresh critic, which only reads, judges each `says` rule; review/goal.judge.json)
raea make plan [DIR] [--no-review] (the plan stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
raea make refs [DIR] [--only ID,...] [--model M] [--dry] (a kit: every object's reference from the style images, in the plan's style, then review/refs.png; --dry quotes it)
raea make sheet refs [DIR] (review/refs.png again: the style images, then every reference)
@@ -102,7 +103,7 @@ pub fn status_in(dir: &Path) -> Result<Option<Value>, String> {
}
/// The flags that take a value: what follows them isn't a positional argument.
const VALUED: [&str; 7] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out"];
const VALUED: [&str; 8] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out", "--by"];
fn flag<'a>(args: &'a [String], k: &str) -> Option<&'a str> {
args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).map(String::as_str)
@@ -184,6 +185,7 @@ fn step(verb: &str, args: &[String]) -> Result<String, String> {
pub fn cli(args: &[String]) -> Result<String, String> {
match args.get(1).map(String::as_str) {
Some("status") => {}
Some("judge") => return job(&PathBuf::from(positional(args, 2).first().map_or(".", String::as_str))).and_then(|(b, m)| raea_runtime_goal_plan::judge(m.goal.as_ref().ok_or("raea make judge: the job isn't a goal({...})")?, b.parent().unwrap_or(Path::new(".")), flag(args, "--by").unwrap_or("claude")).map(|v| serde_json::to_string_pretty(&v).unwrap_or_default())),
Some(v @ ("plan" | "refs" | "sheet" | "gen" | "pick-sheet" | "pick" | "prep" | "kit" | "framing" | "lenschart")) => return step(v, args),
_ => return Err(USAGE.into()),
}
+9 -7
View File
@@ -1,8 +1,7 @@
//! Whether a job is done (docs/make.feature MK1), from what's on disk and nothing the agent says: the deliverables, the
//! notes, the record of renders and checks, and the judge's rounds. Pure over a `Job` so it is tested on fixtures.
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use std::{path::{Path, PathBuf}, time::SystemTime};
use raea_core_brief::make::{self, Make};
use raea_core_facts::{Level, record::Entry};
@@ -143,7 +142,7 @@ fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
let what = match job.make.kind {
make::Kind::Kit => "raea render shared/components/KIT/lineup.tsx --review review/r1",
make::Kind::Shot => "raea make framing --out review/r1",
make::Kind::Scene | make::Kind::Cut => "raea render EDIT.tsx --review review/r1",
make::Kind::Scene | make::Kind::Cut | make::Kind::Goal => "raea render EDIT.tsx --review review/r1",
};
return vec![gate("critic", None, false, format!("no round yet: {what}, then raea judge review/r1 --kind {kind} --by claude --brief brief.ts"))];
};
@@ -183,14 +182,16 @@ pub fn status(job: &Job) -> Value {
}
}
let notes = notes_text(job.dir).unwrap_or_default();
if !notes.to_lowercase().contains(&SKILL_HEADING.to_lowercase()) {
if job.make.kind != make::Kind::Goal && !notes.to_lowercase().contains(&SKILL_HEADING.to_lowercase()) {
missing.push(format!("NOTES.md with a \"{SKILL_HEADING}\" section (one line per thing that cost time; what the guide got wrong for this job)"));
}
let mut gates = checks(job);
gates.extend(lods(job, &notes));
// a cut job: its brief's rules over every delivered file (MK25-MK27), and the person's review its critic; a goal's
let plan = |g: make::Gate| gate(g.name, g.of.as_deref(), g.clear, g.says);
match (&job.make.cut, job.make.kind) {
// a cut job: its brief's rules over every delivered file (MK25-MK27), and the person's review its critic
(Some(c), make::Kind::Cut) => gates.extend(raea_runtime_cut_plan::gates(c, job.dir).into_iter().map(|g| gate(g.name, g.of.as_deref(), g.clear, g.says))),
(Some(c), make::Kind::Cut) => gates.extend(raea_runtime_cut_plan::gates(c, job.dir).into_iter().map(plan)),
(_, make::Kind::Goal) => gates.extend(job.make.goal.iter().flat_map(|g| raea_runtime_goal_plan::gates(g, job.dir)).map(plan)),
_ => gates.extend(critic(job, newest, &notes)),
}
let (asks, said) = crate::asked::gates(&sheets(job), job.ledger, &notes);
@@ -215,6 +216,7 @@ pub fn status(job: &Job) -> Value {
"gates": gates,
"judge": {"rounds": job.rounds.len(), "cap": cap, "passesInARow": advice["passesInARow"], "changeApproach": advice["stall"], "again": advice["again"]},
"plan": make::doctor(job.make),
"files": {"deliverables": make::deliverables(job.make), "previews": make::previews(job.make)},
"advice": said,
"why": why,
})
@@ -239,6 +241,6 @@ pub fn text(s: &Value) -> String {
t.push(format!(" {} {}{of}: {}", if g["clear"] == true { "ok " } else { "open" }, g["gate"].as_str().unwrap_or(""), g["says"].as_str().unwrap_or("")));
}
let j = &s["judge"];
t.push(format!("judge: {} of {} rounds, {} passes in a row{}", j["rounds"], j["cap"], j["passesInARow"], if j["changeApproach"] == true { "; the same defect keeps coming back: change the approach for that part, not the dose" } else { "" }));
if s["kind"] != "goal" { t.push(format!("judge: {} of {} rounds, {} passes in a row{}", j["rounds"], j["cap"], j["passesInARow"], if j["changeApproach"] == true { "; the same defect keeps coming back: change the approach for that part, not the dose" } else { "" })); }
t.join("\n")
}
+7
View File
@@ -93,6 +93,10 @@ pub struct Phrase {
pub struct Cta {
pub text: String,
pub from: String,
/// the other lines a brief rotates (two host lines, a paid take's): any one lands it, each found in the brief
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub also: Vec<String>,
/// how near the end it must land, in seconds (8 when left out)
pub within: Option<f64>,
}
@@ -151,6 +155,9 @@ pub fn quotes(c: &Cut) -> Vec<(String, &str)> {
}
if let Some(cta) = &c.cta {
q.push(("cta".into(), &cta.from));
for line in &cta.also {
q.push((format!("cta \"{line}\""), line));
}
}
for o in &c.open {
q.push((format!("open \"{}\"", o.question), &o.from));
+67
View File
@@ -0,0 +1,67 @@
//! A goal job's contract: `make: goal({...})` on brief.ts, the person's goal written as rules before the work starts
//! (11-26, Shane: "we essentially just need to make sure that it can't stop unless all the goals pass, or all the rules
//! in the brief"). `/goal` in raea.app and an agent's own goal are this: the goal in the person's words, then each
//! thing that must hold, as a command that must pass, a file that must exist, or words a fresh critic must find true.
//! `raea make status` (runtime/goal-plan) decides from them whether the agent may stop; the agent saying so never does.
use serde::{Deserialize, Serialize};
use ts_rs::TS;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeGoal")]
pub struct Goal {
/// the goal as the person said it
pub goal: String,
/// what must hold before the agent may stop: every one, each checked in code or by a fresh critic
#[serde(default)]
#[ts(as = "Option<Vec<GoalRule>>", optional)]
pub rules: Vec<GoalRule>,
}
/// One thing that must hold. Exactly one of `run`, `file` or `says`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "MakeGoalRule")]
pub struct GoalRule {
/// a short name: [a-z0-9_], how status, the critic and NOTES.md name it
pub id: String,
/// a command that must exit 0, run in the brief's folder (`bun test`, `raea check edit.tsx`)
pub run: Option<String>,
/// the seconds `run` gets before it counts as failed (300 when left out)
pub timeout: Option<u32>,
/// a file that must exist, relative to the brief (`a|b`: either; `dir/`: three or more pictures in it)
pub file: Option<String>,
/// words that must be true of the work, judged by a fresh critic (`raea make judge`), never by the agent that did it
pub says: Option<String>,
}
/// What the goal's rules still lack, each with what to do. Empty when it's ready.
pub fn doctor(g: &Goal) -> Vec<String> {
let mut out = Vec::new();
if g.goal.trim().is_empty() {
out.push("no `goal`: the goal in the person's own words".into());
}
if g.rules.is_empty() {
out.push("no `rules`: what must hold before you stop, each a `run` command, a `file` or words a critic judges (`says`)".into());
}
let mut seen = std::collections::BTreeSet::new();
for r in &g.rules {
if !crate::make::is_name(&r.id) {
out.push(format!("rule `{}`: ids are [a-z0-9_]", r.id));
}
if !seen.insert(r.id.as_str()) {
out.push(format!("rule `{}` is listed twice", r.id));
}
let n = [r.run.is_some(), r.file.is_some(), r.says.is_some()].iter().filter(|x| **x).count();
if n != 1 {
out.push(format!("rule `{}` needs exactly one of `run`, `file` or `says` (it has {n})", r.id));
}
if r.timeout.is_some() && r.run.is_none() {
out.push(format!("rule `{}` has a `timeout` but no `run`", r.id));
}
}
out
}
+2
View File
@@ -5,6 +5,7 @@
pub mod brief;
pub mod cut;
pub mod goal;
pub mod make;
pub mod parts;
pub mod script;
@@ -41,6 +42,7 @@ pub fn declarations() -> String {
parts::Parts, parts::Concept, parts::Level, parts::Count, parts::Part,
make::Make, make::Kind, make::Source, make::DialValue, make::Dial, make::Route, make::Origin, make::Pick, make::Object, make::Shot,
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open,
goal::Goal, goal::GoalRule,
));
out.join("\n\n") + "\n"
}
+34 -1
View File
@@ -21,6 +21,8 @@ pub enum Kind {
Shot,
/// ads cut from footage to a client's brief: its deliverables, phrases, claims and CTA as rules (cut.rs, MK25)
Cut,
/// any other work held to a goal: commands that must pass, files that must exist, words a critic judges (goal.rs)
Goal,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
@@ -56,6 +58,13 @@ pub struct Make {
pub rounds: Option<u32>,
/// a cut job's contract: the brief as rules (cut.rs)
pub cut: Option<crate::cut::Cut>,
/// a goal job's contract: the goal and its rules (goal.rs)
pub goal: Option<crate::goal::Goal>,
/// what the job shows but never delivers, relative to the brief (pictures, render tests, examples): each a file or a
/// `dir/` (review/ and previews/ when left out). Deliverables are what it hands over; previews are how it got there
#[serde(default)]
#[ts(as = "Option<Vec<String>>", optional)]
pub previews: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
@@ -194,7 +203,7 @@ impl Kind {
/// as brief.ts writes it, and as raea judge's rubrics are named
pub fn name(self) -> &'static str {
// in the enum's order
["scene", "kit", "shot", "cut"][self as usize]
["scene", "kit", "shot", "cut", "goal"][self as usize]
}
}
@@ -205,6 +214,7 @@ pub fn dials(kind: Kind) -> &'static [&'static str] {
Kind::Kit => &["count", "variety", "detail", "wear", "wetness", "warmth", "look"],
Kind::Shot => &["res", "seconds", "lens", "handheld", "look"],
Kind::Cut => &["look"],
Kind::Goal => &[],
}
}
@@ -232,9 +242,16 @@ pub fn deliverables(m: &Make) -> Vec<String> {
// a shot is a still or a move, so either file answers; apps/make reads `a|b`
Kind::Shot => m.shots.iter().map(|s| format!("out/shots/{0}.png|out/shots/{0}.mp4", s.name)).collect(),
Kind::Cut => m.cut.as_ref().map(crate::cut::deliverables).unwrap_or_default(),
// a goal's `file` rules
Kind::Goal => m.goal.iter().flat_map(|g| &g.rules).filter_map(|r| r.file.clone()).collect(),
}
}
/// What the job shows but doesn't deliver: the plan's own list, else review/ and previews/.
pub fn previews(m: &Make) -> Vec<String> {
if m.previews.is_empty() { vec!["review/".into(), "previews/".into()] } else { m.previews.clone() }
}
/// A name a file lands as: [a-z0-9_], not empty.
pub fn is_name(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
@@ -258,6 +275,12 @@ pub fn doctor(m: &Make) -> Vec<String> {
(Some(_), k) => out.push(format!("`cut` is for a cut job, not a {k:?}: drop it, or make this `cut({{...}})`")),
_ => {}
}
match (&m.goal, m.kind) {
(Some(g), Kind::Goal) => out.extend(crate::goal::doctor(g)),
(None, Kind::Goal) => out.push("no `goal`: the goal in the person's words and its `rules`".into()),
(Some(_), k) => out.push(format!("`goal` is for a goal job, not a {k:?}: drop it, or make this `goal({{...}})`")),
_ => {}
}
if m.kind == Kind::Kit && m.style.is_none() {
out.push("no `style`: one paragraph (era, palette, materials, wear, one fictional maker) every reference carries".into());
}
@@ -295,3 +318,13 @@ pub fn doctor(m: &Make) -> Vec<String> {
}
out
}
/// One gate as `raea make status` lists it: its name, the file, item or rule it's about, whether it's clear, and what
/// it says. A cut's gates come from raea-runtime-cut-plan, a goal's from raea-runtime-goal-plan.
#[derive(Debug, Clone, PartialEq)]
pub struct Gate {
pub name: &'static str,
pub of: Option<String>,
pub clear: bool,
pub says: String,
}
+101
View File
@@ -0,0 +1,101 @@
@spec
Feature: raea cloud: a synced folder is pictured, understood, embedded and organized for the person
Shane, 2026-11-24: "when i have a data sync, we should auto index/tag and relate them to the appropriate folders or
have an ai agent or our ask/decision model api if available otherwise use their subscription agent and tag or
auto-organize the assets or files or folders so we can help understand what purpose they are for and predict what
they mean/do. also make sure we embed all the assets based on embedding type. this will mean if we have a client
library, we want to relate a client based folder to that library, or if disorganized we go file by file."
Later that day: "we should be able to pick a folder from a sync location and have all content when syncing
auto-tagged and organized for the user", "make sure thumbnails are also generated correctly", and of the models:
"isn't it running the models in modal?"
Today (11-24) a sync lists its folder through Composio and adds each file as a link item, all in one flat folder,
named and typed from its name and mime type only. Search embeds words (Workers AI's bge-small) and nothing else; no
file is tagged; pictures came from drive.google.com in the viewer's browser, so a viewer signed out of Google saw
none. The first real client demo is StreetTalk's: workspace streettalk, its Main library's "raea test — StreetTalk
samples (Nov 2026)" Drive folder (54 files: 47 videos, 6 documents, 1 picture) and three client libraries (Dutch,
Elfster, The Body Shop), each with a Drive folder of its own.
Background:
Given a workspace with Google Drive (or Box, Dropbox, Frame.io, Slack) connected through Composio
And raea never moves, renames or deletes anything in the tool: organizing happens in raea's library only
Rule: a folder is picked, and its shape comes with it
Scenario: IG1. A sync is a folder picked from the tool's own list
When the person adds a sync and picks a folder from Drive's list (syncadd.js)
Then the sync keeps the folder's id and its name; a folder typed as its id or its Drive link works the same,
and is named for the folder on its first run (built 11-24: sync-run.ts driveId, NAME)
Scenario: IG2. Subfolders come in as folders
Given the picked folder holds subfolders ("Raw/Angle 1", "Finals")
Then each becomes a library folder under the sync's folder, with the same name and nesting, and each file lands
in its own; a file moved between subfolders in the tool moves in raea on the next run
Rule: every file has a picture anyone who can see the library sees
Scenario: IG3. A synced file's picture is kept by raea
When a run lists a file that has a picture in its tool (Drive's thumbnailLink; Box's and Dropbox's thumbnails)
Then raea fetches it once at 640 px and keeps it in the workspace's own store (items.thumb, the API's signed
thumb_src), 60 a run, a failed fetch tried again on the next run (built 11-24 for Drive)
And the library's card shows it, with a play mark on a video; a tool's page address is never put in a <video>
Scenario: IG4. A file with no picture in its tool gets one made
Given a video, PDF or document the tool has no picture of
Then a frame (a video's at 10% of its length), a first page or a typeset title card is made on Modal (IG8) and
kept the same way
Rule: every file is understood
Scenario: IG5. Each new file is read by its kind
When a run brings files in
Then each is read once per version (its tool's modified time or checksum): a picture by its picture; a video by
its picture, frames at 10/50/90% and its words (transcribed); a document by its text (Drive exports Docs as
text, PDFs are read); a sound by its words or, with none, what it sounds like
And what it says about the file is kept on the item: a one-line description, tags (its kind: raw footage, b-roll,
a final cut, a brief, a script, a logo, a voiceover, a reference; its subject; its client or brand; its format,
9x16 or 16x9; its length), and for each tag who said it and why
Scenario: IG6. raea's model reads first; the workspace's agent when there's none
(built 11-24 with raea's model as a vision model on OpenRouter, tagger.ts: description, role, client, tags with
why, on the item and its turbopuffer rows; raea ask's clef model takes its place when it's deployed)
Given the workspace's plan has raea's ask model (raea ask, docs/ask.feature: clef-omni on the plan's pool)
Then the files are read by it, batched, the spend on the pool
Otherwise they are read by the workspace's own connected agent on raea cloud's box (Claude Code on its Claude, or
Antigravity on its Google AI plan), as a background job that never takes a project's turn
And with neither, files are tagged from their names, folders and types alone, and the library says how to get more
Scenario: IG7. A person's correction wins
When someone removes or changes a tag, or moves a file to another folder
Then raea never puts it back, and the next files like it are read with that correction in the prompt
Rule: every file is embedded by its kind, once, into turbopuffer (Enterprise)
Scenario: IG8. raea's own library indexer runs on Modal and writes to turbopuffer
Then each file is indexed by the desktop's own indexer (apps/app host/library/index-file.ts, in the cloud
indexer's image: EmbeddingGemma 2 for pictures, shots, sound and words, TransNetV2 cuts, Whisper; a document's
text in windows), as a job on Modal (ingest.py index_job, any length), so a desktop's and the cloud's vectors
compare; EmbeddingGemma 2 on a GPU (RAEA_INDEX_GPU=L4: fp16, CUDA 13) while there's work, else the CPU at q8
And its rows go to turbopuffer in raea-api's layout, one namespace a workspace (raea-cloud-<workspace>.
embeddinggemma-2@768), a row per segment and modality, replaced when the file is indexed again
And only an Enterprise workspace is indexed in the cloud (raea cloud is Enterprise only, Shane 11-24); the raea
app's Pro and Team plans embed on their own computers and keep their index in turbopuffer through raea-api,
Free on the Mac
(built 11-24: index-run.ts, tools/library-index cloud.ts, cloud-cli.ts, cloud-server.ts)
Scenario: IG9. Search finds a file by what's in it
(built 11-24: search.ts deep, turbopuffer's nearest segments, a hit's at {t0, t1})
When the person searches "girl laughing on a street corner, vertical"
Then the words are matched against pictures and frames (SigLIP's text tower), descriptions and transcripts, and
tags, fused into one ranking; a hit says where in a video it is
Rule: the files are organized for the person
Scenario: IG10. A folder about a client goes with that client's library
Given a synced folder whose name, or most of whose files, are about one of the workspace's clients
Then the sync is related to that client's library (or its files are, when the folder is the workspace's), shown
with the reason ("47 of 54 files show The Body Shop's products"), and undone in one click
Scenario: IG11. A disorganized folder is sorted file by file
Given a folder of files with no useful subfolders
Then raea proposes folders (by client, then by kind: Raw, B-roll, Finals, Briefs) with each file's place and
reason, as one review the person accepts whole, or file by file; nothing moves until they do
And once accepted, new files that fit are placed the same way on later runs
Rule: the person can see it working
Scenario: IG12. The left panel says what a sync is doing
Then a sync bringing files in turns in the left panel, on its row and its library's (built 11-24), then says
"Reading 12 of 54" while files are read, and its card shows the tags as they come
Scenario: IG13. Proven on StreetTalk's demo
When StreetTalk's four Drive syncs run from empty
Then every file has a picture, a description and tags; the three client folders are related to their client
libraries; a search for a shot finds it by what's in it; and the run says its time and what it cost
+33 -1
View File
@@ -260,7 +260,8 @@ Feature: Make: scenes, kits and shots built to a frozen plan and held to a revie
Then core/brief reads `cut` (cut.rs): `brief` (that text), `count` (how many cuts the brief asks for), `seconds`
and `formats`, each cut (id, angle, solo or mashup, hook, captions or a text hook, its own formats and length),
`say` (phrases every cut says or shows, or one cut with `every: false`), `never` (phrases no cut says or
shows), `cta` (the line every cut ends on, within its last 8 s) and `open` (the brief's [TO CONFIRM] items)
shows), `cta` (the line every cut ends on, within its last 8 s; `also`: the other lines a brief rotates, any
one of which lands it, each found in the brief) and `open` (the brief's [TO CONFIRM] items)
And every rule has `from`: the brief's own words for it
And each cut lands at a fixed path, out/cuts/<id>_<W>x<H>.mp4 for each of its formats
And `doctor` names what the contract still lacks: no count, no cta, an id that isn't [a-z0-9_], a format that
@@ -286,6 +287,37 @@ Feature: Make: scenes, kits and shots built to a frozen plan and held to a revie
error: no face cut by the frame or a seam, no text under the size floor ("frames")
And the cut job has no critic tier yet: the person's review is its critic
Rule: any goal, held to rules (MK28-MK29)
Shane, 11-26, asking whether raea make is just a version of /goal: "when we use these things, they should just
probably be consolidated into one workflow, because in any case we'll have a goal or a brief or something that
dictates what we need. And then we essentially just need to make sure that it can't stop unless all the goals pass,
or all the rules in the brief". /goal in raea.app's chat let the agent end the loop by writing "GOAL MET"; a goal it
can declare met is advice. So /goal and raea make are one loop: a goal is a fifth kind of job, its words become
rules in brief.ts before the work starts, and only `raea make status` says it's met.
@needs:MK2
Scenario: MK28. A goal as rules: `make: goal({...})`
Given work that isn't a scene, kit, shot or cut (fix a bug, write a page, ship a change)
When the agent writes `make: goal({ goal: "the person's words", rules: [...] })` before it starts
Then core/brief reads `goal` (goal.rs): the goal as the person said it, and `rules`, each an id and exactly one of
`run` (a command that must exit 0 in the brief's folder, within `timeout` seconds, 300 by default), `file` (a
file that must exist: a deliverable) or `says` (words that must be true of the work)
And `doctor` names what it lacks: no goal, no rules, an id that isn't [a-z0-9_] or is listed twice, a rule with
none or more than one of run, file and says, a timeout with no run
And a goal job needs no NOTES.md "What the skill got wrong" section (no skill made it) and has no render critic
@needs:MK28
Scenario: MK29. Held by a command's exit and a fresh critic, never the agent's word
Given a goal job
Then `raea make status` runs every `run` rule at every status, the Stop hook's included, and holds the job on one
that fails or outlives its timeout, with its exit code and last line ("run")
And a `says` rule is clear only when review/goal.judge.json, written by `raea make judge [DIR] [--by claude|kimi]`
(a fresh session that may only read: Read, Grep and Glob), found it true at a time no earlier than the work's
newest file, the job's own review/, .raea/, NOTES.md, .git and node_modules left out, compared at whole seconds
("says")
And `file` rules are its deliverables, listed under missing
And raea.app's /goal is this job: it writes the rules first, and only the status ends the loop
Rule: raea cloud (MK19-MK20)
@needs:MK2 @done
+3 -2
View File
@@ -66,7 +66,9 @@ else throws a SyntaxError, as Chrome's does.
that doesn't load rejects, and the text falls back.
- `window` has `innerWidth`, `innerHeight` and `devicePixelRatio` for the composition's size, and `getComputedStyle`.
- `requestAnimationFrame` calls back once per frame drawn, given that frame's time, so a frame drawn again gets the
same calls. `new Image()` fires `load` when its `src` is set, with no pixel size.
same calls. `new Image()` fires `load` when its `src` is set (a `staticFile` path, a data: URL or an http URL), and
by then `naturalWidth` and `naturalHeight` are the picture's size; `width` and `height` are the ones you gave, else
the same. A file that isn't there fires `error` instead.
- `ResizeObserver` calls back once when it starts observing, then after any layout that changed an observed element's
size, with `contentRect`, `borderBoxSize` and `contentBoxSize`.
@@ -75,7 +77,6 @@ else throws a SyntaxError, as Chrome's does.
- `MutationObserver` and `IntersectionObserver` exist, so a component that makes one doesn't throw, but they never
call back.
- An `<img>`'s `onError` never fires: an image that doesn't load fails the render, naming its src.
- `new Image()` has no `naturalWidth` or `naturalHeight` (they stay 0).
- An element has no `innerHTML` or `outerHTML`: read `textContent`, or walk `children` and `childNodes`.
- A Range across wrapped lines is one rect, not one per line, and an inline element's `getClientRects()` is one rect
too.
+22 -2
View File
@@ -5,7 +5,7 @@ order: 44
sources: ["apps/make/src/lib.rs", "apps/make/src/status.rs", "apps/make/src/asked.rs", "apps/make/src/plan.rs", "apps/make/src/kit.rs", "apps/make/src/kitout.rs", "apps/make/src/shots.rs", "apps/make/src/floor.rs", "apps/make/src/sheet.rs", "core/brief/src/make.rs", "apps/check/make/src/lib.rs"]
---
`raea make status` reads the job on a project's brief.ts (`make: scene({...})`, `kit({...})` or `shot({...})` from
`raea make status` reads the job on a project's brief.ts (`make: scene({...})`, `kit({...})`, `shot({...})`, `cut({...})` or `goal({...})` from
`raea/brief`) and says what's still missing, from what's on disk and never from what the agent says:
- the kind's deliverables (a scene's three or more stills; a kit's GLB, LOD1 and thumbnail per object, its lineup
@@ -26,6 +26,24 @@ sources: ["apps/make/src/lib.rs", "apps/make/src/status.rs", "apps/make/src/aske
An answer counts for the sheet it was asked of, matched by the file's bytes, so a sheet rendered again is asked
again.
A goal job (`goal({...})`, what raea.app's `/goal` writes) is any other work: the goal 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 (status runs
it every time, 300 seconds unless its `timeout` says otherwise); a `file` rule is a deliverable; a `says` rule is
words that must be true of the work, judged by a fresh critic that may only read: `raea make judge` asks one
(`--by claude` or `kimi`) and keeps its verdict in review/goal.judge.json, and the rule clears only while that verdict
is no older than the work's newest file. A goal job needs no NOTES.md section and has no render critic.
```ts
make: goal({
goal: "the export plays and the README says how to run it",
rules: [
{ id: "tests", run: "bun test" },
{ id: "export", file: "out/final.mp4" },
{ id: "readme", says: "README.md says how to install and run it, in order" },
],
}),
```
`--plan` writes the gates as check lines under the job's own task in the project's plan.org, keeping the person's
mark (DONE, DROPPED) and their own lines; the Stop hook runs it so.
@@ -80,7 +98,8 @@ raea make lenschart counter_push
## Usage
```sh
raea make status [DIR] [--json] [--plan] (a scene, kit or shot held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
raea make status [DIR] [--json] [--plan] (a scene, kit, shot, cut or goal held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)
raea make judge [DIR] [--by claude|kimi] (a goal job: a fresh critic, which only reads, judges each `says` rule; review/goal.judge.json)
raea make plan [DIR] [--no-review] (the plan stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)
raea make refs [DIR] [--only ID,...] [--model M] [--dry] (a kit: every object's reference from the style images, in the plan's style, then review/refs.png; --dry quotes it)
raea make sheet refs [DIR] (review/refs.png again: the style images, then every reference)
@@ -99,6 +118,7 @@ Headless: it needs nothing running and opens no window. Takes up to 5 arguments
| Flag | Takes | What it does |
| --- | --- | --- |
| `--by` | `claude\|kimi` | The critic `judge` asks, a fresh session that may only read (default `claude`). |
| `--dry` | – | Quote the generation (refs, gen) and make nothing. |
| `--json` | – | Print the status as JSON: missing, gates, judge, done, short and why. |
| `--meshy` | `M` | The Meshy model for `gen` (default `fal:meshy/v7.1/image-to-3d`). |
+25 -3
View File
@@ -30,10 +30,10 @@ See [Workspaces and projects](../../concepts/workspaces.md) for where each spec
<!-- generated:begin by tools/manual-ref/sdk.ts from the SDK's exports and doc comments; edit outside this block -->
```ts
import { brief, cut, fingerprint, kit } from "raea/brief"
import { brief, cut, fingerprint, goal } from "raea/brief"
```
`raea/brief` exports 9 functions, 40 types. Source: [sdk/raea/src/brief.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/brief.ts).
`raea/brief` exports 10 functions, 42 types. Source: [sdk/raea/src/brief.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/brief.ts).
## Functions
@@ -62,6 +62,16 @@ A fingerprint (fingerprint.ts): its axes and the encoders its heads were trained
function fingerprint(f: Fingerprint): Fingerprint
```
### `goal`
any other work held to a goal (`/goal`): the goal in the person's words and the rules that must hold before the agent
stops, each a command that must pass (`run`), a file that must exist (`file`) or words a fresh critic judges
(`says`, by `raea make judge`). `raea make status` holds the agent to every one.
```ts
function goal({ goal, rules, ...m }: MakeGoal & Omit<Make, "kind" | "goal">): Make
```
### `kit`
A kit: props in one style at real size (`style` is the paragraph every reference carries: era, palette, materials,
@@ -243,10 +253,22 @@ type MakeDial = MakeDialValue | { value: MakeDialValue, source?: MakeSource, /**
type MakeDialValue = number | string
```
### `MakeGoal`
```ts
type MakeGoal = { /** * the goal as the person said it */ goal: string, /** * what must hold before the agent may stop: every one, each checked in code or by a fresh critic */ rules?: Array<MakeGoalRule>, }
```
### `MakeGoalRule`
```ts
type MakeGoalRule = { /** * a short name: [a-z0-9_], how status, the critic and NOTES.md name it */ id: string, /** * a command that must exit 0, run in the brief's folder (`bun test`, `raea check edit.tsx`) */ run?: string, /** * the seconds `run` gets before it counts as failed (300 when left out) */ timeout?: num…
```
### `MakeKind`
```ts
type MakeKind = "scene" | "kit" | "shot" | "cut"
type MakeKind = "scene" | "kit" | "shot" | "cut" | "goal"
```
### `MakeObject`
+1 -1
View File
@@ -33,7 +33,7 @@ The composition, the app, and the specs and notes an agent writes.
| --- | --- | --- |
| [`raea`](raea.md) | The main entry: compositions, sequences, time, interpolation, springs, footage, sound and words. | 21 components, 9 hooks, 65 functions, 11 values, 109 types |
| [`raea/app`](app.md) | The App, its plugins and schedules, and the registry a video's compositions are kept in. | 1 component, 1 hook, 5 functions, 3 classes, 17 values, 18 types |
| [`raea/brief`](brief.md) | The specs an agent writes as data: brief, script, taste and an object's parts, checked against raea's schemas. | 9 functions, 40 types |
| [`raea/brief`](brief.md) | The specs an agent writes as data: brief, script, taste and an object's parts, checked against raea's schemas. | 10 functions, 42 types |
| [`raea/note`](note.md) | A person's note as a file in the project: their words kept as written, and the asks the agent restates it as. | 1 function, 4 types |
## Time and motion
+81
View File
@@ -0,0 +1,81 @@
---
title: "raea 0.1.11"
version: "0.1.11"
date: "2026-11-26"
summary: "A goal is a make job, judged by its own commands and a fresh critic. Live sound follows your output device, a picture taller than the GPU's largest texture draws, and Windows on ARM gets raea's installer and its own build. In the app, typing to Ideate answers with your own agent, there is one Settings page, and voice comes with Studio."
sources: ["https://github.com/shinyobjectz/raea/releases/tag/v0.1.11"]
---
raea 0.1.11 makes a goal something `raea make` holds an agent to: the goal's own commands and a critic that only
reads decide when it's done, never the agent's word. Live sound now follows the output you're listening on, a very
tall picture draws instead of being refused, and Windows on ARM PCs get raea's installer and a build of their own. In
the app, typing to Ideate answers with the agent you connected, Settings are one page, and talking with Ideate comes
with Studio.
**Get the app at [raea.io](https://raea.io)** (a Mac with Apple silicon, Windows 10 or 11, or Linux on x86_64).
The engine alone:
```sh
curl -fsSL https://raea.io/install | sh
```
On Windows, in PowerShell: `irm https://raea.io/install.ps1 | iex`.
## What changed since 0.1.10
**A goal is a make job.** Besides scenes, kits, shots and cuts, `make: goal({...})` in `brief.ts` is a fifth kind of
job (MK28-MK29). Its rules are commands that must pass and things it must say, and `raea make judge` has a fresh
critic, which only reads, judge each `says` rule into `review/goal.judge.json`. `raea make status` is the one judge
of whether the goal is met.
**Cuts from a brief rotate their call to action.** A `cut` brief's `cta.also` lists the other lines a brief rotates,
and each cut ends on one of them within its last 8 seconds (MK25).
**Live sound follows your output.** When the system's output changes (headphones, AirPods, a display) or the stream
breaks, live sound reopens on the device in use instead of going quiet.
**A tall picture draws (#245).** A picture larger than the GPU's image atlas (a 1080 x 18000 site capture drawn 880
wide) was refused with a message about a filtered layer. It is now decoded at a size that fits the atlas, which is
16384 px a side even on a GPU that allows larger textures.
**Windows on ARM (#82).**
- `irm https://raea.io/install.ps1 | iex` installs on an ARM64 PC: raea's ARM64 build when the release has one, else
the x86_64 build, which Windows 11 on ARM runs emulated. Before, the installer refused ARM64 PCs.
- raea is built natively for Windows on ARM (`raea-0.1.11-windows-arm64.zip`) when its build passes, beside the
release's other archives.
- On a Snapdragon PC, raea picks DirectX 12 for its Adreno GPU, where Vulkan drew 2D pages striped and with grey boxes
behind fading text.
**In the app.**
- Typing to Ideate answers with your own agent (Claude, Codex, or whichever you connected), named on screen while it
thinks, and the conversation stays open instead of fading after a few seconds. raea's own voice model is only for
speaking.
- Talking with Ideate comes with Studio (300 minutes a month) and Enterprise (no limit). Free and Pro type.
- Settings are one page: your workspace's sections, then this computer's (account, plan, sharing, general, storage
and debugging), searched together.
- Signing out on the Mac's workspace signs raea's account out, and the menu names the account you're in.
- A review's player starts with sound, and remembers if you turn it off.
- Every project has a canvas: deliverables, previews and the brief's frames, marked with a region or a point and a
`#tag`, sent back as a note or as edits.
- On Windows, Codex's shell commands run (#244). Codex's elevated sandbox waited on a Windows prompt or failed every
call with "The tool call failed"; raea now starts it with Windows' unelevated sandbox, unless you set your own.
**raea cloud.**
- Boxes move onto each new release, and each box build is stamped with the commit and files it came from.
- An agent's errors go into its run's trace, a runaway render is stopped before it takes the box down, and an agent
waiting on a long render keeps its connection.
- A render sends a project's footage once, known by the file rather than its path.
- `raea words` on a box transcribes with Whisper large-v3, and `raea frames check` measures what a cut's pictures get
wrong (faces cut off, split frames that make no sense).
- Google's AI signs in on the box, in a browser you work from the dashboard.
**Known**
- The Windows on ARM build is checked in CI without drawing: GitHub's ARM64 runner has no GPU raea can draw on. A
Snapdragon PC is where its pictures are checked. If something looks wrong, the x86_64 build still runs there, and
`WGPU_BACKEND=vulkan` or `dx12` chooses the graphics API by hand.
- The Windows app is unsigned, as before: Windows asks once whether to run it (#221).
- On Linux, raea needs a processor with AVX (most from 2011 on) and glibc 2.39 or newer (Ubuntu 24.04, Debian 13,
Fedora 40 and later).
- A proxy set by an automatic configuration (PAC) file isn't read. If yours uses one, start raea with `HTTPS_PROXY`
set.
+8 -2
View File
@@ -34,6 +34,8 @@ pub fn device() -> Result<Handles, String> {
/// Intel's and AMD's PCI vendor ids, as DXGI and Vulkan report them.
const INTEL: u32 = 0x8086;
const AMD: u32 = 0x1002;
/// Qualcomm's (Adreno, on a Windows on ARM PC): DXGI reports "QCOM" as its vendor, some drivers 0x5143
const QUALCOMM: [u32; 2] = [0x4D4F_4351, 0x5143];
/// Whether the shared device runs on DX12 alone: on Windows, when WGPU_BACKEND isn't set and DX12 lists Intel's or
/// AMD's own hardware among its GPUs (`dx12`: each one's vendor and kind; WARP, Windows' software DirectX, is a Cpu),
@@ -41,10 +43,12 @@ const AMD: u32 = 0x1002;
/// 0.1.3's app crashed before its window in AMD's OpenGL driver (atio6axx.dll, 0xc0000005) on a laptop with an AMD
/// 780M beside an RTX 5060, under wgpu's every-backend default and under Vulkan alike (#155); both ran with
/// WGPU_BACKEND=dx12. On that laptop DX12's high-performance pick is the NVIDIA GPU, so the rule looks at every GPU,
/// not the pick. A PC with only NVIDIA's GPUs, a PC with no GPU, a Mac or Linux, and a WGPU_BACKEND someone set
/// not the pick. A Snapdragon PC's Adreno too (#82): under Vulkan Vello's 2D pages came out striped and with grey boxes
/// behind fading text on an Adreno X1-85, and on DX12 they were clean. A PC with only NVIDIA's GPUs, a PC with no GPU,
/// a Mac or Linux, and a WGPU_BACKEND someone set
/// (Windows' check sets vulkan, for lavapipe) keep wgpu's own pick.
pub fn dx12_first(windows: bool, env: Option<wgpu::Backends>, dx12: &[(u32, wgpu::DeviceType)]) -> bool {
windows && env.is_none() && dx12.iter().any(|&(vendor, kind)| matches!(vendor, INTEL | AMD) && kind != wgpu::DeviceType::Cpu)
windows && env.is_none() && dx12.iter().any(|&(vendor, kind)| (matches!(vendor, INTEL | AMD) || QUALCOMM.contains(&vendor)) && kind != wgpu::DeviceType::Cpu)
}
/// The backends every wgpu instance of raea's asks for (the shared device's, Bevy's own when it isn't there, systems/k's
@@ -147,6 +151,8 @@ mod tests {
assert!(dx12_first(true, None, &[(AMD, igpu), (0x10de, dgpu), warp]), "#155: an AMD 780M beside an RTX 5060 (DX12 picks the NVIDIA)");
assert!(dx12_first(true, None, &[(0x10de, dgpu), (AMD, igpu)]), "the same laptop listed NVIDIA first");
assert!(dx12_first(true, None, &[(AMD, dgpu)]), "an AMD Radeon card");
assert!(dx12_first(true, None, &[(0x4D4F_4351, igpu), warp]), "#82: a Snapdragon's Adreno (DXGI's QCOM)");
assert!(dx12_first(true, None, &[(0x5143, igpu)]), "#82: an Adreno reported by its PCI id");
assert!(dx12_first(true, None, &[(INTEL, igpu), (0x10de, dgpu)]), "an Intel laptop with an NVIDIA GPU");
assert!(!dx12_first(true, Some(Backends::VULKAN), &[(INTEL, igpu)]), "WGPU_BACKEND=vulkan is kept");
assert!(!dx12_first(true, Some(Backends::DX12), &[(AMD, igpu)]), "WGPU_BACKEND set: wgpu's own read of it");
+7 -1
View File
@@ -11,5 +11,11 @@ raea-io-codec = { path = "../codec", features = ["mux"] }
raea-io-soft = { path = "../soft" }
muxide = "0.2"
# from the v1.1.0 tag: the crates.io package leaves out src/arm/asm-offsets.h, which its arm assembly includes
rav1d = { git = "https://github.com/memorysafety/rav1d", tag = "v1.1.0" }
rav1d = { git = "https://github.com/memorysafety/rav1d", tag = "v1.1.0", default-features = false, features = ["bitdepth_8", "bitdepth_16"] }
rav1e = { version = "0.8", default-features = false, features = ["threading"] }
# rav1d's assembly everywhere but Windows on ARM (#82): there its arm64 .S files are GNU syntax, which MSVC's cl.exe
# skips (the link then fails), and building them with clang-cl instead breaks metis-sys's GKlib headers. The Rust and
# C paths decode the same frames, slower.
[target.'cfg(not(all(windows, target_arch = "aarch64")))'.dependencies]
rav1d = { git = "https://github.com/memorysafety/rav1d", tag = "v1.1.0", features = ["asm", "asm_arm64_dotprod", "asm_arm64_i8mm", "asm_arm64_sve2"] }
+19 -15
View File
@@ -10,14 +10,8 @@ use std::path::Path;
use raea_core_brief::cut::{self, Cut, norm};
use serde_json::Value;
/// One gate as `raea make status` lists it: its name, the file or item it's about, whether it's clear, what it says.
#[derive(Debug, Clone, PartialEq)]
pub struct Gate {
pub name: &'static str,
pub of: Option<String>,
pub clear: bool,
pub says: String,
}
/// One gate as `raea make status` lists it (a goal's are the same kind)
pub use raea_core_brief::make::Gate;
fn gate(name: &'static str, of: Option<&str>, clear: bool, says: String) -> Gate {
Gate { name, of: of.map(str::to_string), clear, says }
@@ -183,17 +177,27 @@ fn file_gates(c: &Cut, plan: &cut::CutPlan, format: &str, f: &Path, rel: &str, s
if let Some(cta) = &c.cta {
let within = cta.within.unwrap_or(cut::CTA_WITHIN);
let end = shape.map(|s| s.2).or_else(|| words.last().map(|w| w.2)).unwrap_or(0.0);
let want_s = norm(&cta.text);
let want: Vec<&str> = want_s.split(' ').collect();
let share = |got: &[&str]| {
let last: Vec<&str> = words.iter().filter(|w| w.2 >= end - within).map(|w| w.0.as_str()).collect();
// the share of a line's words, in order, in `got`; the best of the brief's lines
let share = |line: &str, got: &[&str]| {
let want_s = norm(line);
let want: Vec<&str> = want_s.split(' ').collect();
let j = joined(got, &want);
in_order(&want, &j.iter().map(|(w, _)| w.as_str()).collect::<Vec<_>>())
};
let last: Vec<&str> = words.iter().filter(|w| w.2 >= end - within).map(|w| w.0.as_str()).collect();
let heard_share = share(&last);
let on_screen = screen.iter().any(|(s, at)| *at >= end - within && share(&s.split(' ').collect::<Vec<_>>()) >= CTA_SHARE);
let lines: Vec<&str> = std::iter::once(cta.text.as_str()).chain(cta.also.iter().map(String::as_str)).collect();
// the line heard most, the first of equals (none when no line's words were heard)
let heard: Vec<_> = lines.iter().map(|l| share(l, &last)).collect();
let heard_share = heard.iter().copied().fold(0.0, f64::max);
let best = lines.iter().zip(&heard).find(|(_, h)| heard_share > 0.0 && **h == heard_share).map_or("", |(l, _)| *l);
let on_screen = screen.iter().any(|(s, at)| *at >= end - within && lines.iter().any(|l| share(l, &s.split(' ').collect::<Vec<_>>()) >= CTA_SHARE));
let ok = heard_share >= CTA_SHARE || on_screen;
out.push(gate("cta", Some(rel), ok, if ok { format!("ends on the CTA ({})", if on_screen { "on screen" } else { "heard" }) } else { format!("the CTA isn't in its last {within:.0} s ({:.0}% of its words heard there): \"{}\"", heard_share * 100.0, cta.text) }));
let says = match (ok, on_screen) {
(true, true) => "ends on the CTA (on screen)".to_string(),
(true, false) => format!("ends on the CTA (heard: \"{best}\")"),
_ => format!("no CTA in its last {within:.0} s ({:.0}% of the nearest one's words heard there): \"{}\"", heard_share * 100.0, if best.is_empty() { &cta.text } else { best }),
};
out.push(gate("cta", Some(rel), ok, says));
}
}
}
+17
View File
@@ -180,3 +180,20 @@ fn heard_the_way_people_say_it() {
deliver(&d, S1, &line.replace("It's free it's fun", "It's fun it's free"), &[]);
assert!(!of(&run(&m, &d), "say", S1).clear);
}
#[test]
fn a_rotated_cta_lands_on_any_of_its_lines() {
// Dutch's hosts rotate "See a vet today at Dutch.com." and "Download the Dutch app and book a call for your dog or cat."
let brief = format!("{BRIEF}\"See a vet today at Dutch.com.\"\n");
let d = dir("rotated");
put(&d, "media/brief.txt", brief.as_bytes());
let mut m = contract("");
m.cut.as_mut().unwrap().cta.as_mut().unwrap().also = vec!["See a vet today at Dutch.com.".into()];
deliver(&d, S1, "it draws the names it's free fun and easy so See a vet today at Dutch com", &[]);
let g = run(&m, &d);
assert!(of(&g, "cta", S1).clear, "{:?}", of(&g, "cta", S1));
assert!(named(&g, "quotes")[0].clear, "{:?}", named(&g, "quotes"));
// a rotated line the brief doesn't have is held like any other rule
m.cut.as_mut().unwrap().cta.as_mut().unwrap().also.push("Book now at Dutch.com".into());
assert!(!named(&run(&m, &d), "quotes")[0].clear);
}
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "raea-runtime-goal-plan"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "A goal job held to its rules: commands that must pass, and words a fresh critic must find true after the work's last change (make: goal({...}), /goal)"
[dependencies]
# the contract: `make: goal({...})` on brief.ts
raea-core-brief = { path = "../../core/brief" }
serde_json = "1"
+205
View File
@@ -0,0 +1,205 @@
//! A goal job's gates (`make: goal({...})` on brief.ts, core/brief goal.rs): the person's goal held as rules, from what's
//! on disk and what a fresh critic said, never from the agent that did the work. `/goal` in raea.app and an agent's own
//! goal are this one loop (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 (run again at every status)
//! file the file exists: a deliverable, so `raea make status` lists it under missing, not here
//! says a fresh critic (`raea make judge`) found it true of the work, after the work's last change
//! The critic's verdict is review/goal.judge.json: {at, by, rules: {ID: {pass, why}}}.
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime};
use raea_core_brief::goal::Goal;
use serde_json::{Value, json};
/// One gate as `raea make status` lists it (a cut's are the same kind): `of` is the rule it's about
pub use raea_core_brief::make::Gate;
fn gate(name: &'static str, of: &str, clear: bool, says: String) -> Gate {
Gate { name, of: Some(of.to_string()), clear, says }
}
/// Where the critic's verdict is kept, beside the brief.
pub const VERDICT: &str = "review/goal.judge.json";
/// The seconds a `run` rule gets when it names none.
pub const TIMEOUT: u32 = 300;
/// Folders that aren't the work: what the job writes about itself, and what tools keep.
const NOT_WORK: [&str; 7] = ["review", ".git", "node_modules", ".raea", "target", ".cache", ".raea-cloud"];
/// When the work last changed: the newest file under DIR, its own bookkeeping left out (a bounded walk).
pub fn newest(dir: &Path) -> Option<SystemTime> {
let mut best: Option<SystemTime> = None;
let mut stack = vec![dir.to_path_buf()];
let mut seen = 0usize;
while let Some(d) = stack.pop() {
for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {
seen += 1;
if seen > 20_000 {
return best;
}
let p = e.path();
let name = e.file_name().to_string_lossy().to_string();
let Ok(t) = e.file_type() else { continue };
if t.is_dir() {
if !(d == dir && NOT_WORK.contains(&name.as_str())) && name != "node_modules" && name != ".git" {
stack.push(p);
}
} else if t.is_file() && name != "NOTES.md" {
if let Ok(m) = e.metadata().and_then(|m| m.modified()) {
best = Some(best.map_or(m, |b| b.max(m)));
}
}
}
}
best
}
/// A command run in DIR through the system shell, stopped at its timeout: (passed, its last words).
pub fn run(cmd: &str, dir: &Path, secs: u32) -> (bool, String) {
let mut c = if cfg!(windows) {
let mut c = std::process::Command::new("cmd");
c.args(["/C", cmd]);
c
} else {
let mut c = std::process::Command::new("sh");
c.args(["-c", cmd]);
c
};
let out = std::env::temp_dir().join(format!("raea-goal-{}-{}.log", std::process::id(), Instant::now().elapsed().as_nanos()));
let Ok(log) = std::fs::File::create(&out) else { return (false, "couldn't make a log file for it".into()) };
let Ok(err) = log.try_clone() else { return (false, "couldn't make a log file for it".into()) };
let child = c.current_dir(dir).stdin(std::process::Stdio::null()).stdout(log).stderr(err).spawn();
let mut child = match child {
Ok(ch) => ch,
Err(e) => return (false, format!("couldn't start it: {e}")),
};
let until = Instant::now() + Duration::from_secs(secs as u64);
let status = loop {
match child.try_wait() {
Ok(Some(s)) => break Some(s),
Ok(None) if Instant::now() >= until => {
let _ = child.kill();
let _ = child.wait();
break None;
}
Ok(None) => std::thread::sleep(Duration::from_millis(100)),
Err(_) => break None,
}
};
let text = std::fs::read_to_string(&out).unwrap_or_default();
let _ = std::fs::remove_file(&out);
let last = text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").trim();
let last: String = last.chars().take(200).collect();
match status {
Some(s) if s.success() => (true, "passes".into()),
Some(s) => (false, format!("exits {}{}", s.code().map_or("by a signal".into(), |c| c.to_string()), if last.is_empty() { String::new() } else { format!(": {last}") })),
None => (false, format!("still running after {secs} s: stopped (give the rule a longer `timeout`, or make it quicker)")),
}
}
/// The critic's verdict, when there is one.
pub fn verdict(dir: &Path) -> Option<Value> {
serde_json::from_str(&std::fs::read_to_string(dir.join(VERDICT)).ok()?).ok()
}
/// Every rule's gate but `file` rules (deliverables: status lists them as missing).
pub fn gates(g: &Goal, dir: &Path) -> Vec<Gate> {
let says: Vec<_> = g.rules.iter().filter(|r| r.says.is_some()).collect();
let v = if says.is_empty() { None } else { verdict(dir) };
let judged = v.as_ref().and_then(|v| v["at"].as_u64()).map(|s| SystemTime::UNIX_EPOCH + Duration::from_secs(s));
let changed = if says.is_empty() { None } else { newest(dir) };
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
let secs = |t: SystemTime| t.duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
let fresh = match (judged, changed) {
(Some(j), Some(c)) => secs(j) >= secs(c),
(Some(_), None) => true,
_ => false,
};
let mut out = Vec::new();
for r in &g.rules {
if let Some(cmd) = &r.run {
let (ok, said) = run(cmd, dir, r.timeout.unwrap_or(TIMEOUT));
out.push(gate("run", &r.id, ok, if ok { format!("`{cmd}` passes") } else { format!("`{cmd}` {said}") }));
} else if r.says.is_some() {
let one = v.as_ref().map(|v| &v["rules"][&r.id]);
let (clear, said) = match one {
None => (false, "not judged yet: raea make judge".to_string()),
Some(Value::Null) => (false, "the last judging didn't cover it: raea make judge".to_string()),
Some(_) if !fresh => (false, "the work changed after the critic judged it: raea make judge again".to_string()),
Some(x) if x["pass"] == true => (true, format!("a fresh critic found it true: {}", x["why"].as_str().unwrap_or(""))),
Some(x) => (false, format!("a fresh critic found it not true yet: {}", x["why"].as_str().unwrap_or(""))),
};
out.push(gate("says", &r.id, clear, said));
}
}
out
}
/// What the critic is asked: the goal, each `says` rule by id, and the answer's shape. It reads; it changes nothing.
pub fn prompt(g: &Goal, dir: &Path) -> String {
let rules: Vec<String> = g.rules.iter().filter_map(|r| r.says.as_ref().map(|s| format!("- {}: {s}", r.id))).collect();
format!(
"You are a fresh critic. You did none of this work and owe it nothing. The work is in {d}: read whatever you need \
there (its files, its renders, NOTES.md), and change nothing.\n\nThe goal, as the person said it: {goal}\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}\n\nAnswer last with one JSON \
object and nothing after it: {{\"rules\": {{\"ID\": {{\"pass\": true, \"why\": \"...\"}}}}}}",
d = dir.display(),
goal = g.goal,
rules = rules.join("\n")
)
}
/// The verdict: the object around the text's last `"rules"` key (a critic may think aloud, or quote the shape, first).
pub fn last_verdict(text: &str) -> Option<Value> {
let key = text.rfind("\"rules\"")?;
// the nearest brace before the key opens the verdict
let open = text[..key].rfind('{')?;
let v: Value = serde_json::Deserializer::from_str(&text[open..]).into_iter::<Value>().next()?.ok()?;
v["rules"].is_object().then_some(v)
}
/// The critics `raea make judge` can ask, each a fresh session that may only read.
pub const BY: [&str; 2] = ["claude", "kimi"];
/// One fresh critic over the goal's `says` rules: its verdict kept at review/goal.judge.json, stamped with when it was
/// asked (so work changed while it judged counts as changed after). Returns the verdict.
pub fn judge(g: &Goal, dir: &Path, by: &str) -> Result<Value, String> {
if !g.rules.iter().any(|r| r.says.is_some()) {
return Err("raea make judge: the goal has no `says` rules; its `run` and `file` rules are checked by raea make status".into());
}
let asked = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
let p = prompt(g, dir);
let mut cmd = match by {
"claude" => {
let mut c = std::process::Command::new("claude");
c.args(["-p", &p, "--allowedTools", "Read Grep Glob", "--output-format", "json"]);
c
}
"kimi" => {
let mut c = std::process::Command::new("kimi");
c.args(["-p", &p]);
c
}
o => return Err(format!("raea make judge: --by {o}: the critics are {}", BY.join(", "))),
};
let out = cmd.current_dir(dir).stdin(std::process::Stdio::null()).output().map_err(|e| format!("raea make judge: couldn't run {by}: {e} (is its CLI installed and signed in?)"))?;
let text = String::from_utf8_lossy(&out.stdout).to_string();
// claude's json output is {result: "..."}; kimi's is the words
let words = serde_json::from_str::<Value>(&text).ok().and_then(|v| v["result"].as_str().map(String::from)).unwrap_or(text);
let tail = &words[words.floor_char_boundary(words.len().saturating_sub(300))..];
let mut v = last_verdict(&words).ok_or_else(|| format!("raea make judge: {by} answered no verdict: {}", tail.trim()))?;
v["at"] = json!(asked);
v["by"] = json!(by);
v["goal"] = json!(g.goal);
let file: PathBuf = dir.join(VERDICT);
if let Some(parent) = file.parent() {
std::fs::create_dir_all(parent).map_err(|e| format!("raea make judge: {}: {e}", parent.display()))?;
}
std::fs::write(&file, serde_json::to_string_pretty(&v).unwrap_or_default()).map_err(|e| format!("raea make judge: {}: {e}", file.display()))?;
Ok(v)
}
#[cfg(test)]
mod tests;
+84
View File
@@ -0,0 +1,84 @@
use super::*;
use raea_core_brief::goal::{Goal, GoalRule};
fn rule(id: &str) -> GoalRule {
GoalRule { id: id.into(), run: None, timeout: None, file: None, says: None }
}
fn tmp(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("raea-goal-plan-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
#[test]
fn a_command_passes_or_says_why() {
let d = tmp("run");
let g = Goal { goal: "tests pass".into(), rules: vec![GoalRule { run: Some("true".into()), ..rule("ok") }, GoalRule { run: Some("echo broke; exit 3".into()), ..rule("bad") }] };
let gs = gates(&g, &d);
assert_eq!(gs.len(), 2);
assert!(gs[0].clear, "{gs:?}");
assert!(!gs[1].clear);
assert!(gs[1].says.contains("exits 3") && gs[1].says.contains("broke"), "{}", gs[1].says);
}
#[test]
fn a_command_past_its_timeout_fails() {
let d = tmp("slow");
let (ok, said) = run("sleep 5", &d, 1);
assert!(!ok);
assert!(said.contains("still running after 1 s"), "{said}");
}
#[test]
fn words_need_a_fresh_critic() {
let d = tmp("says");
std::fs::write(d.join("work.txt"), "the work").unwrap();
let g = Goal { goal: "a friendly reply".into(), rules: vec![GoalRule { says: Some("the reply is friendly".into()), ..rule("friendly") }] };
// never judged
let gs = gates(&g, &d);
assert!(!gs[0].clear && gs[0].says.contains("raea make judge"), "{gs:?}");
// judged after the work, and found true
let later = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() + 5;
std::fs::create_dir_all(d.join("review")).unwrap();
let v = json!({"at": later, "by": "claude", "rules": {"friendly": {"pass": true, "why": "it says hello warmly"}}});
std::fs::write(d.join(VERDICT), v.to_string()).unwrap();
assert!(gates(&g, &d)[0].clear);
// the critic's own file doesn't count as the work changing
assert!(newest(&d).unwrap() < SystemTime::UNIX_EPOCH + Duration::from_secs(later));
// judged before the work changed: stale
let earlier = json!({"at": 1, "rules": {"friendly": {"pass": true, "why": ""}}});
std::fs::write(d.join(VERDICT), earlier.to_string()).unwrap();
let gs = gates(&g, &d);
assert!(!gs[0].clear && gs[0].says.contains("changed after"), "{gs:?}");
// judged and found not true
let no = json!({"at": later, "rules": {"friendly": {"pass": false, "why": "it is curt"}}});
std::fs::write(d.join(VERDICT), no.to_string()).unwrap();
let gs = gates(&g, &d);
assert!(!gs[0].clear && gs[0].says.contains("it is curt"), "{gs:?}");
}
#[test]
fn file_rules_are_left_to_the_deliverables() {
let d = tmp("file");
let g = Goal { goal: "an export".into(), rules: vec![GoalRule { file: Some("out/final.mp4".into()), ..rule("export") }] };
assert!(gates(&g, &d).is_empty());
}
#[test]
fn the_verdict_is_the_last_json_with_rules() {
let t = "the shape is {\"rules\": {\"ID\": ...}} so: {\"x\": 1} then {\"rules\": {\"a\": {\"pass\": true, \"why\": \"seen\"}}}";
assert_eq!(last_verdict(t).unwrap()["rules"]["a"]["pass"], true);
assert!(last_verdict("no json here").is_none());
}
#[test]
fn the_rules_are_doctored() {
let g = Goal { goal: "".into(), rules: vec![GoalRule { run: Some("x".into()), says: Some("y".into()), ..rule("Two") }, rule("two")] };
let d = raea_core_brief::goal::doctor(&g);
assert!(d.iter().any(|l| l.contains("no `goal`")), "{d:?}");
assert!(d.iter().any(|l| l.contains("`Two`: ids are")), "{d:?}");
assert!(d.iter().any(|l| l.contains("exactly one") && l.contains("it has 2")), "{d:?}");
assert!(d.iter().any(|l| l.contains("`two` needs exactly one") && l.contains("it has 0")), "{d:?}");
}
+1 -1
View File
@@ -32,7 +32,7 @@ curl -H "authorization: Bearer $RAEA_CLOUD_TOKEN" localhost:8080/v1/health
`AGENTS` takes any ids the [ACP registry](https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json)
lists, several at once: `kimi-code`, `claude-acp`, `codex-acp`, `gemini`, `opencode`, `goose`, ... Each is installed
from its registry entry (npm at the registry's version, or its Linux archive checked by sha256), and raea's skill is
installed for it on every start. `RAEA_AGENT` picks the default; a socket can name another (`?agent=`).
installed for it on every start. A socket names its agent (`?agent=`); `RAEA_AGENT` names one for sockets that don't. With neither, there is no agent: the box never picks one itself.
`RAEA_AGENT_CMD` runs an agent the registry doesn't list, by its command line.
Signing the agent in:
+250 -30
View File
@@ -10,6 +10,9 @@
# GET /v1/jobs/ID/media with media=1: the job's media outputs [{path, oid, size}],
# left out of /out
# POST /v1/jobs/ID/media {objects: [{path, oid, href, header}]} PUTs each to its signed URL in R2 (farm_media.py)
# POST /v1/blobs/have {objects: [{oid, size}]} which of a project's media the farm holds: {have: [oid]}
# PUT /v1/blobs/OID?size=N one media file into the farm's cache, kept when it
# hashes to OID (a box's project not in raea's LFS)
# A job's folder may hold .raea-cloud-media.json: its media by Git LFS object id with URLs signed for it, fetched from
# R2 through a cache on the volume keyed by hash instead of coming in the tar (docs/cloud-render.feature CR23).
#
@@ -22,6 +25,7 @@
# - the clipping check (RAEA_CLIP_CHECK) is off on the GPUs: it is an agent's lint, and on a server's CPU it took more
# of a render than its frames (bench/gpus.py)
import contextlib
import json
import os
import re
@@ -62,6 +66,14 @@ image = (
"| tar -xJ -C /opt && ln -s /opt/blender-$v-linux-x64/blender /usr/local/bin/blender && blender -b --version | head -1",
)
.pip_install("fastapi[standard]==0.121.2")
# /v1/faces: OpenCV's YuNet face detector (232 KB, CPU), for the boxes' frames check (server/frames.ts): a box has
# no vision backend of its own (raea-perceive isn't in raea's Linux build), so a face cut by a 9:16 crop went unseen
.pip_install("opencv-python-headless==4.11.0.86", "numpy<2.3")
.run_commands(
"set -e; curl -fsSL -o /opt/yunet.onnx https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/"
"face_detection_yunet/face_detection_yunet_2023mar.onnx "
"&& echo '8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4 /opt/yunet.onnx' | sha256sum -c"
)
.add_local_file(os.path.join(CLOUD, "image", "nvidia_icd.json"), "/usr/share/vulkan/icd.d/nvidia_icd.json", copy=True)
.env({"WGPU_BACKEND": "vulkan", "NVIDIA_DRIVER_CAPABILITIES": "all", "RAEA_CLIP_CHECK": "0", "RAEA_AUDIO_MUTE": "1",
"RAEA_MODELS": "/models/raea", "RAEA_FEED_MODELS": "/models/feed", "RAEA_LIBRARY_MODELS": "/models/library",
@@ -81,6 +93,8 @@ models = modal.Volume.from_name("raea-models", create_if_missing=True, version=2
logs = modal.Dict.from_name("raea-farm-logs", create_if_missing=True)
# the farm's token (RAEA_CLOUD_TOKEN), its own: a CPU box names it as RAEA_CLOUD_GPU_TOKEN
secret = modal.Secret.from_name(os.environ.get("RAEA_FARM_SECRET", "raea-farm"))
# OPENROUTER_API_KEY for /v1/words: raea cloud's own key, the one its library index transcribes with
words_secret = modal.Secret.from_name(os.environ.get("RAEA_FARM_WORDS_SECRET", "raea-farm-words"))
# a CPU render (the coordinator's sound pass) on lavapipe, with EGL's vendors hidden (docs/cloud.feature CL13)
CPU_ENV = {"VK_DRIVER_FILES": "/usr/share/vulkan/icd.d/lvp_icd.json", "__EGL_VENDOR_LIBRARY_DIRS": "/nonexistent"}
@@ -111,7 +125,10 @@ def snapshot(d):
for base, _, files in os.walk(d):
for f in files:
p = os.path.join(base, f)
s = os.stat(p)
try:
s = os.stat(p)
except OSError: # a link that points nowhere here (a box's kits/ link to its cache): not a file of the job's
continue
out[os.path.relpath(p, d)] = f"{s.st_size}:{s.st_mtime_ns}"
return out
@@ -158,7 +175,7 @@ def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: i
if probe:
code, out, s = run(["raea", *args, "--frame", "0", "-o", "/tmp/probe.png", "--manifest", "/tmp/probe.json"], cwd=work)
m = json.load(open("/tmp/probe.json")) if os.path.exists("/tmp/probe.json") else {}
return {"code": code, "out": out[-3000:], "s": s, "length": m.get("length"), "fps": m.get("fps"), "w": m.get("width"), "h": m.get("height"), "kind": kind(), **life()}
return {"code": code, "out": out[-3000:], "s": s, "length": m.get("length"), "fps": m.get("fps"), "w": m.get("width"), "h": m.get("height"), "kind": kind(), "manifest": m, **life()}
if frames is None:
code, out, s = run(["raea", *args], cwd=work)
vol.commit()
@@ -248,6 +265,9 @@ def coordinate(id: str, args: list[str], opts: dict):
vol.commit()
log.end(1)
return
# the media just linked (or fetched) into the job, committed before any GPU container reloads to render it: without
# this a still on this container found the footage and every GPU run of a video didn't ("No such file", 11-25)
vol.commit()
before = snapshot(work)
try:
code = farm_plan.dispatch(args, {**opts, "id": id}, work, log, raea_run, blender_run, CPU_ENV, run, vol.reload)
@@ -255,6 +275,19 @@ def coordinate(id: str, args: list[str], opts: dict):
log(f"raea farm: {e!r}", err=True)
code = 1
vol.commit()
# what the job's GPU containers committed (a whole render's stills, its folder output) is only seen here after a
# reload: without it a render to a folder came back empty while a joined .mp4, written here, came back (11-20).
# Another job's open files in this coordinator refuse a reload (ConflictError, 11-21: a 500 for the box): try again,
# and if it still won't, go on with what this container sees rather than lose a finished render
for pause in (0.5, 1, 2, 4, 0):
try:
vol.reload()
break
except Exception as e: # modal.exception.ConflictError
if not pause:
log(f"raea farm: the volume wouldn't reload ({e}); returning what this container sees", err=True)
else:
time.sleep(pause)
after = snapshot(work)
changed = [p for p, v in after.items() if before.get(p) != v]
if opts.get("media"):
@@ -271,7 +304,7 @@ def coordinate(id: str, args: list[str], opts: dict):
log.end(code)
@app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret], timeout=3600)
@app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret, words_secret], timeout=3600)
@modal.concurrent(max_inputs=32)
@modal.asgi_app()
def api():
@@ -283,6 +316,59 @@ def api():
web = FastAPI()
token = os.environ["RAEA_CLOUD_TOKEN"]
# This container serves many requests at once, and a volume reload refuses while any of them has a file open
# (ConflictError) and, when it goes ahead, takes /farm away from a request mid-write (PermissionError making a
# job's folder). 11-25: StreetTalk's renders lost a finished job's results (GET out: 500) and failed to start
# (POST jobs: 500) whenever two agents rendered together. So requests that touch the volume share it, and a
# reload waits until none of them is in it.
class Gate:
def __init__(self):
self.users = 0
self.reloading = False
self.cond = asyncio.Condition()
@contextlib.asynccontextmanager
async def use(self):
async with self.cond:
await self.cond.wait_for(lambda: not self.reloading)
self.users += 1
try:
yield
finally:
async with self.cond:
self.users -= 1
self.cond.notify_all()
async def reload(self, wait: bool = True) -> bool:
"""the volume as other containers committed it; with wait=False skipped (False) while the volume is in use"""
async with self.cond:
if not wait and (self.users or self.reloading):
return False
await self.cond.wait_for(lambda: not self.users and not self.reloading)
self.reloading = True
try:
for pause in (0.5, 1, 2, 4, 0):
try:
await vol.reload.aio()
return True
except Exception as e: # modal.exception.ConflictError: a file open elsewhere in this container
if not pause:
print(f"raea farm: the volume wouldn't reload: {e}")
return False
await asyncio.sleep(pause)
return False
finally:
async with self.cond:
self.reloading = False
self.cond.notify_all()
gate = Gate()
async def reloaded():
"""the coordinator's commits seen here, or a 503 the box tries again on (the job is still all here)"""
if not await gate.reload():
raise HTTPException(503, "the farm's volume is busy: try again")
def check(req: Request):
got = req.headers.get("authorization", "").removeprefix("Bearer ") or req.query_params.get("token", "")
if got != token:
@@ -297,6 +383,88 @@ def api():
check(req)
return {"raea": RAEA, "blender": BLENDER, "device": {"renders": "gpu", "name": f"raea on {'/'.join(RAEA_GPUS)}, Blender on {'/'.join(BLENDER_GPUS)}, up to {GPUS} at once"}, "farm": True, "jobs": []}
# what's said in a piece of sound, word by word, for a box's `raea words` (server/words.ts): a box has no
# transcriber of its own (raea's is parakeet-mlx, Mac only), so the same Whisper large-v3 on OpenRouter that raea
# cloud's library index uses (apps/app host/library/words.ts) hears it here. The body is one MP3 piece (16 kHz mono,
# at most 10 minutes; the box cuts the pieces), the answer its words in the piece's own seconds. 11-25, Shane: "give
# it whatever we use for indexing and libraries and sync", so agents check the words their cuts say.
def seams(g):
"""a split screen's seams: rows (h) or columns (v) where the picture jumps across nearly all of the frame, as a
cut between two pictures does and nothing filmed does (a caption's box spans part of it, a horizon is soft)"""
import numpy as np
found = []
for axis, d in (("h", np.abs(np.diff(g, axis=0))), ("v", np.abs(np.diff(g, axis=1)).T)):
n = d.shape[0]
share = (d > 24).mean(axis=1)
for i in range(int(n * 0.08), int(n * 0.92)):
if share[i] > 0.7 and share[i] >= share[max(i - 1, 0)] and share[i] >= share[min(i + 1, n - 1)]:
found.append([axis, i + 1, round(float(share[i]), 2)])
return found
@web.post("/v1/faces")
async def faces(req: Request):
"""the faces in a video's frames, for the boxes' frames check: the body is {"frames": [base64 JPEG, ...]} (at most
400, any size), the answer each frame's size and its faces as [x, y, w, h, score] in that frame's pixels"""
import base64
import cv2
import numpy as np
check(req)
body = await req.json()
frames = body.get("frames") if isinstance(body, dict) else None
if not isinstance(frames, list) or not frames:
raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}')
if len(frames) > 400:
raise HTTPException(413, "at most 400 frames a call")
out, det, size = [], None, None
for b64 in frames:
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
if im is None:
out.append(None)
continue
h, w = im.shape[:2]
if size != (w, h):
det, size = cv2.FaceDetectorYN.create("/opt/yunet.onnx", "", (w, h), 0.6, 0.3, 5000), (w, h)
_, found = det.detect(im)
out.append({"w": w, "h": h, "faces": [[round(float(f[0]), 1), round(float(f[1]), 1), round(float(f[2]), 1), round(float(f[3]), 1), round(float(f[14]), 3)] for f in (found if found is not None else [])],
"seams": seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))})
return {"model": "yunet-2023mar", "frames": out}
@web.post("/v1/words")
async def words(req: Request):
import base64
import json as _json
import urllib.error
import urllib.request
check(req)
key = os.environ.get("OPENROUTER_API_KEY", "")
if not key:
raise HTTPException(503, "the farm has no OpenRouter key for words (Modal secret raea-farm-words)")
mp3 = await req.body()
if not mp3:
raise HTTPException(400, "the body is the sound: an MP3, 16 kHz mono, at most 10 minutes")
if len(mp3) > 24 << 20:
raise HTTPException(413, "a piece is at most 24 MB: send 10-minute pieces at 32 kb/s")
body = {"model": "openai/whisper-large-v3", "input_audio": {"data": base64.b64encode(mp3).decode(), "format": "mp3"}, "response_format": "verbose_json", "timestamp_granularities": ["word", "segment"]}
if req.query_params.get("language"):
body["language"] = req.query_params["language"]
def ask():
r = urllib.request.Request("https://openrouter.ai/api/v1/audio/transcriptions", data=_json.dumps(body).encode(), headers={"authorization": f"Bearer {key}", "content-type": "application/json", "x-title": "raea cloud words"})
try:
with urllib.request.urlopen(r, timeout=300) as f:
return 200, _json.load(f)
except urllib.error.HTTPError as e:
return e.code, {"error": e.read()[:500].decode("utf8", "replace")}
code, got = await asyncio.to_thread(ask)
if code != 200:
raise HTTPException(502, f"OpenRouter's Whisper said {code}: {got.get('error', '')}")
ws = [{"text": w.get("word", "").strip(), "start": float(w.get("start", 0)), "end": float(w.get("end", w.get("start", 0)))} for w in got.get("words") or [] if w.get("word", "").strip()]
return {"model": "openai/whisper-large-v3", "duration": got.get("duration"), "text": got.get("text", ""), "words": ws}
@web.post("/v1/jobs")
async def start(req: Request):
check(req)
@@ -307,22 +475,71 @@ def api():
opts = {"gpus": min(int(q.get("gpus", GPUS)), GPUS), "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
id = str(uuid.uuid4())
work = f"{JOBS}/{id}/work"
os.makedirs(work)
tar = f"{JOBS}/{id}/in.tar"
with open(tar, "wb") as f:
async for chunk in req.stream():
f.write(chunk)
# GNU tar reads the compression itself, refuses members with .. and strips a leading /
x = subprocess.run(["tar", "-xf", tar, "-C", work, "--no-same-owner", "--no-same-permissions"], capture_output=True, text=True)
os.remove(tar)
if x.returncode:
shutil.rmtree(f"{JOBS}/{id}", ignore_errors=True)
raise HTTPException(400, f"the folder didn't unpack: {x.stderr.strip()}")
await vol.commit.aio()
async with gate.use():
os.makedirs(work)
tar = f"{JOBS}/{id}/in.tar"
with open(tar, "wb") as f:
async for chunk in req.stream():
f.write(chunk)
# GNU tar reads the compression itself, refuses members with .. and strips a leading /
x = await asyncio.to_thread(subprocess.run, ["tar", "-xf", tar, "-C", work, "--no-same-owner", "--no-same-permissions"], capture_output=True, text=True)
os.remove(tar)
if x.returncode:
shutil.rmtree(f"{JOBS}/{id}", ignore_errors=True)
raise HTTPException(400, f"the folder didn't unpack: {x.stderr.strip()}")
await vol.commit.aio()
await logs.put.aio(id, [])
await coordinate.spawn.aio(id, args, opts)
return {"id": id}
# a project's footage by hash, sent once (11-25: StreetTalk's 1.9 GB of interviews went in every render's tar, even
# one frame's, and three at once ran the box out of memory): the box asks which the farm has, PUTs the rest, and a
# job's .raea-cloud-media.json names them with no href (farm_media.fetch uses them from the cache)
@web.post("/v1/blobs/have")
async def blobs_have(req: Request):
check(req)
objects = (await req.json()).get("objects") or []
await gate.reload(wait=False) # the volume in use: what this container sees will do (a blob it lacks is sent again)
have = []
async with gate.use():
for o in objects[:5000]:
oid, size = str(o.get("oid", "")), int(o.get("size", -1))
blob = f"{ROOT}/blobs/{oid}"
if len(oid) == 64 and all(c in "0123456789abcdef" for c in oid) and os.path.exists(blob) and os.path.getsize(blob) == size:
have.append(oid)
return {"have": have}
@web.put("/v1/blobs/{oid}")
async def blob_put(oid: str, req: Request):
import hashlib
check(req)
if len(oid) != 64 or any(c not in "0123456789abcdef" for c in oid):
raise HTTPException(400, "not an object id: 64 hex characters")
size = int(req.query_params.get("size", "-1"))
async with gate.use():
os.makedirs(f"{ROOT}/blobs", exist_ok=True)
blob = f"{ROOT}/blobs/{oid}"
if os.path.exists(blob) and os.path.getsize(blob) == size:
return {"oid": oid, "bytes": size, "had": True}
tmp = f"{blob}.up-{uuid.uuid4().hex[:8]}"
h = hashlib.sha256()
n = 0
try:
with open(tmp, "wb") as f:
async for chunk in req.stream():
h.update(chunk)
f.write(chunk)
n += len(chunk)
if h.hexdigest() != oid or n != size:
raise HTTPException(400, f"the file came as {h.hexdigest()[:12]}… ({n} bytes), not {oid[:12]}… ({size} bytes)")
os.replace(tmp, blob)
finally:
if os.path.exists(tmp):
os.remove(tmp)
await vol.commit.aio()
return {"oid": oid, "bytes": n}
@web.get("/v1/jobs/{id}")
async def follow(id: str, req: Request):
check(req)
@@ -339,44 +556,47 @@ def api():
await asyncio.sleep(0.5)
@web.get("/v1/jobs/{id}/media")
def media_list(id: str, req: Request):
async def media_list(id: str, req: Request):
check(req)
if logs.get(f"{id}:exit") is None:
if await logs.get.aio(f"{id}:exit") is None:
raise HTTPException(404, "no such finished job")
vol.reload()
p = f"{JOBS}/{id}/media.json"
return {"objects": json.load(open(p)) if os.path.exists(p) else []}
await reloaded()
async with gate.use():
p = f"{JOBS}/{id}/media.json"
return {"objects": json.load(open(p)) if os.path.exists(p) else []}
@web.post("/v1/jobs/{id}/media")
async def media_send(id: str, req: Request):
import farm_media
check(req)
if logs.get(f"{id}:exit") is None:
if await logs.get.aio(f"{id}:exit") is None:
raise HTTPException(404, "no such finished job")
await vol.reload.aio()
await reloaded()
body = await req.json()
objects = body.get("objects") if isinstance(body, dict) else None
if not isinstance(objects, list):
raise HTTPException(400, "objects: [{path, oid, href, header}]")
# said in this container's log, not the job's (its log is done, and Log would start it again)
try:
return await asyncio.to_thread(farm_media.upload, f"{JOBS}/{id}/work", objects, print)
async with gate.use():
return await asyncio.to_thread(farm_media.upload, f"{JOBS}/{id}/work", objects, print)
except ValueError as e:
raise HTTPException(400, str(e))
@web.get("/v1/jobs/{id}/out")
def out(id: str, req: Request):
async def out(id: str, req: Request):
check(req)
if logs.get(f"{id}:exit") is None:
if await logs.get.aio(f"{id}:exit") is None:
raise HTTPException(404, "no such finished job")
vol.reload()
await reloaded()
pack = {"zst": ["--zstd"], "gz": ["--gzip"], "tar": []}.get(req.query_params.get("as", "zst"), ["--zstd"])
r = subprocess.run(["tar", *pack, "-cf", "-", "-C", f"{JOBS}/{id}/work", "--verbatim-files-from", "-T", f"{JOBS}/{id}/changed.txt"], capture_output=True)
shutil.rmtree(f"{JOBS}/{id}", ignore_errors=True)
vol.commit()
async with gate.use():
r = await asyncio.to_thread(subprocess.run, ["tar", *pack, "-cf", "-", "-C", f"{JOBS}/{id}/work", "--verbatim-files-from", "-T", f"{JOBS}/{id}/changed.txt"], capture_output=True)
shutil.rmtree(f"{JOBS}/{id}", ignore_errors=True)
await vol.commit.aio()
for k in (id, f"{id}:exit"):
logs.pop(k, None)
await logs.pop.aio(k, None)
if r.returncode:
raise HTTPException(500, f"the results didn't pack: {r.stderr.decode().strip()}")
return Response(r.stdout, media_type="application/octet-stream")
+14 -2
View File
@@ -5,6 +5,8 @@
# a raea credential, only signed URLs that each reach one object.
#
# .raea-cloud-media.json in the job's folder, from the box: {"objects": [{"path", "oid", "size", "href", "header"}]}
# An object with no href is one the box sent the farm itself (PUT /v1/blobs/OID, farm.py:
# a project not in raea's LFS, 11-25): it is used from the cache, and only from there
# fetch(work, cache, ...) each object into the cache (once), then into its path in the job's folder
# outputs(work, changed) the job's media among what it made or changed: [{"path", "oid", "size"}]
# upload(work, objects) PUTs each to its signed URL: [{"path", "oid", "href", "header"}]
@@ -78,7 +80,12 @@ def fetch(work, cache, log=print, download=get, check=probe):
if len(oid) != 64 or any(c not in "0123456789abcdef" for c in oid) or not inside(work, path):
raise ValueError(f"media: {path!r} ({oid}) isn't a path in the job or an object id")
blob = os.path.join(cache, oid)
if os.path.exists(blob) and os.path.getsize(blob) == size:
if not o.get("href"):
# sent by the box over the farm's own token (PUT /v1/blobs), checked against its hash as it came
if not (os.path.exists(blob) and os.path.getsize(blob) == size):
raise ValueError(f"media: {path} ({oid[:12]}…) was never sent to the farm")
cached += size
elif os.path.exists(blob) and os.path.getsize(blob) == size:
# a hash alone doesn't open the cache: the job's URL, signed for its account, has to answer
check(o["href"], o.get("header"))
cached += size
@@ -95,7 +102,12 @@ def fetch(work, cache, log=print, download=get, check=probe):
os.makedirs(os.path.dirname(dest), exist_ok=True)
if os.path.lexists(dest):
os.remove(dest)
shutil.copyfile(blob, dest)
# a link into the cache, not a copy: a project's footage is gigabytes, the same across every job (11-25); every
# container of the job mounts the volume at the same place, so the link resolves on the GPUs too
try:
os.symlink(blob, dest)
except OSError:
shutil.copyfile(blob, dest)
log(f"raea farm: {len(objects)} media files by hash, {fetched / 1e6:.1f} MB from R2, {cached / 1e6:.1f} MB already here")
return {"objects": len(objects), "fetched": fetched, "cached": cached}
+23 -1
View File
@@ -28,6 +28,14 @@ def split_out(args):
return args[:i] + args[i + 2 :], args[i + 1] if i + 1 < len(args) else None
def drop_flag(args, flag):
"""The arguments without FLAG VALUE, and VALUE (None when it isn't there)."""
if flag not in args:
return list(args), None
i = args.index(flag)
return args[:i] + args[i + 2 :], args[i + 1] if i + 1 < len(args) else None
def splittable(args):
"""A `raea render` of a composition to a video or a folder, every frame: the farm can split it."""
if not args or args[0] != "render" or any(a in args for a in ("--frame", "--at", "--review", "--bundle", "--audio")):
@@ -161,6 +169,10 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
bill = bill or Bill()
id = opts["id"]
rest, out = split_out(args)
# the render's own --manifest is written here once it's done (from frame 0's): left in, the probe's run had two and
# wrote its own where the render's went, so it said no length and the job stopped unexplained (11-25: StreetTalk's
# four cuts, each "exit 1" after frame 0); and every GPU run would have written one into the job's folder
rest, manifest = drop_flag(rest, "--manifest")
# the sound, on this CPU while the GPUs draw (a video's frames come back without it)
sound = f"/tmp/{id}.wav"
if out.endswith(VIDEO):
@@ -169,6 +181,8 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
p = bill.add(render.remote(id, rest, probe=True))
if p["code"] or not p["length"]:
log(p["out"], err=True)
if not p["code"]:
log("raea farm: frame 0 rendered but didn't say the piece's length, so its frames can't be shared out", err=True)
return p["code"] or 1
length, fps, kind = p["length"], p["fps"] or 30, p.get("kind") or opts.get("gpu") or "T4"
log(f"raea farm: {length} frames at {p['w']}x{p['h']}, {fps} fps; frame 0 on a {kind} in {p['s']:.1f} s")
@@ -194,11 +208,19 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
code = spread(render, kind, [(id, rest, f, at, False, video) for f, at in runs(n0, length - 1, k * m, warm)], log, "frames", bill, k) if left else 0
if code:
return code
# the sound's run finished first: its open files in the job's folder refuse the reload that brings the other
# containers' frames (11-25: "the volume wouldn't reload ... cwd of raea render")
if video:
t.join()
reload() # the other containers' frames
frames = f"{os.path.dirname(work)}/frames"
dest = os.path.join(work, out)
if manifest and p.get("manifest"):
path = os.path.join(work, manifest)
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
with open(path, "w") as f:
json.dump(p["manifest"], f, indent=2)
if video:
t.join()
os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
c, o, s = join(frames, dest, sound, run)
log(f"raea farm: joined {out} in {s:.1f} s" if not c else o, err=bool(c))
+386
View File
@@ -0,0 +1,386 @@
# raea cloud's ingest on Modal (docs/cloud-ingest.feature): what a synced file needs that a Worker can't do itself.
# The Worker (sync-run.ts) calls it with the file at an address it can fetch (a Composio download's s3url) and keeps
# what comes back. From sdk/cloud:
#
# MODAL_PROFILE=raea modal deploy deploy/modal/ingest.py
#
# indexer (its own URL, raea--raea-ingest-indexer…): raea's library indexer (tools/library-index cloud-server.ts, the
# desktop's indexFile in the cloud indexer's image: EmbeddingGemma 2 for pictures, shots, sound and words, TransNetV2
# cuts, Whisper base): POST /v1/index {url, name, kind} -> {fragment, posters}; POST /v1/embed {texts} -> query
# vectors. raea cloud writes the fragments to turbopuffer in raea-api's layout (IG8). Before deploying, bundle it:
# tools/library-index/cloud-build.sh
#
# POST /v1/frame {url, at?} a video's frame as a JPEG 640 px on its long side; at is where, as a fraction of its
# length (0.1 when left out: past a fade from black, before the end card). IG4
# GET /healthz
#
# Every call but /healthz carries Authorization: Bearer RAEA_INGEST_TOKEN (Modal secret raea-ingest; the Worker's
# secret of the same name). The secret's OPENROUTER_API_KEY, when set, has index jobs transcribe with Whisper large-v3
# on OpenRouter. CPU only: a frame is ffmpeg seeking in the file, a second or two.
import os
import subprocess
import tempfile
import modal
HERE = os.path.dirname(os.path.abspath(__file__))
LIB = os.path.abspath(os.path.join(HERE, "..", "..", "..", "..", "tools", "library-index"))
app = modal.App("raea-ingest", image=modal.Image.debian_slim(python_version="3.12").apt_install("ffmpeg").pip_install("fastapi[standard]"))
secret = modal.Secret.from_name("raea-ingest")
# the largest file fetched for a frame: a phone's minute of 4K is about 400 MB
MAX_BYTES = 2 << 30
LONG_SIDE = 640
def probe_seconds(path: str) -> float:
r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path], capture_output=True, text=True, timeout=60)
try:
return max(0.0, float(r.stdout.strip()))
except ValueError:
return 0.0
def frame(path: str, at: float) -> bytes:
secs = probe_seconds(path)
t = secs * min(max(at, 0.0), 0.95) if secs else 0.0
scale = f"scale='if(gt(iw,ih),{LONG_SIDE},-2)':'if(gt(iw,ih),-2,{LONG_SIDE})'"
for seek in (t, 0.0):
r = subprocess.run(["ffmpeg", "-v", "error", "-ss", f"{seek:.3f}", "-i", path, "-frames:v", "1", "-vf", scale, "-q:v", "4", "-f", "image2", "-c:v", "mjpeg", "pipe:1"], capture_output=True, timeout=120)
if r.returncode == 0 and r.stdout:
return r.stdout
raise RuntimeError((r.stderr or b"no frame").decode(errors="replace")[-300:])
@app.function(cpu=2, memory=4096, secrets=[secret], timeout=900, scaledown_window=120)
@modal.concurrent(max_inputs=8)
@modal.asgi_app()
def api():
import urllib.request
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import PlainTextResponse, Response
web = FastAPI()
token = os.environ["RAEA_INGEST_TOKEN"]
def check(req: Request):
if req.headers.get("authorization", "").removeprefix("Bearer ") != token:
raise HTTPException(401, "a raea ingest token is needed (Authorization: Bearer)")
@web.post("/v1/index-jobs")
async def submit(req: Request):
check(req)
b = await req.json()
if not isinstance(b.get("url"), str) or not b["url"].startswith("https://"):
raise HTTPException(400, "url is the file's https address")
if b.get("kind") not in ("video", "image", "audio", "doc"):
raise HTTPException(400, "kind is one of video, image, audio, doc")
call = await index_job.spawn.aio(b["url"], str(b.get("name") or "file"), b["kind"])
return {"id": call.object_id}
@web.get("/v1/index-jobs/{job}")
async def collect(job: str, req: Request):
check(req)
try:
out = await modal.FunctionCall.from_id(job).get.aio(timeout=0)
except modal.exception.FunctionTimeoutError:
return {"state": "failed", "error": "the file took over an hour"}
except (TimeoutError, modal.exception.TimeoutError):
return {"state": "running"}
except Exception as e:
return {"state": "failed", "error": str(e)[:300]}
if out.get("error"):
return {"state": "failed", **out}
return {"state": "done", **out}
# a fingerprint's model (fingerprint_fit below): trained as a job, its state collected like an index job's
@web.post("/v1/fingerprints/fit")
async def fp_fit(req: Request):
check(req)
b = await req.json()
if not all(isinstance(b.get(k), str) and b[k] for k in ("workspace", "fingerprint")) or not isinstance(b.get("modalities"), dict):
raise HTTPException(400, "workspace, fingerprint and modalities {v|a|t: {good, bad, background}}")
call = await fingerprint_fit.spawn.aio(b["workspace"], b["fingerprint"], b["modalities"])
return {"id": call.object_id}
@web.get("/v1/fingerprints/jobs/{job}")
async def fp_job(job: str, req: Request):
check(req)
try:
out = await modal.FunctionCall.from_id(job).get.aio(timeout=0)
except (TimeoutError, modal.exception.TimeoutError):
return {"state": "running"}
except Exception as e:
return {"state": "failed", "error": str(e)[:300]}
return {"state": "failed", **out} if out.get("error") else {"state": "done", **out}
@web.post("/v1/fingerprints/score")
async def fp_score(req: Request):
check(req)
b = await req.json()
if not all(isinstance(b.get(k), str) and b[k] for k in ("workspace", "fingerprint")) or not isinstance(b.get("vectors"), dict):
raise HTTPException(400, "workspace, fingerprint and vectors {v|a|t: [f16 base64]}")
return await fingerprint_score.remote.aio(b["workspace"], b["fingerprint"], b["vectors"])
@web.get("/healthz")
def healthz():
return PlainTextResponse("ok")
@web.post("/v1/frame")
async def make_frame(req: Request):
check(req)
body = await req.json()
url, at = body.get("url"), float(body.get("at", 0.1))
if not isinstance(url, str) or not url.startswith("https://"):
raise HTTPException(400, "url is the file's https address")
with tempfile.NamedTemporaryFile(suffix=".media") as f:
got = 0
try:
with urllib.request.urlopen(urllib.request.Request(url, headers={"user-agent": "raea-ingest/1"}), timeout=120) as r:
while chunk := r.read(1 << 20):
got += len(chunk)
if got > MAX_BYTES:
raise HTTPException(413, "the file is over 2 GB")
f.write(chunk)
except HTTPException:
raise
except Exception as e:
raise HTTPException(502, f"couldn't fetch the file: {e}")
f.flush()
try:
jpg = frame(f.name, at)
except Exception as e:
raise HTTPException(422, f"no frame in it: {e}")
return Response(jpg, media_type="image/jpeg")
return web
# the index jobs' GPU: an L4 by default (EmbeddingGemma 2 at fp16 on CUDA 13: loaded in 6 s, a batch in under one);
# RAEA_INDEX_GPU= (empty) at deploy for the CPU at q8
GPU = os.environ.get("RAEA_INDEX_GPU", "L4") or None
# the cloud indexer's own image (tools/library-index/Dockerfile: Node, ffmpeg, EmbeddingGemma 2's and Whisper's weights
# baked in) on CUDA 13 with cuDNN 9 (onnxruntime-node 1.30's CUDA provider links CUDA 13, though its package says cuda12), its fp16 weights for the GPU beside the q8
# ones, pdftotext for documents and the raea cloud server. EmbeddingGemma 2 (the fingerprints: pictures, shots, sound,
# words) runs on the GPU; Whisper, TransNetV2's cuts and ffmpeg on the CPU beside it
def indexer_image_for(gpu):
return (
# on a GPU, build/Dockerfile.gpu (cloud-build.sh: the CUDA 13 base and fp16 weights written in; Modal's builds
# don't take a build argument in FROM, so BASE as an argument left a plain Ubuntu without CUDA)
modal.Image.from_dockerfile(os.path.join(LIB, "build", "Dockerfile.gpu") if gpu else os.path.join(LIB, "Dockerfile"), context_dir=LIB, add_python="3.12")
.apt_install("poppler-utils")
.env({"RAEA_LIBRARY_DEVICE": "cuda", "RAEA_LIBRARY_DTYPE": "fp16"} if gpu else {})
.add_local_file(os.path.join(LIB, "build", "cloud-server.mjs"), "/app/cloud-server.mjs")
.add_local_file(os.path.join(LIB, "build", "cloud-cli.mjs"), "/app/cloud-cli.mjs")
)
# index jobs on the GPU when there is one; the search-words server on the CPU (a query is one short text, seconds on a
# CPU, and a GPU held five minutes for it isn't worth it; q8 and fp16 vectors of the same model compare)
indexer_image = indexer_image_for(GPU)
server_image = indexer_image_for(None)
# one file indexed as a job (tools/library-index cloud-cli.ts), for a file of any length: raea cloud submits it through
# the API's POST /v1/index-jobs and collects it with GET /v1/index-jobs/ID on its next alarm (index-run.ts)
@app.function(image=indexer_image, gpu=GPU, cpu=4, memory=16384, secrets=[secret], timeout=3600, max_containers=12, scaledown_window=120)
def index_job(url: str, name: str, kind: str) -> dict:
import json
import subprocess as sp
with tempfile.TemporaryDirectory() as d:
inp, out = os.path.join(d, "in.json"), os.path.join(d, "out.json")
with open(inp, "w") as f:
json.dump({"url": url, "name": name, "kind": kind}, f)
# what's said: Whisper large-v3 on OpenRouter when the secret has its key (words.ts), else Whisper base here
words = "openrouter" if os.environ.get("OPENROUTER_API_KEY") else "whisper"
r = sp.run(["node", "/app/cloud-cli.mjs", inp, out], cwd="/app", capture_output=True, text=True, timeout=3500, env={**os.environ, "RAEA_LIBRARY_WORDS": words})
if r.returncode != 0 or not os.path.exists(out):
return {"error": f"the indexer stopped ({r.returncode}): {(r.stderr or '')[-300:]}"}
with open(out) as f:
return json.load(f)
# a GPU only while there's work: five idle minutes and the container goes
@app.function(image=server_image, cpu=4, memory=12288, secrets=[secret], timeout=3600, scaledown_window=300)
@modal.concurrent(max_inputs=4)
@modal.web_server(8080, startup_timeout=180)
def indexer():
import subprocess as sp
sp.Popen(["node", "/app/cloud-server.mjs"], cwd="/app", env={**os.environ, "PORT": "8080"})
# the GPU checked: RAEA_INDEX_GPU=L4 MODAL_PROFILE=raea modal run deploy/modal/ingest.py::gpu_probe. EmbeddingGemma 2
# loaded on the GPU at fp16 and two texts embedded, each step timed
PROBE = """
const t0 = Date.now(), log = (...a) => console.log(`[${((Date.now() - t0) / 1000).toFixed(1)}s]`, ...a)
const tf = await import("@huggingface/transformers")
tf.env.cacheDir = "/models"
const id = "onnx-community/embeddinggemma-2-ONNX"
const p = await tf.AutoProcessor.from_pretrained(id)
log("model fp16 on", process.env.RAEA_LIBRARY_DEVICE)
const m = await tf.AutoModel.from_pretrained(id, { dtype: "fp16", device: process.env.RAEA_LIBRARY_DEVICE || "cpu" })
log("loaded")
for (let k = 0; k < 2; k++) { const o = await m(await p(["a white rabbit in a forest", "a quarterly sales spreadsheet"])); log("two texts", o.sentence_embedding.dims, o.sentence_embedding.tolist()[0].slice(0, 3)) }
process.exit(0)
"""
# ---- a fingerprint's model (raea cloud's fingerprint-model.ts; Shane 11-24: "our embedding models for fingerprints
# stored and runnable from Modal GPU") ----
# Per modality (v picture, a sound, t words), a linear head on EmbeddingGemma 2's 768-d vectors, trained on the GPU:
# a fingerprint's good references against its bad ones, and, while it has few or no bad ones, against a sample of the
# workspace's other files (what's distinctive in it, against the rest of the library). Its held-out separation (AUC,
# k-fold) says how much it has learned. Kept on the volume raea-fingerprints at <workspace>/<fingerprint>.json, the
# newest one per fingerprint; fingerprint_score loads it on the GPU and scores vectors (a file's segments) 0..1.
# training.ts's SigLIP fine-tune replaces the head once a fingerprint has 200 judged examples.
fp_volume = modal.Volume.from_name("raea-fingerprints", create_if_missing=True)
fp_image = modal.Image.debian_slim(python_version="3.12").pip_install("torch==2.8.0", "numpy")
def _fp_path(workspace: str, fingerprint: str) -> str:
import re
safe = lambda x: re.sub(r"[^A-Za-z0-9._-]+", "-", x)[:80]
return f"/fp/{safe(workspace)}/{safe(fingerprint)}.json"
def _vectors(xs):
import base64
import numpy as np
rows = [np.frombuffer(base64.b64decode(x), dtype="<f2").astype("float32") for x in xs or [] if isinstance(x, str)]
rows = [r for r in rows if r.shape == (768,)]
return np.stack(rows) if rows else np.zeros((0, 768), dtype="float32")
def _auc(pos, neg) -> float:
import numpy as np
if not len(pos) or not len(neg):
return None
allv = np.concatenate([pos, neg])
ranks = allv.argsort().argsort() + 1.0
return float((ranks[: len(pos)].sum() - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg)))
def _r4(x):
return None if x is None else round(x, 4)
def _train(torch, good, neg, wneg, dev, steps=400):
"""logistic regression on the GPU, classes balanced, started from the difference of their means"""
X = torch.tensor(__import__("numpy").concatenate([good, neg]), device=dev)
y = torch.cat([torch.ones(len(good), device=dev), torch.zeros(len(neg), device=dev)])
wt = torch.cat([torch.full((len(good),), 0.5 / len(good), device=dev), torch.tensor(wneg, device=dev) * (0.5 / float(sum(wneg)))])
init = X[: len(good)].mean(0) - X[len(good) :].mean(0)
w = (init / (init.norm() + 1e-6) * 4).clone().requires_grad_(True)
b = torch.zeros(1, device=dev, requires_grad=True)
opt = torch.optim.Adam([w, b], lr=0.05)
for _ in range(steps):
opt.zero_grad()
logit = X @ w + b
loss = (torch.nn.functional.binary_cross_entropy_with_logits(logit, y, reduction="none") * wt).sum() + 1e-3 * (w * w).sum()
loss.backward()
opt.step()
return w.detach(), b.detach()
@app.function(image=fp_image, gpu=GPU, volumes={"/fp": fp_volume}, timeout=900)
def fingerprint_fit(workspace: str, fingerprint: str, modalities: dict) -> dict:
import json
import time
import numpy as np
import torch
dev = "cuda" if torch.cuda.is_available() else "cpu"
out = {"workspace": workspace, "fingerprint": fingerprint, "model": "embeddinggemma-2@768", "version": int(time.time() * 1000), "device": torch.cuda.get_device_name(0) if dev == "cuda" else "cpu", "modalities": {}}
for m, d in (modalities or {}).items():
if m not in ("v", "a", "t"):
continue
good, bad, bg = _vectors(d.get("good")), _vectors(d.get("bad")), _vectors(d.get("background"))
if len(good) < 3 or len(bad) + len(bg) < 3:
continue
neg = np.concatenate([bad, bg])
# a bad reference says more than an unlabelled file: three times the weight
wneg = [3.0] * len(bad) + [1.0] * len(bg)
# held-out separation, k-fold on the good side and the negatives alike
k = min(5, len(good), len(neg))
rng = np.random.default_rng(0)
gi, ni = rng.permutation(len(good)) % k, rng.permutation(len(neg)) % k
hp, hn, hb = [], [], []
for f in range(k):
w, b = _train(torch, good[gi != f], neg[ni != f], [x for x, i in zip(wneg, ni) if i != f], dev, steps=250)
hp += torch.sigmoid(torch.tensor(good[gi == f], device=dev) @ w + b).tolist()
hn += torch.sigmoid(torch.tensor(neg[ni == f], device=dev) @ w + b).tolist()
hb += [int(i) < len(bad) for i in np.where(ni == f)[0]]
w, b = _train(torch, good, neg, wneg, dev)
gs = torch.sigmoid(torch.tensor(good, device=dev) @ w + b).cpu().numpy()
out["modalities"][m] = {
"w": [round(float(x), 6) for x in w.cpu().numpy()],
"b": float(b.cpu().numpy()[0]),
"good": int(len(good)),
"bad": int(len(bad)),
"background": int(len(bg)),
"auc": _r4(_auc(np.array(hp), np.array(hn))),
# against its bad references alone, when it has any: the boundary people drew
"auc_bad": _r4(_auc(np.array(hp), np.array([s for s, x in zip(hn, hb) if x]))),
# a typical good example's score, to read a new one against
"good_median": round(float(np.median(gs)), 4),
}
if not out["modalities"]:
return {"error": "too few examples: a modality needs 3 good and 3 others"}
path = _fp_path(workspace, fingerprint)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
json.dump(out, f)
fp_volume.commit()
return {k: v for k, v in out.items() if k != "modalities"} | {"modalities": {m: {k: v for k, v in x.items() if k != "w"} for m, x in out["modalities"].items()}, "path": path}
@app.function(image=fp_image, gpu=GPU, volumes={"/fp": fp_volume}, timeout=300, scaledown_window=120)
def fingerprint_score(workspace: str, fingerprint: str, vectors: dict) -> dict:
import json
import torch
fp_volume.reload()
path = _fp_path(workspace, fingerprint)
if not os.path.exists(path):
return {"error": "this fingerprint has no model yet"}
model = json.load(open(path))
dev = "cuda" if torch.cuda.is_available() else "cpu"
scores = {}
for m, xs in (vectors or {}).items():
head = model["modalities"].get(m)
X = _vectors(xs)
if not head or not len(X):
continue
w = torch.tensor(head["w"], device=dev)
scores[m] = [round(float(s), 4) for s in torch.sigmoid(torch.tensor(X, device=dev) @ w + head["b"]).tolist()]
return {"version": model["version"], "device": torch.cuda.get_device_name(0) if dev == "cuda" else "cpu", "scores": scores, "good_median": {m: h["good_median"] for m, h in model["modalities"].items()}}
@app.function(image=indexer_image, gpu=GPU, cpu=4, memory=16384, timeout=900)
def gpu_probe() -> str:
import subprocess as sp
def run(cmd: str, t: int = 600) -> str:
r = sp.run(["bash", "-c", cmd], capture_output=True, text=True, timeout=t, cwd="/app")
return (r.stdout + r.stderr)[-3000:]
out = run("nvidia-smi | grep -o 'CUDA Version: [0-9.]*'; nvidia-smi --query-gpu=name --format=csv,noheader")
out += run("echo CUDA_VERSION=$CUDA_VERSION NV_CUDA=$NV_CUDA_LIB_VERSION LD=$LD_LIBRARY_PATH; ls -d /usr/local/cuda* 2>&1; find / -xdev \\( -name 'libcublas.so*' -o -name 'libcudart.so*' -o -name 'libcudnn.so*' \\) 2>/dev/null | head; cat /etc/os-release | head -2")
out += run("ldd node_modules/onnxruntime-node/bin/napi-v*/linux/x64/libonnxruntime_providers_cuda.so | grep 'not found' || echo 'cuda provider: every library found'")
with open("/app/probe.mjs", "w") as f:
f.write(PROBE)
out += run("node probe.mjs 2>&1 | cut -c1-300")
print(out)
return out
+113 -5
View File
@@ -8,21 +8,35 @@
# box is set up by too), and its server started
# deploy/sprites/box.sh status NAME its URL, raea, the server's health
# deploy/sprites/box.sh token NAME its RAEA_CLOUD_TOKEN, for the TypeScript client
# deploy/sprites/box.sh promote NAME the box into raea cloud's list of boxes, at the top: the one work runs on
# (POST /v1/admin/boxes; its health must answer). A box below it takes over
# by itself when it stops answering, so a box is never swapped by editing secrets
# deploy/sprites/box.sh list raea cloud's boxes in order, each one's health and build
# deploy/sprites/box.sh latest [VERSION] every box in raea cloud's list onto a release (the newest when none is
# named), once its release run has attached the Linux archive: raea and
# sdk/cloud's server both from that release's commit, each box after its running
# agents finish. tools/agents/release-go.sh runs it after every release it publishes
# deploy/sprites/box.sh key NAME a raea agent key (repos and storage scopes) from stdin, or the clipboard, onto
# the box as RAEA_AGENT_KEY: its agents clone raea projects (raea-repo clone OWNER
# PROJECT DIR, deploy/git/repo.sh), push, and send renders' media by hash (CR22, CR23)
#
# RAEA_VERSION (0.1.6) and AGENTS ("kimi-code claude-acp") pick what goes on, and RAEA_CLOUD_REF takes sdk/cloud from
# RAEA_VERSION (the newest release when unset) and AGENTS ("kimi-code claude-acp") pick what goes on, and RAEA_CLOUD_REF takes sdk/cloud from
# raea's public repo at that commit instead of this working tree; the farm comes from
# ~/.config/raea-cloud/farm.env (RAEA_CLOUD_GPU_URL, RAEA_CLOUD_GPU_TOKEN). The Sprite's URL stays private to the org.
# Game kits need ~/.config/raea-cloud/games/raea-games-linux-x86_64.tgz (raea-decompose and unity-rs built for Linux,
# checked against its .sha256 beside it); without it the box can fetch builds but not take them apart.
set -euo pipefail
# the org raea owns, never another business's (org.sh)
. "$(dirname "$0")/org.sh"
NAME=${2:-}
[ -n "$NAME" ] || { echo "box: name the Sprite"; exit 2; }
RAEA_VERSION=${RAEA_VERSION:-0.1.6}
AGENTS=${AGENTS:-kimi-code claude-acp}
[ -n "$NAME" ] || [ "${1:-}" = list ] || [ "${1:-}" = latest ] || { echo "box: name the Sprite"; exit 2; }
REPO=shinyobjectz/raea
# the newest published release (never an rc): what a box gets unless RAEA_VERSION names one
newest() { gh release view -R "$REPO" --json tagName -q .tagName 2>/dev/null | sed 's/^v//'; }
if [ -z "${RAEA_VERSION:-}" ] && [ "${1:-}" != latest ]; then RAEA_VERSION=$(newest); fi
[ -n "${RAEA_VERSION:-}" ] || [ "${1:-}" = latest ] || { echo "box: couldn't read raea's newest release (gh signed in?); set RAEA_VERSION"; exit 2; }
AGENTS=${AGENTS:-kimi-code claude-acp antigravity-acp}
HERE=$(cd "$(dirname "$0")/../.." && pwd)
FARM=${RAEA_FARM_ENV:-$HOME/.config/raea-cloud/farm.env}
@@ -38,13 +52,51 @@ up)
sprite list -o "$ORG" | grep -qx "$NAME" || sprite create -o "$ORG" --skip-console --label raea --label raea-cloud "$NAME"
# sdk/cloud's files from this working tree; with RAEA_CLOUD_REF set, setup.sh takes them from raea's public repo at
# that commit instead, as a bot's box does
if [ -z "${RAEA_CLOUD_REF:-}" ]; then
# Every build is stamped (BUILD.json on the box, shown in its health): the commit, and from a working tree whether it
# was dirty, which files, and an id from the packed files themselves; the tarball is kept under
# ~/.config/raea-cloud/builds/ID.tgz, so a box can be made again from exactly what another one runs (RAEA_CLOUD_BUILD=ID)
builds=$HOME/.config/raea-cloud/builds
if [ -n "${RAEA_CLOUD_BUILD:-}" ]; then
[ -s "$builds/$RAEA_CLOUD_BUILD.tgz" ] || { echo "box: no build $RAEA_CLOUD_BUILD in $builds"; exit 2; }
put "$builds/$RAEA_CLOUD_BUILD.tgz" /tmp/raea-cloud.tgz
put "$builds/$RAEA_CLOUD_BUILD.json" /tmp/raea-cloud-build.json
elif [ -z "${RAEA_CLOUD_REF:-}" ]; then
mkdir -p "$builds"
pack=$(mktemp)
COPYFILE_DISABLE=1 tar -czf "$pack" --no-mac-metadata -C "$HERE" server src image deploy/git package.json package-lock.json
# the id: the packed files' own contents (names and bytes, not their times)
id=$(cd "$HERE" && find server src image deploy/git package.json package-lock.json -type f -not -name '.DS_Store' -print0 | sort -z | xargs -0 shasum -a 256 | shasum -a 256 | cut -c1-12)
commit=$(git -C "$HERE" rev-parse HEAD)
dirty=$(git -C "$HERE" status --porcelain -- . | sed 's/^...//' | tr '\n' ' ')
printf '{"build":"%s","commit":"%s","dirty":%s,"changed":"%s","from":"%s"}\n' "$id" "$commit" "$([ -n "$dirty" ] && echo true || echo false)" "${dirty% }" "$(hostname -s)" > "$builds/$id.json"
cp "$pack" "$builds/$id.tgz"
echo "box: build $id (commit ${commit:0:10}$([ -n "$dirty" ] && echo ", dirty: ${dirty% }"))"
put "$pack" /tmp/raea-cloud.tgz
put "$builds/$id.json" /tmp/raea-cloud-build.json
rm -f "${pack:?}"
fi
put "$FARM" /tmp/farm.env
games=${RAEA_GAMES_TGZ:-$HOME/.config/raea-cloud/games/raea-games-linux-x86_64.tgz}
if [ -s "$games" ]; then
if [ -s "$games.sha256" ] && ! shasum -a 256 -c --status "$games.sha256"; then echo "box: $games doesn't match its .sha256"; exit 1; fi
put "$games" /tmp/raea-games.tgz
fi
# A box with agents running isn't rebuilt under them: setup.sh restarts the server, which cuts their runs off
# (11-25: a StreetTalk project failed mid-run). Waits for none, a quarter of an hour at most; RAEA_BOX_FORCE=1
# rebuilds anyway (raea cloud then resumes the cut-off runs, projects.ts resumeRequest).
if [ "${RAEA_BOX_FORCE:-}" != 1 ]; then
for i in $(seq 1 90); do
n=$(x ". ~/.raea-cloud.env 2>/dev/null; curl -fsS -m 5 -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" localhost:8080/v1/health 2>/dev/null" | python3 -c 'import json,sys
try: print(json.load(sys.stdin).get("running", "unknown"))
except Exception: print("down")')
# down: nothing to cut off; unknown: a server too old to say, so it isn't rebuilt blind
[ "$n" = 0 ] || [ "$n" = down ] && break
[ "$n" = unknown ] && { echo "box: $NAME's server doesn't say whether agents are running: rebuild it when it's idle (RAEA_BOX_FORCE=1)"; exit 1; }
[ "$i" = 90 ] && { echo "box: $NAME still has $n agents running: not rebuilt (RAEA_BOX_FORCE=1 to cut them off)"; exit 1; }
[ "$i" = 1 ] && echo "box: $NAME has $n agents running: waiting for them to finish"
sleep 10
done
fi
# the box itself, set up by the one script a bot's box is set up by too
if ! sprite exec -o "$ORG" -s "$NAME" -- bash -s -- "$NAME" "$RAEA_VERSION" "$AGENTS" "${RAEA_CLOUD_REF:-}" < "$(dirname "$0")/setup.sh" 2>&1 | quiet; then
echo "box: setup.sh failed on $NAME"; exit 1
@@ -56,6 +108,62 @@ status)
x "/opt/raea/bin/raea --version; . ~/.raea-cloud.env; curl -fsS -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" localhost:8080/v1/health | head -c 600; echo"
;;
token) x ". ~/.raea-cloud.env; echo \$RAEA_CLOUD_TOKEN" ;;
latest)
# Shane, 11-26: "make sure that release pipeline automatically updates boxes for raea cloud to the latest"
version=${2:-$(newest)}
[ -n "$version" ] || { echo "box: couldn't read raea's newest release (gh signed in?)"; exit 2; }
tag=v$version
linux=raea-$version-linux-x86_64.tar.gz
attached() { gh release view "$tag" -R "$REPO" --json assets -q '.assets[].name' 2>/dev/null | grep -qx "$linux"; }
# a box takes raea's Linux archive, which the tag's release.yml run attaches: that run is waited on to its end
if ! attached; then
# the run registers a few seconds after the tag is pushed (two minutes at most)
id=""
for _ in $(seq 1 24); do
id=$(gh run list -R "$REPO" -w release.yml -b "$tag" --json databaseId -q '.[0].databaseId' 2>/dev/null)
[ -n "$id" ] && break
sleep 5
done
[ -n "$id" ] || { echo "box: no release.yml run for $tag: no box changed"; exit 1; }
echo "box: waiting for $tag's release run ($id) to attach the Linux archive"
gh run watch "$id" -R "$REPO" --exit-status > /dev/null 2>&1 || attached || { echo "box: $tag's release run failed before its Linux archive: no box changed"; exit 1; }
attached || { echo "box: $tag's release run ended without $linux: no box changed"; exit 1; }
fi
# sdk/cloud's server from the release's own commit in the public repo, as a bot's box takes it
ref=$(gh api "repos/$REPO/commits/$tag" -q .sha) || { echo "box: couldn't read $tag's commit"; exit 1; }
names=$("$0" list | sed 's/^[* ] *//' | awk '{print $1}' | grep -v '^$') || { echo "box: couldn't list raea cloud's boxes"; exit 1; }
[ -n "$names" ] || { echo "box: raea cloud lists no boxes"; exit 1; }
failed=""
for b in $names; do
# a Sprite that's gone or whose disk died (raea-1, 11-25) is reported and passed over; the others still go
echo "box: $b onto raea $version (${ref:0:10})"
# RAEA_BOX_DRY=1: what it would do, and nothing done
[ "${RAEA_BOX_DRY:-}" = 1 ] && continue
RAEA_VERSION=$version RAEA_CLOUD_REF=$ref "$0" up "$b" || failed+=" $b"
done
"$0" list
[ "${RAEA_BOX_DRY:-}" = 1 ] && { echo "box: dry run: no box changed"; exit 0; }
[ -z "$failed" ] || { echo "box: not on $version:$failed"; exit 1; }
echo "box: every box is on raea $version"
;;
promote | list)
# raea cloud's staff key: RAEA_CLOUD_ADMIN_KEY, else the Mac's keychain (raea-cloud-prod-staff-key)
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 "box: no staff key (RAEA_CLOUD_ADMIN_KEY, or raea-cloud-prod-staff-key in the keychain)"; exit 2; }
if [ "$1" = promote ]; then
url=$(sprite url -o "$ORG" -s "$NAME" 2>&1 | sed -n 's/^URL: *//p')
tok=$(x ". ~/.raea-cloud.env; echo \$RAEA_CLOUD_TOKEN" | tail -1 | tr -d '[:space:]')
[ -n "$url" ] && [ ${#tok} -ge 32 ] || { echo "box: couldn't read $NAME's address or token"; exit 1; }
body=$(python3 -c 'import json,sys; print(json.dumps({"name": sys.argv[1], "url": sys.argv[2], "token": sys.argv[3], "first": True}))' "$NAME" "$url" "$tok")
curl -fsS -X POST -H "authorization: Bearer $key" -H 'content-type: application/json' --data-binary @- "$api/v1/admin/boxes" <<< "$body" > /dev/null || { echo "box: raea cloud refused $NAME"; exit 1; }
fi
curl -fsS -H "authorization: Bearer $key" "$api/v1/admin/boxes" | python3 -c '
import json, sys
for b in json.load(sys.stdin)["data"]:
bd = b.get("build") or {}
print(("* " if b["runs_work"] else " ") + b["name"].ljust(10), b["note"].ljust(22), "build", bd.get("build", "?"), "commit", str(bd.get("commit", "?"))[:10], "dirty" if bd.get("dirty") else "", "raea", bd.get("raea", "?"))'
;;
key)
# never echoed: from a pipe, or the clipboard when there's none
if [ -t 0 ]; then k=$(pbpaste); else k=$(cat); fi
+28 -1
View File
@@ -34,6 +34,15 @@ if [ "$(/opt/raea/bin/raea --version 2> /dev/null)" != "$VERSION" ]; then
rm -f "/tmp/$f" "/tmp/$f.sha256"
fi
# the Google sign-in's own browser (server/google-screen.ts): Chrome on a virtual display, shown over VNC
sudo -E apt-get install -y -qq --no-install-recommends xvfb x11vnc xdotool fonts-noto-color-emoji > /dev/null
command -v google-chrome > /dev/null || {
say "google chrome"
curl -fsSLo /tmp/chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo -E apt-get install -y -qq /tmp/chrome.deb > /dev/null
rm -f /tmp/chrome.deb
}
# sdk/cloud's server, client and wrapper, as the image has them (image/Dockerfile)
if [ ! -s /tmp/raea-cloud.tgz ]; then
[ -n "$REF" ] || { echo "box: no /tmp/raea-cloud.tgz and no REF to take sdk/cloud from"; exit 2; }
@@ -68,7 +77,25 @@ if [ -s /tmp/farm.env ]; then
fi
grep -q '^RAEA_CLOUD_GPU_URL=' ~/.raea-cloud.env || { echo "box: no farm (write RAEA_CLOUD_GPU_URL and RAEA_CLOUD_GPU_TOKEN to /tmp/farm.env)"; exit 2; }
umask 022
for a in $AGENTS; do raea skills install --agent "$a" > /dev/null 2>&1 || say "raea skills for $a not installed"; done
# raea's skills by raea's own agent names (the registry's ids aren't them: 11-25, every box had gone without), into the
# box's home; each client's socket links them into its own config folders (server/main.ts linkSkills)
for a in $AGENTS; do
case "$a" in claude-acp) s=claude ;; antigravity-acp | gemini) s=gemini ;; kimi-code | kimi) s=kimi ;; codex-acp) s=codex ;; *) continue ;; esac
/opt/raea/bin/raea skills install --agent "$s" > /dev/null 2>&1 || say "raea skills for $a ($s) not installed"
done
# the build, as the caller stamped it (box.sh: /tmp/raea-cloud-build.json), with what this script put on: shown on
# GET /v1/health and raea cloud's /v1/admin/boxes, so which code a box runs is never a guess
python3 - "$NAME" "$VERSION" "$REF" << 'PY' > /opt/raea-cloud/BUILD.json
import json, os, sys, datetime
b = {}
try: b = json.load(open("/tmp/raea-cloud-build.json"))
except Exception: pass
if sys.argv[3]: b.setdefault("commit", sys.argv[3]); b.setdefault("build", sys.argv[3][:12]); b.setdefault("dirty", False)
b.update(box=sys.argv[1], raea=sys.argv[2], built_at=datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"))
print(json.dumps(b))
PY
rm -f /tmp/raea-cloud-build.json
# the server, as the Sprite's HTTP service on 8080: raea on lavapipe (docs/cloud.feature CL13), renders to the farm
cat > /opt/raea-cloud/image/sprite-start.sh << 'EOF'
+7
View File
@@ -7,4 +7,11 @@ if [ -n "${RAEA_CLOUD_GPU_URL:-}" ] && [ -n "${1:-}" ]; then
*" $1 "*) exec node /opt/raea-cloud/server/offload.ts "$@" ;;
esac
fi
# what's said, by the farm's Whisper (server/words.ts): raea's own transcriber is Mac only. `raea transcribe` is the name
# agents reach for, so it's the same
case "${1:-}" in
words|transcribe) exec node /opt/raea-cloud/server/words.ts "$@" ;;
# faces cut by the frame or a seam, text too small (server/frames.ts, the farm's face detector)
frames) exec node /opt/raea-cloud/server/frames.ts "$@" ;;
esac
exec /opt/raea/bin/raea "$@"
+6 -2
View File
@@ -124,8 +124,12 @@ export function spawnFor(id?: string): Spawn {
const cmd = process.env.RAEA_AGENT_CMD
if (cmd && (!want || want === "custom")) return { id: "custom", version: "", command: sh(), args: ["-c", cmd], env: {} }
const all = installed()
const s = want ? all.find((a) => a.id === want) : all[0]
if (!s) throw new Error(want ? `${want} isn't installed in this image (installed: ${all.map((a) => a.id).join(", ") || "none"})` : "no agent is installed: build with AGENTS=..., or set RAEA_AGENT_CMD")
// no default (11-24, Shane): an agent runs only when it's named, by the request (?agent=) or the box's RAEA_AGENT,
// never whichever is installed first, so a run is never on a model nobody picked
const ids = all.map((a) => a.id).join(", ") || "none"
if (!want) throw new Error(`no agent named: pass ?agent=ID, or set RAEA_AGENT on the box (installed: ${ids})`)
const s = all.find((a) => a.id === want)
if (!s) throw new Error(`${want} isn't installed in this image (installed: ${ids})`)
return s
}
+151
View File
@@ -0,0 +1,151 @@
// A Claude subscription's token, made by Claude Code's own sign-in (`claude setup-token`) on this box, so a person
// signs in with nothing but a browser: raea cloud asks for a sign-in, shows them the claude.com link it prints, they
// sign in there and paste back the code Anthropic shows, and Claude Code prints the token (a year long, for Claude
// Code's use only). The token goes back to the caller once and is never kept here: each sign-in runs in a config
// folder of its own that's removed when it ends, and one left waiting is stopped after 15 minutes.
// POST /v1/claude-token {id, url}: a sign-in started, and the link to open
// POST /v1/claude-token/ID {code} {token}: the code pasted in; or {error}
// POST /v1/claude-token/check {token} {ok, said}: one short turn on a token
import { type ChildProcess, spawn } from "node:child_process"
import { randomBytes } from "node:crypto"
import { mkdtempSync, rmSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
interface SignIn {
child: ChildProcess
dir: string
out: string
url?: string
token?: string
ended: boolean
timer: NodeJS.Timeout
}
const waiting = new Map<string, SignIn>()
/** a program on a terminal (200x60), its input from our stdin and its screen to our stdout. script(1) was here first,
* but Claude Code never took Enter after a long code through it; written to the terminal directly, it does */
const BRIDGE = `import os, pty, select, struct, fcntl, termios, sys
pid, fd = pty.fork()
if pid == 0:
os.execvp(sys.argv[1], sys.argv[1:])
fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 60, 200, 0, 0))
while True:
r, _, _ = select.select([fd, 0], [], [])
if fd in r:
try:
b = os.read(fd, 65536)
except OSError:
break
if not b:
break
os.write(1, b)
if 0 in r:
b = os.read(0, 65536)
if not b:
break
os.write(fd, b)
os.kill(pid, 9) if os.waitpid(pid, os.WNOHANG) == (0, 0) else None
`
const CLAUDE = process.env.RAEA_CLAUDE_BIN ?? "claude"
const TOKEN = /sk-ant-oat01-[A-Za-z0-9_-]{20,}/
/** the text a terminal shows, with its escapes gone; OSC 8 links keep their address */
export const plain = (s: string) =>
s
.replace(/\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)/g, " $1 ")
.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "")
.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "")
/** the sign-in link Claude Code printed */
export const urlIn = (out: string) => /https:\/\/claude\.(?:com|ai)\/\S*oauth\/authorize\?\S+/.exec(plain(out))?.[0]
/** the token it printed once the code was accepted (on one line: the terminal is 200 columns wide, room for it; 1000 broke Enter after a long code) */
export const tokenIn = (out: string) => TOKEN.exec(plain(out))?.[0]
function end(id: string) {
const s = waiting.get(id)
if (!s) return
waiting.delete(id)
clearTimeout(s.timer)
if (s.child.exitCode === null) s.child.kill("SIGTERM")
rmSync(s.dir, { recursive: true, force: true })
}
const until = async (s: SignIn, ok: () => boolean, ms: number) => {
for (let t = 0; t < ms && !ok() && !s.ended; t += 200) await new Promise((r) => setTimeout(r, 200))
}
export async function startClaudeSignIn(env: NodeJS.ProcessEnv): Promise<{ id: string; url: string }> {
const dir = mkdtempSync(path.join(tmpdir(), "claude-sign-in-"))
const id = randomBytes(12).toString("hex")
const clean: NodeJS.ProcessEnv = { ...env, CLAUDE_CONFIG_DIR: dir, BROWSER: "true", TERM: "xterm-256color" }
for (const k of ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"]) delete clean[k]
// Claude Code on a terminal of its own (BRIDGE), 200 columns: the token fits on one line (the link is read from its
// OSC 8 address)
const child = spawn("python3", ["-I", "-c", BRIDGE, CLAUDE, "setup-token"], { cwd: dir, env: clean, stdio: ["pipe", "pipe", "pipe"] })
const s: SignIn = { child, dir, out: "", ended: false, timer: setTimeout(() => end(id), 15 * 60_000) }
waiting.set(id, s)
const read = (c: string) => {
s.out += c
s.url ??= urlIn(s.out)
s.token ??= tokenIn(s.out)
}
child.stdout!.setEncoding("utf8").on("data", read)
child.stderr!.setEncoding("utf8").on("data", read)
child.on("exit", () => (s.ended = true))
await until(s, () => !!s.url, 30_000)
if (!s.url) {
const why = plain(s.out).replace(/\s+/g, " ").trim().slice(-300)
end(id)
throw new Error(`Claude Code didn't print a sign-in link${why ? `: ${why}` : ""}`)
}
return { id, url: s.url }
}
export async function finishClaudeSignIn(id: string, code: string): Promise<{ token: string }> {
const s = waiting.get(id)
if (!s) throw new Error("that sign-in has ended (they last 15 minutes): start again")
const c = code.trim()
if (!/^[A-Za-z0-9_#.~-]{10,600}$/.test(c)) throw new Error("that doesn't look like the code claude.com showed")
const from = s.out.length
// the code as one paste, then Enter on its own a second later (Enter in the same write is taken as part of the paste)
s.child.stdin!.write(c)
await new Promise((r) => setTimeout(r, 1000))
s.child.stdin!.write("\r")
// done at the token, or as soon as Claude Code says the code was wrong
await until(s, () => !!s.token || /OAuth error|Invalid code|expired/i.test(plain(s.out.slice(from))), 60_000)
const token = s.token
const said = plain(s.out.slice(from)).replace(/\s+/g, " ").trim()
// what Claude Code said after the code, any token masked: the service log shows why a sign-in didn't finish
console.log(`raea-cloud: claude sign-in ${id.slice(0, 6)} ${token ? "got a token" : "no token"}: ${JSON.stringify(s.out.slice(from).replace(/sk-ant-[A-Za-z0-9_-]{8,}/g, "sk-ant-…")).slice(-1500)}`)
end(id)
if (!token) throw new Error(`Claude Code didn't accept the code${said ? `: ${said.slice(-300)}` : ""}`)
return { token }
}
/** whether a token (a subscription's, or an API key) gets an answer from Claude Code: one short turn, in a config folder
* of its own that's removed after. {ok, said} */
export async function checkClaude(env: NodeJS.ProcessEnv, token: string): Promise<{ ok: boolean; said: string }> {
const t = token.trim()
if (!/^sk-ant-(oat01|api03)-[A-Za-z0-9_-]{20,}$/.test(t)) throw new Error("that isn't a Claude token (sk-ant-oat01-…) or API key (sk-ant-api03-…)")
const dir = mkdtempSync(path.join(tmpdir(), "claude-check-"))
const clean: NodeJS.ProcessEnv = { ...env, CLAUDE_CONFIG_DIR: dir }
delete clean.ANTHROPIC_API_KEY
delete clean.CLAUDE_CODE_OAUTH_TOKEN
clean[t.startsWith("sk-ant-oat01-") ? "CLAUDE_CODE_OAUTH_TOKEN" : "ANTHROPIC_API_KEY"] = t
try {
const child = spawn(CLAUDE, ["-p", "Reply with just the word: ready", "--max-turns", "1"], { cwd: dir, env: clean, stdio: ["ignore", "pipe", "pipe"] })
let out = ""
child.stdout.setEncoding("utf8").on("data", (c: string) => (out += c))
child.stderr.setEncoding("utf8").on("data", (c: string) => (out += c))
const code = await new Promise<number | null>((ok) => {
const timer = setTimeout(() => child.kill("SIGTERM"), 90_000)
child.on("exit", (c) => (clearTimeout(timer), ok(c)))
})
const said = plain(out).replace(/\s+/g, " ").trim().slice(0, 400)
return { ok: code === 0 && /ready/i.test(said), said }
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
+226
View File
@@ -0,0 +1,226 @@
// `raea frames check` on a raea cloud box: what an export's pictures get wrong that a viewer sees at once, measured
// (11-25, Shane: "it cuts out faces all the time and also does split frame shots when they make no sense", "it makes
// text too small on some things, we should have a text/glyph readability check and measurement").
//
// raea frames check VIDEO [--manifest RENDER.json] [-o REPORT.json]
// faces: VIDEO's frames, two a second, through the farm's face detector (POST /v1/faces, OpenCV's YuNet; a box has
// no vision backend of its own). A face of a person in the shot (at least 6% of the frame's height) touching an
// edge is cut by the frame: for a second or more it's an error, shorter a warning.
// text: each text the render's manifest shows (raea render --manifest; a .tsx render through raea cloud writes
// VIDEO.render.json by itself), its font size in pixels of a 1080-wide frame: under 40 px is an error (no one
// reads it on a phone), under 48 px a warning (small for anything but a badge or small print).
// Exit 1 on any error. A face at the edge that's meant (someone walking out of shot) is said, with its reason, in
// VIDEO.despite.txt beside the video: its findings are then warnings.
import { spawnSync } from "node:child_process"
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
/** frames sampled a second, and the width they're read at (a face's place is in shares of the picture) */
const RATE = 2
const SIDE = 540
/** a face this share of the frame's height or more is someone in the shot, not a passer-by far behind (a split
* screen's half holds a face about this big) */
export const FACE_MIN = 0.05
/** least font sizes, in pixels of a frame 1080 wide (its shorter side): the Direct Response skill's table */
export const TEXT_ERROR = 40
export const TEXT_WARN = 48
export type Finding = { level: "error" | "warn"; kind: "face-cut" | "split" | "text-small"; at: number | null; until?: number; says: string }
/** a line where the picture jumps across nearly the whole frame (the farm's): its axis (h, a row), where, and its share */
export type Seam = [string, number, number]
export type Faces = { w: number; h: number; faces: number[][]; seams?: Seam[] } | null
type Split = { axis: "h" | "v"; at: number }
/** a frame's split-screen seams: lone lines in its middle 60% (a bar's two edges close together are a caption's box, a
* badge or a letterbox, not a seam) */
export function splitsOf(fr: NonNullable<Faces>): Split[] {
const out: Split[] = []
for (const axis of ["h", "v"] as const) {
const dim = axis === "h" ? fr.h : fr.w
const at = [...new Set((fr.seams ?? []).filter((x) => x[0] === axis).map((x) => x[1]))].sort((a, b) => a - b)
const lines = at.filter((y, i) => i === 0 || y - at[i - 1] > 4)
for (const y of lines) {
const bar = lines.some((o) => o !== y && Math.abs(o - y) < dim * 0.15)
if (!bar && y > dim * 0.2 && y < dim * 0.8) out.push({ axis, at: y })
}
}
return out
}
const near = (a: Split, b: Split) => a.axis === b.axis && Math.abs(a.at - b.at) <= 6
const big = (fr: NonNullable<Faces>) => fr.faces.filter((f) => f[3] >= fr.h * FACE_MIN)
/** what cuts a face in a frame: an edge of the frame, or a split screen's seam */
function cutBy(fr: NonNullable<Faces>, splits: Split[]): string | null {
for (const [x, y, fw, fh] of big(fr)) {
if (x <= 1) return "the left edge"
if (x + fw >= fr.w - 1) return "the right edge"
if (y <= 1) return "the top edge"
if (y + fh >= fr.h - 1) return "the bottom edge"
for (const sp of splits) {
const [a, b] = sp.axis === "h" ? [y, y + fh] : [x, x + fw]
if ((a < sp.at - 2 && b > sp.at + 2) || Math.abs(b - sp.at) <= 3 || Math.abs(a - sp.at) <= 3) return "the split screen's seam"
}
}
return null
}
/** runs of the same thing in consecutive frames, as [from, to) in frames */
function runs<T>(xs: (T | null)[], same: (a: T, b: T) => boolean = (a, b) => a === b): [number, number, T][] {
const out: [number, number, T][] = []
for (let i = 0; i < xs.length; ) {
const x = xs[i]
if (x === null) {
i++
continue
}
let j = i + 1
while (j < xs.length && xs[j] !== null && same(x, xs[j] as T)) j++
out.push([i, j, x])
i = j
}
return out
}
/** faces cut by the frame's edges or a split screen's seam (a second or more an error, shorter a warning), and split
* screens that hold one person (a split is for two things at once) */
export function cutFaces(frames: Faces[], rate = RATE): Finding[] {
const raw = frames.map((fr) => (fr ? splitsOf(fr) : []))
// a seam held for a second or more: a split screen; a line for a frame is a cut or a flash
const held = raw.map((ss, i) => ss.filter((s) => (raw[i - 1] ?? []).some((o) => near(s, o)) || (raw[i + 1] ?? []).some((o) => near(s, o))))
const out: Finding[] = []
const hits = frames.map((fr, i) => (fr ? cutBy(fr, held[i]) : null))
for (const [i, j, by] of runs(hits)) {
const from = i / rate
const to = j / rate
out.push({ level: to - from >= 1 ? "error" : "warn", kind: "face-cut", at: from, until: to, says: `a face is cut by ${by} from ${from.toFixed(1)} s to ${to.toFixed(1)} s: reframe on the person (both eyes, mouth and chin inside the picture)${by.includes("seam") ? ", or cut between two singles" : " or cut away"}` })
}
const split = held.map((ss) => ss[0] ?? null)
for (const [i, j, sp] of runs(split, near)) {
if (j - i < 2) continue
// whose face is on each side of the seam, frame by frame
let one = 0
let any = 0
for (let k = i; k < j; k++) {
const fr = frames[k]
if (!fr) continue
const sides = new Set(big(fr).map(([x, y, fw, fh]) => ((sp.axis === "h" ? y + fh / 2 : x + fw / 2) < sp.at ? 0 : 1)))
if (sides.size) any++
if (sides.size === 1) one++
}
const from = i / rate
const to = j / rate
const where = sp.axis === "h" ? "top and bottom" : "side by side"
if (any && one * 2 > any) out.push({ level: "warn", kind: "split", at: from, until: to, says: `a split screen (${where}) from ${from.toFixed(1)} s to ${to.toFixed(1)} s shows a face in only one half: split only for two things at once (two people reacting, a face and the product), else cut between singles` })
}
return out
}
/** texts under the size floor, from a render manifest: each text once, at its first frame */
export function smallText(manifest: any): Finding[] {
const w = Number(manifest?.width) || 1080
const h = Number(manifest?.height) || 1920
const fps = Number(manifest?.fps) || 30
const scale = 1080 / Math.min(w, h)
const seen = new Map<string, { at: number; px: number }>()
for (const fr of (manifest?.frames ?? []) as any[]) {
for (const t of (fr?.text ?? []) as any[]) {
const text = String(t?.text ?? "").trim()
if (!text || (t?.opacity ?? 1) <= 0.05) continue
const px = Number(t?.size) * scale
if (!Number.isFinite(px) || px <= 0) continue
const was = seen.get(text)
if (!was || px > was.px) seen.set(text, { at: was?.at ?? Number(fr?.frame ?? 0) / fps, px })
}
}
const out: Finding[] = []
for (const [text, { at, px }] of seen) {
const q = text.length > 40 ? `"${text.slice(0, 40)}..."` : `"${text}"`
if (px < TEXT_ERROR) out.push({ level: "error", kind: "text-small", at, says: `${q} is ${px.toFixed(0)} px (in a 1080-wide frame): under ${TEXT_ERROR} px no one reads it on a phone. Make it bigger, or cut words so it fits bigger` })
else if (px < TEXT_WARN) out.push({ level: "warn", kind: "text-small", at, says: `${q} is ${px.toFixed(0)} px: small for anything but a badge or small print (captions 52 px, hooks 64 px)` })
}
return out.sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
}
function ffmpeg(args: string[]) {
const r = spawnSync("ffmpeg", args, { encoding: "utf8" })
if (r.status !== 0) throw new Error(`ffmpeg: ${(r.stderr ?? "").slice(-400)}`)
}
/** VIDEO's faces, two frames a second, by the farm */
export async function faces(file: string, f: typeof fetch = fetch): Promise<Faces[]> {
const url = process.env.RAEA_CLOUD_GPU_URL
const token = process.env.RAEA_CLOUD_GPU_TOKEN ?? ""
if (!url) throw new Error("the faces check needs the farm (RAEA_CLOUD_GPU_URL); this box has none set")
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-frames-"))
try {
ffmpeg(["-v", "error", "-y", "-i", file, "-vf", `fps=${RATE},scale='if(gt(iw,ih),-2,${SIDE})':'if(gt(iw,ih),${SIDE},-2)'`, "-q:v", "4", path.join(dir, "f%05d.jpg")])
const jpgs = readdirSync(dir).filter((n) => n.endsWith(".jpg")).sort()
const out: Faces[] = []
for (let i = 0; i < jpgs.length; i += 300) {
const body = JSON.stringify({ frames: jpgs.slice(i, i + 300).map((n) => readFileSync(path.join(dir, n)).toString("base64")) })
let r: Response | undefined
let why = ""
for (let k = 0; k < 4; k++) {
r = await f(`${url.replace(/\/$/, "")}/v1/faces`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body, signal: AbortSignal.timeout(300_000) })
if (r.ok) break
why = `${r.status} ${(await r.text()).slice(0, 300)}`
if (r.status < 500) break
await new Promise((ok) => setTimeout(ok, 1000 * 2 ** k))
}
if (!r?.ok) throw new Error(`the farm couldn't look at ${path.basename(file)}: ${why}`)
out.push(...((await r.json()) as { frames: Faces[] }).frames)
}
return out
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
function flag(args: string[], name: string): string | undefined {
const i = args.indexOf(name)
return i >= 0 ? args[i + 1] : undefined
}
/** the manifest a render of VIDEO wrote: --manifest, or VIDEO.render.json beside it */
export const manifestOf = (video: string) => `${video.slice(0, video.length - path.extname(video).length)}.render.json`
export async function main(args: string[]): Promise<number> {
const a = args[0] === "check" ? args.slice(1) : args
const video = a.find((x, i) => !x.startsWith("-") && !["--manifest", "-o"].includes(a[i - 1] ?? ""))
if (!video || !existsSync(video)) {
console.error("usage: raea frames check VIDEO [--manifest RENDER.json] [-o REPORT.json] (faces cut by the frame, and text too small to read)")
return 2
}
const m = flag(a, "--manifest") ?? manifestOf(video)
const found: Finding[] = []
let looked = 0
try {
const fr = await faces(video)
looked = fr.length
found.push(...cutFaces(fr))
} catch (e) {
console.log(`WARN the faces check couldn't run: ${(e as Error).message}`)
}
const texts = existsSync(m) ? smallText(JSON.parse(readFileSync(m, "utf8"))) : null
if (texts) found.push(...texts)
const despite = `${video.slice(0, video.length - path.extname(video).length)}.despite.txt`
const why = existsSync(despite) ? readFileSync(despite, "utf8").trim() : ""
const out = found.map((x) => (why && x.kind === "face-cut" ? { ...x, level: "warn" as const, says: `${x.says} (despite: ${why.slice(0, 200)})` } : x)).sort((p, q) => (p.at ?? 0) - (q.at ?? 0))
for (const x of out) console.log(`${x.level === "error" ? "ERROR" : "WARN "} ${x.at === null ? "" : `${x.at.toFixed(1)} s `}${x.says}`)
const errors = out.filter((x) => x.level === "error").length
const report = flag(a, "-o") ?? `${video.slice(0, video.length - path.extname(video).length)}.frames-check.json`
writeFileSync(report, JSON.stringify({ video, looked_at: looked, text_checked: texts !== null, findings: out }, null, 1))
console.log(`${errors ? "FAILED" : "PASSED"} ${path.basename(video)}: ${looked} frames looked at for faces, ${texts === null ? "no manifest for its text" : `${new Set(texts.map((t) => t.says)).size} small texts`}, ${errors} errors, ${out.length - errors} warnings; ${path.basename(report)}`)
return errors ? 1 : 0
}
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
const a = process.argv.slice(2)
main(a[0] === "frames" ? a.slice(1) : a).then(
(c) => process.exit(c),
(e) => (console.error(`raea frames: ${(e as Error).message}`), process.exit(1)),
)
}
+130
View File
@@ -0,0 +1,130 @@
// The Google sign-in's own browser (11-24, Shane: "I don't want people having to do it themselves"). Antigravity's
// Google sign-in sends the browser back to 127.0.0.1 on the machine it runs on, so a browser on the person's computer
// lands on a page that can't load. Here the sign-in runs in a Chrome on the box instead, on a virtual display of its
// own, and the person sees and works it from the dashboard over VNC (RFB, carried on a WebSocket: main.ts
// /v1/google-token/ID/screen). Google's last step then lands on Antigravity's listener on the box and the sign-in
// finishes by itself, 2-step verification and all (checked 11-24 on Shane's account).
//
// Each sign-in gets its own display, Chrome profile (in the sign-in's folder, so the Google session it holds is removed
// with it) and VNC port; all three stop when the sign-in ends. With no Chrome installed there's no screen, and the
// sign-in falls back to the pasted address.
import { type ChildProcess, spawn, spawnSync } from "node:child_process"
import { existsSync, readFileSync, rmSync } from "node:fs"
import { connect } from "node:net"
import path from "node:path"
/** the screen's size: Google's sign-in fits it, and the dashboard's panel scales it */
export const SCREEN = { width: 960, height: 760 }
const CHROMES = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]
export interface Screen {
/** the VNC server's port on 127.0.0.1 */
port: number
/** whether it's still up */
up(): boolean
stop(): void
}
const which = (bin: string) => spawnSync("sh", ["-c", `command -v ${bin}`], { encoding: "utf8" }).stdout.trim()
const chrome = () => process.env.RAEA_CHROME || CHROMES.map(which).find(Boolean) || ""
/** whether this box can show a sign-in: Chrome, a virtual display and a VNC server */
export const canShow = () => !!chrome() && !!which("Xvfb") && !!which("x11vnc")
const until = async (ok: () => boolean, ms: number) => {
for (let t = 0; t < ms && !ok(); t += 100) await new Promise((r) => setTimeout(r, 100))
return ok()
}
const listening = (port: number) =>
new Promise<boolean>((ok) => {
const s = connect(port, "127.0.0.1")
s.once("connect", () => (s.destroy(), ok(true)))
s.once("error", () => ok(false))
})
const alive = (pid: number) => {
try {
process.kill(pid, 0)
return true
} catch {
return false
}
}
/** the first display number from 100 that's free: no X server holds it (a socket and lock left by one that's gone,
* as a restart of the service leaves them, are cleared) */
function freeDisplay(): number {
for (let n = 100; n < 400; n++) {
const sock = `/tmp/.X11-unix/X${n}`, lock = `/tmp/.X${n}-lock`
const pid = existsSync(lock) ? Number(readFileSync(lock, "utf8").trim()) : 0
if (pid && alive(pid)) continue
if (existsSync(sock) || existsSync(lock)) {
try {
rmSync(sock, { force: true })
rmSync(lock, { force: true })
} catch {
continue
}
}
return n
}
throw new Error("no free display for the sign-in's browser")
}
/** whether Chrome has a window up on display n (xdotool; without it, assumed so) */
const windowUp = (n: number) => {
if (!which("xdotool")) return true
const r = spawnSync("xdotool", ["search", "--onlyvisible", "--class", "chrome"], { env: { ...process.env, DISPLAY: `:${n}` }, encoding: "utf8" })
return r.status === 0 && r.stdout.trim() !== ""
}
/** a Chrome on a display of its own at url, served over VNC on 127.0.0.1; its profile is under dir */
export async function openScreen(dir: string, url: string): Promise<Screen> {
const bin = chrome()
if (!bin) throw new Error("no Chrome on this box")
const n = freeDisplay()
const port = 5900 + n
const kids: ChildProcess[] = []
const stop = () => {
for (const k of kids.reverse()) if (k.exitCode === null && k.signalCode === null) k.kill("SIGTERM")
}
try {
const x = spawn("Xvfb", [`:${n}`, "-screen", "0", `${SCREEN.width}x${SCREEN.height}x24`, "-nolisten", "tcp"], { stdio: "ignore" })
kids.push(x)
if (!(await until(() => existsSync(`/tmp/.X11-unix/X${n}`) || x.exitCode !== null, 10_000)) || x.exitCode !== null) throw new Error("the virtual display didn't start")
const env = { ...process.env, DISPLAY: `:${n}` }
// no sandbox: the box's container has no user namespaces for it (test-type keeps Chrome from warning about that in
// a bar across Google's page; pages can't see either flag); the window is an app window (no tabs or address
// bar), the whole screen, and keeps its passwords in its profile (no keyring to ask about)
kids.push(
spawn(
bin,
[
"--no-sandbox",
"--test-type",
"--disable-gpu",
"--disable-dev-shm-usage",
"--no-first-run",
"--no-default-browser-check",
"--password-store=basic",
`--user-data-dir=${path.join(dir, "chrome")}`,
"--window-position=0,0",
`--window-size=${SCREEN.width},${SCREEN.height}`,
`--app=${url}`,
],
{ env, stdio: "ignore" },
),
)
kids.push(spawn("x11vnc", ["-display", `:${n}`, "-localhost", "-nopw", "-forever", "-shared", "-quiet", "-rfbport", String(port)], { env, stdio: "ignore" }))
let ok = false
for (let t = 0; t < 10_000 && !ok; t += 200) {
ok = await listening(port)
if (!ok) await new Promise((r) => setTimeout(r, 200))
}
if (!ok) throw new Error("the sign-in's screen didn't start")
// the page, not a black screen: a fresh Chrome profile takes a while on the box's CPU (about 20 s seen 11-24)
for (let t = 0; t < 45_000 && !windowUp(n); t += 300) await new Promise((r) => setTimeout(r, 300))
} catch (e) {
stop()
throw e
}
return { port, up: () => kids.every((k) => k.exitCode === null && k.signalCode === null), stop }
}
+308
View File
@@ -0,0 +1,308 @@
// A Google AI subscription (Google One AI Pro or Ultra) for the box's Gemini agent, Google Antigravity (the ACP
// registry's antigravity-acp). Since 2026-06-18 Gemini CLI refuses personal Google sign-ins, and Antigravity is where
// Google sends them; it is also where Pro and Ultra get Gemini 4 Neon. Its "Log in with Google" (ACP method
// oauth-personal) is an OAuth sign-in whose address sends the browser back to 127.0.0.1 on the machine it runs on.
// Here that machine is the box, so the person signs in in their own browser, lands on a page that doesn't load (their
// computer has nothing on that port), and pastes that page's address back; the box hands it to Antigravity's own
// listener on 127.0.0.1, exactly as their browser would have.
//
// Off macOS Antigravity keeps its Google token as one JSON file under GEMINI_HOME. After a sign-in that file goes back
// to the caller once, as one string (agy1:BASE64 of {path under GEMINI_HOME: text}), and is never kept here: each
// sign-in runs in a folder of its own that's removed when it ends, and one left waiting is stopped after 15 minutes.
// An agent socket that's given the string (x-raea-agent-env RAEA_GOOGLE_CREDENTIAL, main.ts) has it written into its
// own GEMINI_HOME before Antigravity starts.
// Where the box has a Chrome (google-screen.ts) the sign-in can run in a browser on the box instead, which the person
// works from the dashboard: Google's last step then reaches Antigravity's listener on its own, and nothing is pasted.
// POST /v1/google-token {screen?} {id, url, screen}: a sign-in started, the link to open, and whether it
// runs in the box's own browser (WS /v1/google-token/ID/screen shows it)
// POST /v1/google-token/ID {address?} {credential, email?}: with the address the browser landed on; with none,
// once the box's browser has finished it ({pending: true} while it hasn't,
// after waiting up to 25 s); or {error}
// POST /v1/google-token/check {credential} {ok, said, models, current}: one short turn on a credential or a Gemini
// API key (AIza…)
import { type ChildProcess, spawn } from "node:child_process"
import { randomBytes } from "node:crypto"
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { spawnFor } from "./agents.ts"
import { canShow, openScreen, type Screen } from "./google-screen.ts"
export const GOOGLE_AGENT = process.env.RAEA_GOOGLE_AGENT ?? "antigravity-acp"
const PREFIX = "agy1:"
const API_KEY = /^AIza[0-9A-Za-z_-]{30,}$/
/** what never reaches Antigravity from the container: its own Google sign-ins and keys */
const GOOGLE_ENV = ["GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_PROJECT", "GOOGLE_GENAI_USE_VERTEXAI", "GEMINI_HOME"]
// ---- one Antigravity process, spoken to over ACP on its stdin and stdout ----
interface Agy {
child: ChildProcess
/** everything it printed, both streams (its sign-in link goes to either) */
out: string
ended: boolean
request<T = any>(method: string, params: Record<string, unknown>, ms?: number): Promise<T>
onUpdate?: (u: any) => void
}
function startAgy(env: NodeJS.ProcessEnv, home: string, cwd: string, own: Record<string, string> = {}): Agy {
const a = spawnFor(GOOGLE_AGENT)
const clean: NodeJS.ProcessEnv = { ...env, ...a.env }
for (const k of GOOGLE_ENV) delete clean[k]
Object.assign(clean, own, { GEMINI_HOME: home, AGY_ACP_FORCE_FILE_STORAGE: "1", BROWSER: "true", NO_BROWSER: "true" })
const child = spawn(a.command, a.args, { cwd, env: clean, stdio: ["pipe", "pipe", "pipe"] })
const pending = new Map<number, { ok: (v: any) => void; no: (e: Error) => void }>()
let next = 1
let buf = ""
const agy: Agy = {
child,
out: "",
ended: false,
request(method, params, ms = 60_000) {
if (agy.ended) return Promise.reject(new Error(`Antigravity has stopped: ${tail(agy.out)}`))
const id = next++
return new Promise((ok, no) => {
const t = setTimeout(() => (pending.delete(id), no(new Error(`Antigravity didn't answer ${method} in ${ms / 1000} s`))), ms)
pending.set(id, { ok: (v) => (clearTimeout(t), ok(v)), no: (e) => (clearTimeout(t), no(e)) })
child.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n")
})
},
}
child.stdout!.setEncoding("utf8").on("data", (c: string) => {
agy.out += c
buf += c
for (let i; (i = buf.indexOf("\n")) >= 0; ) {
const line = buf.slice(0, i).trim()
buf = buf.slice(i + 1)
if (!line.startsWith("{")) continue
let m: any
try {
m = JSON.parse(line)
} catch {
continue
}
if (m.id !== undefined && m.method === undefined) {
const p = pending.get(m.id)
pending.delete(m.id)
if (m.error) p?.no(new Error(m.error.message ?? JSON.stringify(m.error)))
else p?.ok(m.result)
} else if (m.method === "session/update") agy.onUpdate?.(m.params?.update)
else if (m.id !== undefined) {
// its requests to us: a permission is granted (a check asks for none), anything else refused
const o = m.params?.options?.find((x: any) => x.kind === "allow_once") ?? m.params?.options?.[0]
const reply = m.method === "session/request_permission" && o ? { result: { outcome: { outcome: "selected", optionId: o.optionId } } } : { error: { code: -32601, message: `no ${m.method} here` } }
child.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id: m.id, ...reply }) + "\n")
}
}
})
child.stderr!.setEncoding("utf8").on("data", (c: string) => (agy.out += c))
child.on("exit", () => {
agy.ended = true
for (const p of pending.values()) p.no(new Error(`Antigravity stopped: ${tail(agy.out)}`))
pending.clear()
})
return agy
}
const initialize = (a: Agy) => a.request("initialize", { protocolVersion: 1, clientCapabilities: {}, clientInfo: { name: "raea-cloud", version: "1" } })
/** its last words, without its Python warnings or log prefixes */
const tail = (out: string) =>
out
.split("\n")
.filter((l) => l.trim() && !/SyntaxWarning|^\s*[IW]\d{4} /.test(l))
.slice(-3)
.join(" ")
.slice(-300)
/** the Google sign-in link Antigravity printed, and where it sends the browser back to */
export function linkIn(out: string): { url: string; port: number; state: string } | undefined {
const m = /https:\/\/accounts\.google\.com\/o\/oauth2\/[^\s"']+/.exec(out)
if (!m) return undefined
const u = new URL(m[0])
const back = new URL(u.searchParams.get("redirect_uri") ?? "")
if (!/^(127\.0\.0\.1|localhost|\[::1\])$/.test(back.hostname)) return undefined
return { url: m[0], port: Number(back.port), state: u.searchParams.get("state") ?? "" }
}
/** the address the person's browser landed on, checked against the sign-in it belongs to: the query to hand on */
export function landedQuery(address: string, s: { port: number; state: string }): string {
let u: URL
try {
u = new URL(address.trim())
} catch {
throw new Error("paste the whole address of the page Google sent you to (it starts http://127.0.0.1)")
}
if (!/^(127\.0\.0\.1|localhost|\[::1\])$/.test(u.hostname) || Number(u.port) !== s.port) throw new Error("that address isn't the page this sign-in sent you to: sign in from the newest link")
if (u.searchParams.get("error")) throw new Error(`Google said ${u.searchParams.get("error")}`)
if (!u.searchParams.get("code")) throw new Error("that address has no code in it: copy it from the browser's address bar after you approve")
if (u.searchParams.get("state") !== s.state) throw new Error("that address is from another sign-in: sign in from the newest link")
return `${u.pathname}${u.search}`
}
// ---- the credential: the files under GEMINI_HOME that hold a refresh token, as one string ----
export function packCredential(home: string): string | undefined {
const files: Record<string, string> = {}
const walk = (dir: string) => {
for (const d of readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, d.name)
if (d.isDirectory()) walk(p)
else if (d.isFile() && d.name.endsWith(".json") && statSync(p).size < 64_000) {
const text = readFileSync(p, "utf8")
if (/"refresh_token"\s*:/.test(text)) files[path.relative(home, p)] = text
}
}
}
walk(home)
return Object.keys(files).length ? PREFIX + Buffer.from(JSON.stringify(files)).toString("base64") : undefined
}
/** writes a credential's files into an agent's GEMINI_HOME, 0600 under 0700 folders; each path stays inside it */
export function unpackCredential(credential: string, home: string): void {
if (!credential.startsWith(PREFIX)) throw new Error("that isn't a Google sign-in from raea cloud")
let files: Record<string, unknown>
try {
files = JSON.parse(Buffer.from(credential.slice(PREFIX.length), "base64").toString("utf8"))
} catch {
throw new Error("that Google sign-in can't be read")
}
for (const [rel, text] of Object.entries(files)) {
const p = path.resolve(home, rel)
if (typeof text !== "string" || !p.startsWith(path.resolve(home) + path.sep)) throw new Error("that Google sign-in names a file outside its folder")
mkdirSync(path.dirname(p), { recursive: true, mode: 0o700 })
writeFileSync(p, text, { mode: 0o600 })
}
}
/** the account a credential is for, when its token file says */
const emailIn = (credential: string): string | undefined => /"email"\s*:\s*"([^"]+@[^"]+)"/.exec(Buffer.from(credential.slice(PREFIX.length), "base64").toString("utf8"))?.[1]
// ---- signing in ----
interface SignIn {
agy: Agy
dir: string
home: string
port: number
state: string
authed: boolean
failed?: string
timer: NodeJS.Timeout
/** the box's own browser for it, when it runs there */
screen?: Screen
}
const waiting = new Map<string, SignIn>()
function end(id: string) {
const s = waiting.get(id)
if (!s) return
waiting.delete(id)
clearTimeout(s.timer)
s.screen?.stop()
if (s.agy.child.exitCode === null) s.agy.child.kill("SIGTERM")
rmSync(s.dir, { recursive: true, force: true })
}
const until = async (ok: () => boolean, ms: number) => {
for (let t = 0; t < ms && !ok(); t += 200) await new Promise((r) => setTimeout(r, 200))
}
export async function startGoogleSignIn(env: NodeJS.ProcessEnv, o: { screen?: boolean } = {}): Promise<{ id: string; url: string; screen: boolean }> {
const dir = mkdtempSync(path.join(tmpdir(), "google-sign-in-"))
const home = path.join(dir, ".gemini")
mkdirSync(home, { mode: 0o700 })
const agy = startAgy(env, home, dir)
const id = randomBytes(12).toString("hex")
try {
await initialize(agy)
} catch (e) {
agy.child.kill("SIGTERM")
rmSync(dir, { recursive: true, force: true })
throw new Error(`Antigravity didn't start: ${(e as Error).message}`)
}
const s: SignIn = { agy, dir, home, port: 0, state: "", authed: false, timer: setTimeout(() => end(id), 15 * 60_000) }
waiting.set(id, s)
// authenticate answers only once the browser has come back: it waits for the whole sign-in
agy.request("authenticate", { methodId: "oauth-personal" }, 15 * 60_000).then(
() => (s.authed = true),
(e: Error) => (s.failed = e.message),
)
await until(() => !!linkIn(agy.out) || !!s.failed || agy.ended, 30_000)
const link = linkIn(agy.out)
if (!link) {
const why = s.failed ?? tail(agy.out)
end(id)
throw new Error(`Antigravity didn't print a Google sign-in link${why ? `: ${why}` : ""}`)
}
s.port = link.port
s.state = link.state
// the box's own browser, when asked for and there is one; else the person signs in in theirs and pastes
if (o.screen && canShow()) {
try {
s.screen = await openScreen(dir, link.url)
} catch (e) {
console.error(`raea-cloud: google sign-in ${id.slice(0, 6)}: no screen, the address is pasted instead:`, (e as Error).message)
}
}
return { id, url: link.url, screen: !!s.screen }
}
/** the VNC port of a sign-in's own browser, while it's up */
export function screenPort(id: string): number | undefined {
const s = waiting.get(id)
return s?.screen?.up() ? s.screen.port : undefined
}
export async function finishGoogleSignIn(id: string, address?: string): Promise<{ credential: string; email?: string } | { pending: true }> {
const s = waiting.get(id)
if (!s) throw new Error("that sign-in has ended (they last 15 minutes): start again")
let r: { ok: boolean; status: number; statusText: string } = { ok: true, status: 200, statusText: "" }
if (address) {
const q = landedQuery(address, s)
// the browser's visit to Antigravity's listener, made from the box
r = await fetch(`http://127.0.0.1:${s.port}${q}`, { signal: AbortSignal.timeout(30_000) }).catch((e: Error) => ({ ok: false, status: 0, statusText: e.message }))
await until(() => s.authed || !!s.failed || s.agy.ended, 60_000)
} else {
// the box's own browser finishes it: wait a while, and say it's still going if it hasn't (the caller asks again)
await until(() => s.authed || !!s.failed || s.agy.ended, 25_000)
if (!s.authed && !s.failed && !s.agy.ended) return { pending: true }
}
const credential = s.authed ? packCredential(s.home) : undefined
const why = s.failed ?? (r.ok ? tail(s.agy.out) : `its sign-in page answered ${r.status || r.statusText}`)
console.log(`raea-cloud: google sign-in ${id.slice(0, 6)} ${credential ? "got a credential" : `no credential: ${why}`}`)
end(id)
if (!credential) throw new Error(`Google's sign-in didn't finish${why ? `: ${why}` : ""}`)
return { credential, email: emailIn(credential) }
}
/** whether a credential (or a Gemini API key) gets an answer from Antigravity: one short turn in a folder of its own
* that's removed after; the models it offers that account, and the one it picked */
export async function checkGoogle(env: NodeJS.ProcessEnv, credential: string): Promise<{ ok: boolean; said: string; models: { id: string; name: string }[]; current?: string }> {
const c = credential.trim()
const key = API_KEY.test(c)
if (!key && !c.startsWith(PREFIX)) throw new Error("that isn't a Google sign-in from raea cloud or a Gemini API key (AIza…)")
const dir = mkdtempSync(path.join(tmpdir(), "google-check-"))
const home = path.join(dir, ".gemini")
mkdirSync(home, { mode: 0o700 })
if (!key) unpackCredential(c, home)
const agy = startAgy(env, home, dir, key ? { GEMINI_API_KEY: c } : {})
let said = ""
agy.onUpdate = (u) => {
if (u?.sessionUpdate === "agent_message_chunk" && u.content?.type === "text") said += u.content.text ?? ""
}
const timer = setTimeout(() => agy.child.kill("SIGTERM"), 120_000)
try {
await initialize(agy)
// with a good credential it signs in from the file; a link printed means Google wants a new sign-in
const auth = agy.request("authenticate", { methodId: key ? "gemini-api-key" : "oauth-personal" }, 45_000)
await Promise.race([auth, until(() => !!linkIn(agy.out), 45_000).then(() => linkIn(agy.out) && Promise.reject(new Error("Google wants this account signed in again")))])
const s = await agy.request<{ sessionId: string; models?: { availableModels?: { modelId: string; name?: string }[]; currentModelId?: string } }>("session/new", { cwd: dir, mcpServers: [] })
const models = (s.models?.availableModels ?? []).map((m) => ({ id: m.modelId, name: m.name ?? m.modelId }))
await agy.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "Reply with just the word: ready" }] }, 90_000)
said = said.replace(/\s+/g, " ").trim().slice(0, 400)
return { ok: /ready/i.test(said), said, models, current: s.models?.currentModelId }
} catch (e) {
return { ok: false, said: (e as Error).message.slice(0, 400), models: [] }
} finally {
clearTimeout(timer)
if (agy.child.exitCode === null) agy.child.kill("SIGTERM")
rmSync(dir, { recursive: true, force: true })
}
}
+184 -5
View File
@@ -11,8 +11,22 @@
// (10 min unless given, 1 h at most) its process group is stopped and the last
// line says {exit, timed_out: true}. For an agent's shell tool (raea cloud)
// POST /v1/login?agent=ID an agent's terminal sign-in: {url, code, state, output}; GET says where it is
// POST /v1/claude-token a Claude subscription sign-in in a browser: {id, url} (claude-token.ts)
// POST /v1/claude-token/ID {code} the code claude.com showed, in: {token}, handed back once and never kept
// POST /v1/claude-token/check {token} one short Claude Code turn on it: {ok, said}
// POST /v1/google-token {screen?} a Google AI subscription sign-in (Antigravity): {id, url, screen} (google-token.ts)
// POST /v1/google-token/ID {address?} the address Google's sign-in landed on, in (none when it ran in the box's own
// browser): {credential, email?}, handed back once, or {pending: true}
// WS /v1/google-token/ID/screen the box's own browser for that sign-in, over VNC (google-screen.ts)
// POST /v1/google-token/check {credential} one short Antigravity turn on it (or a Gemini API key): {ok, said, models}
// 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
// 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
// model keys below, and x-raea-agent-home: a short name. That socket's agent gets
// only those keys (never the container's) and its own config folder under
// ~/.agent-homes/NAME, so one client's sign-in never runs another's work. A
// Google sign-in (RAEA_GOOGLE_CREDENTIAL) is the one thing written: its token
// file, into that socket's own GEMINI_HOME, where Antigravity reads it.
// POST /v1/jobs?args=JSON a render job: a folder in (tar.zst), `raea ARGS` on it, followed with
// GET /v1/jobs/ID?from=N short requests, and the files it made back from /out (jobs.ts); how a CPU
// GET /v1/jobs/ID/out box hands renders to a GPU worker (offload.ts)
@@ -22,13 +36,17 @@
import { execFileSync, spawn } from "node:child_process"
import { timingSafeEqual } from "node:crypto"
import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"
import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
import path from "node:path"
import { WebSocketServer } from "ws"
import { installed, spawnFor } from "./agents.ts"
import { guard } from "./memguard.ts"
import { device } from "./gpu.ts"
import * as jobs from "./jobs.ts"
import { checkClaude, finishClaudeSignIn, startClaudeSignIn } from "./claude-token.ts"
import { checkGoogle, finishGoogleSignIn, screenPort, startGoogleSignIn, unpackCredential } from "./google-token.ts"
import { connect as tcp } from "node:net"
import { login, loginState } from "./login.ts"
import { Outside, resolve, WORK } from "./workspace.ts"
@@ -48,6 +66,83 @@ const childEnv = (): NodeJS.ProcessEnv => {
}
let version: string | undefined
/** the model keys a caller may hand one agent process, and the config folder each agent keeps its state in */
const AGENT_KEYS = ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY", "CODEX_API_KEY", "GEMINI_API_KEY"] as const
const AGENT_HOMES: Record<string, string> = { CLAUDE_CONFIG_DIR: "claude", CODEX_HOME: "codex", GEMINI_CLI_HOME: "gemini", GEMINI_HOME: "gemini/.gemini" }
/** a Google sign-in's token file (google-token.ts), written into the socket's GEMINI_HOME rather than handed on */
const GOOGLE_CREDENTIAL = "RAEA_GOOGLE_CREDENTIAL"
/** the agent processes running for open sockets now (GET /v1/health running) */
const running = new Set<unknown>()
/** the box's build, as setup.sh wrote it (/opt/raea-cloud/BUILD.json); null on a box made before builds were stamped */
function buildOf(): Record<string, unknown> | null {
try {
return JSON.parse(readFileSync(path.join(process.env.RAEA_CLOUD_ROOT ?? "/opt/raea-cloud", "BUILD.json"), "utf8"))
} catch {
return null
}
}
/** raea's skills, installed once in the box's own home (setup.sh), linked into a socket's own config folders: each
* client's agent gets its own home (AGENT_HOMES), which had left them without raea's skills (11-25) */
const SKILL_DIRS: Record<string, string> = { CLAUDE_CONFIG_DIR: ".claude/skills", GEMINI_HOME: ".gemini/skills" }
function linkSkills(env: Record<string, string>, home: string) {
for (const [k, rel] of Object.entries(SKILL_DIRS)) {
const from = path.join(home, rel)
const to = path.join(env[k], "skills")
try {
if (existsSync(from) && !existsSync(to)) symlinkSync(from, to)
} catch {
// a folder of its own already there: left alone
}
}
}
/** a socket's own sign-in (its headers), or null to run on the container's environment */
export function socketEnv(headers: Record<string, string | string[] | undefined>, home = process.env.HOME ?? "/root"): Record<string, string> | null {
const raw = headers["x-raea-agent-env"]
if (typeof raw !== "string" || !raw) return null
let given: Record<string, unknown>
try {
given = JSON.parse(raw)
} catch {
throw new Error("x-raea-agent-env isn't JSON")
}
const env: Record<string, string> = {}
for (const k of AGENT_KEYS) {
const v = given[k]
if (typeof v === "string" && v) env[k] = v
}
const google = typeof given[GOOGLE_CREDENTIAL] === "string" ? (given[GOOGLE_CREDENTIAL] as string) : ""
if (!Object.keys(env).length && !google) throw new Error(`x-raea-agent-env names none of ${[...AGENT_KEYS, GOOGLE_CREDENTIAL].join(", ")}`)
const name = String(headers["x-raea-agent-home"] ?? "")
if (!/^[a-z0-9][a-z0-9_-]{0,62}$/.test(name)) throw new Error("x-raea-agent-home must be a short lowercase name")
for (const [k, dir] of Object.entries(AGENT_HOMES)) {
env[k] = path.join(home, ".agent-homes", name, dir)
mkdirSync(env[k], { recursive: true, mode: 0o700 })
}
linkSkills(env, home)
if (google) {
unpackCredential(google, env.GEMINI_HOME)
env.AGY_ACP_FORCE_FILE_STORAGE = "1"
}
return env
}
/** what a socket signed in as one of raea cloud's clients runs with: its agent works one turn at a time for a caller
* that ends the run when the turn ends, so Claude Code mustn't background a command and end its turn to wait for it
* (11-21: a render backgrounded, the turn ended, the project stopped with nothing to show), and a render through
* raea's MCP tools or in the shell gets half an hour */
const RUN_DEFAULTS: Record<string, string> = { CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1", BASH_DEFAULT_TIMEOUT_MS: "1800000", BASH_MAX_TIMEOUT_MS: "3600000", MCP_TOOL_TIMEOUT: "1800000" }
/** the container's environment less every model key: a socket with its own sign-in never falls back to the box's */
const withoutKeys = (env: NodeJS.ProcessEnv) => {
const out = { ...env }
for (const k of [...AGENT_KEYS, "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS"]) delete out[k]
return out
}
const raeaVersion = () => {
try {
version ??= execFileSync(RAEA, ["--version"], { encoding: "utf8", timeout: 20_000, env: childEnv() }).trim()
@@ -150,12 +245,16 @@ const server = createServer(async (req, res) => {
const gpu = process.env.RAEA_CLOUD_GPU_URL
return json(res, {
raea: raeaVersion(),
// what deploy/sprites/box.sh put here: the build's id, the commit, whether the tree was dirty (BUILD.json)
build: buildOf(),
agent: def,
agents: installed().map((a) => ({ id: a.id, version: a.version })),
workspace: WORK,
device: device(childEnv()),
offload: gpu ? { url: gpu, commands: (process.env.RAEA_CLOUD_GPU_COMMANDS ?? "render").split(/\s+/).filter(Boolean) } : null,
jobs: jobs.held(),
// agents running now: deploy/sprites/box.sh up waits for none before it restarts this server
running: running.size,
})
}
if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url)
@@ -181,6 +280,29 @@ const server = createServer(async (req, res) => {
const f = await jobs.follow(job[1], Number(url.searchParams.get("from") ?? 0))
return f ? json(res, f) : json(res, { error: "no job with that id" }, 404)
}
if (url.pathname === "/v1/claude-token" && req.method === "POST") return json(res, await startClaudeSignIn(childEnv()))
if (url.pathname === "/v1/claude-token/check" && req.method === "POST") {
const b = JSON.parse((await body(req)).toString("utf8") || "{}") as { token?: unknown }
return json(res, await checkClaude(childEnv(), String(b.token ?? "")))
}
if (url.pathname === "/v1/google-token" && req.method === "POST") {
const b = JSON.parse((await body(req)).toString("utf8") || "{}") as { screen?: unknown }
return json(res, await startGoogleSignIn(childEnv(), { screen: b.screen === true }))
}
if (url.pathname === "/v1/google-token/check" && req.method === "POST") {
const b = JSON.parse((await body(req)).toString("utf8") || "{}") as { credential?: unknown }
return json(res, await checkGoogle(childEnv(), String(b.credential ?? "")))
}
const gt = /^\/v1\/google-token\/([0-9a-f]{24})$/.exec(url.pathname)
if (gt && req.method === "POST") {
const b = JSON.parse((await body(req)).toString("utf8") || "{}") as { address?: unknown }
return json(res, await finishGoogleSignIn(gt[1], typeof b.address === "string" && b.address.trim() ? b.address : undefined))
}
const ct = /^\/v1\/claude-token\/([0-9a-f]{24})$/.exec(url.pathname)
if (ct && req.method === "POST") {
const b = JSON.parse((await body(req)).toString("utf8") || "{}") as { code?: unknown }
return json(res, await finishClaudeSignIn(ct[1], String(b.code ?? "")))
}
if (url.pathname === "/v1/login") {
const a = spawnFor(url.searchParams.get("agent") ?? undefined)
return json(res, req.method === "POST" ? await login(a, childEnv()) : loginState(a.id))
@@ -194,8 +316,23 @@ const server = createServer(async (req, res) => {
// the WebSocket upgrade checks the token before a socket opens
const wss = new WebSocketServer({ noServer: true })
const agentSockets = new Set<import("ws").WebSocket>()
server.on("upgrade", (req, socket, head) => {
const url = new URL(req.url ?? "/", "http://raea-cloud")
// a Google sign-in's own browser (google-screen.ts): its VNC stream, both ways, as binary frames
const gs = /^\/v1\/google-token\/([0-9a-f]{24})\/screen$/.exec(url.pathname)
if (gs) {
const port = authorized(req, url) ? screenPort(gs[1]) : undefined
if (port === undefined) return socket.end(authorized(req, url) ? "HTTP/1.1 404 Not Found\r\n\r\n" : "HTTP/1.1 401 Unauthorized\r\n\r\n")
return wss.handleUpgrade(req, socket, head, (ws) => {
const vnc = tcp(port, "127.0.0.1")
vnc.on("data", (d) => ws.readyState === ws.OPEN && ws.send(d))
ws.on("message", (m) => vnc.write(m as Buffer))
vnc.on("close", () => ws.close(1000, "the sign-in's screen closed"))
vnc.on("error", () => ws.close(1011, "the sign-in's screen failed"))
ws.on("close", () => vnc.destroy())
})
}
if (url.pathname !== "/v1/acp" || !authorized(req, url)) return socket.end("HTTP/1.1 401 Unauthorized\r\n\r\n")
let a
try {
@@ -204,8 +341,43 @@ server.on("upgrade", (req, socket, head) => {
return socket.end(`HTTP/1.1 400 Bad Request\r\ncontent-type: text/plain\r\n\r\n${(e as Error).message}`)
}
const agent = a
let own: Record<string, string> | null
try {
own = socketEnv(req.headers)
} catch (e) {
return socket.end(`HTTP/1.1 400 Bad Request\r\ncontent-type: text/plain\r\n\r\n${(e as Error).message}`)
}
const env = own ? { ...withoutKeys(childEnv()), ...agent.env, ...RUN_DEFAULTS, ...own } : { ...childEnv(), ...agent.env }
wss.handleUpgrade(req, socket, head, (ws) => {
const child = spawn(agent.command, agent.args, { cwd: WORK, env: { ...childEnv(), ...agent.env }, stdio: ["pipe", "pipe", "inherit"] })
// 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)
const child = spawn(agent.command, agent.args, { cwd: WORK, env, stdio: ["pipe", "pipe", "pipe"], detached: true })
const stopAll = () => {
if (!child.pid) return
try {
process.kill(-child.pid, "SIGTERM")
} catch {}
setTimeout(() => {
try {
process.kill(-child.pid!, "SIGKILL")
} catch {}
}, 5000).unref()
}
running.add(child)
agentSockets.add(ws)
// 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)
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat)))
child.on("exit", () => running.delete(child))
// 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)
child.stderr.setEncoding("utf8").on("data", (c: string) => {
process.stderr.write(c)
if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/stderr", params: { text: c.slice(0, 16_000) } }))
})
let buf = ""
// ACP messages are newline-delimited JSON: split on \n only
child.stdout.setEncoding("utf8").on("data", (c: string) => {
@@ -213,13 +385,20 @@ server.on("upgrade", (req, socket, head) => {
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) => child.stdin.write(m.toString() + "\n"))
ws.on("close", () => child.exitCode === null && child.kill("SIGTERM"))
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}`))
child.on("exit", (code) => (ws.close(1011, `${agent.id} exited ${code}`), stopAll()))
})
})
mkdirSync(WORK, { recursive: true })
// the box kept from running out of memory (memguard.ts): what it stops is said in the box's log and in every agent's
// trace (_raea/stderr), where a cut-off run's reason is read
if (existsSync("/proc/meminfo") && process.env.RAEA_CLOUD_MEMGUARD !== "0")
guard((line) => {
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" } }))
})
server.listen(PORT, () => {
const d = device(childEnv())
const gpu = process.env.RAEA_CLOUD_GPU_URL
+101 -1
View File
@@ -10,8 +10,10 @@
import { createHash } from "node:crypto"
import { spawnSync } from "node:child_process"
import { createReadStream, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { Readable } from "node:stream"
import type { Media } from "../src/index.ts"
const LFS = "application/vnd.git-lfs+json"
@@ -132,5 +134,103 @@ export async function outputs(root: string, lfs: Lfs, made: Media[]): Promise<{
return { send, done }
}
// what goes by hash when the project isn't in raea's LFS (farmInputs): media by type, and anything large, as the farm's
// farm_media.py MEDIA and LARGE judge it; a file under SMALL stays in the tar, where it costs less than a lookup
const MEDIA = new Set(
"mp4 mov m4v webm mkv avi mxf mp3 wav aiff aif flac m4a ogg opus caf png jpg jpeg heic heif webp gif tif tiff exr hdr psd blend glb gltf fbx obj usd usdz abc ply splat spz ktx2 ttf otf woff woff2 zip tar gz zst safetensors onnx bin npz npy pdf".split(" "),
)
const LARGE = 4 << 20
const SMALL = 256 << 10
/** the farm's cache of media (farm.py POST /v1/blobs/have, PUT /v1/blobs/OID), over its own token */
export interface FarmBlobs {
/** which of these it holds; null when this farm has no cache (an older one): the media goes in the tar */
have(objects: { oid: string; size: number }[]): Promise<Set<string> | null>
put(file: string, oid: string, size: number): Promise<void>
}
export function farmBlobs(url: string, token: string): FarmBlobs {
const auth = { authorization: `Bearer ${token}` }
return {
async have(objects) {
const r = await fetch(`${url}/v1/blobs/have`, { method: "POST", headers: { ...auth, "content-type": "application/json" }, body: JSON.stringify({ objects }) })
if (r.status === 404) return null
if (!r.ok) throw new Error(`the farm's media cache answered ${r.status}: ${(await r.text()).slice(0, 200)}`)
return new Set(((await r.json()) as { have: string[] }).have)
},
async put(file, oid, size) {
// streamed from the disk: a file is never held in memory (a project's interviews are gigabytes)
const body = Readable.toWeb(createReadStream(file)) as unknown as ReadableStream
const r = await fetch(`${url}/v1/blobs/${oid}?size=${size}`, { method: "PUT", headers: { ...auth, "content-type": "application/octet-stream", "content-length": String(size) }, body, duplex: "half" } as RequestInit)
if (!r.ok) throw new Error(`the farm didn't keep ${path.basename(file)}: ${r.status} ${(await r.text()).slice(0, 200)}`)
},
}
}
/** each file's hash, kept by the file itself (its device and inode) with its size and time, so a project's footage is
* hashed once, not on every render, nor again in a new thread's folder that links the same files (11-25: StreetTalk's
* restart hard-linked its 1.9 GB of interviews into a new folder, and they were hashed again) */
function hashes(file: string) {
let known: Record<string, { size: number; mtime: number; oid: string }> = {}
try {
known = JSON.parse(readFileSync(file, "utf8"))
} catch {}
let changed = false
return {
async of(p: string, id: string, size: number, mtime: number): Promise<string> {
const k = known[id]
if (k && k.size === size && k.mtime === mtime) return k.oid
const oid = await sha256(p)
known[id] = { size, mtime, oid }
changed = true
return oid
},
save() {
if (!changed) return
mkdirSync(path.dirname(file), { recursive: true })
const tmp = `${file}.${process.pid}`
writeFileSync(tmp, JSON.stringify(known))
renameSync(tmp, file)
},
}
}
/** A project's media when it isn't in raea's LFS (11-25): each media or large file by its hash, sent once into the
* farm's cache and named in the job's manifest with no href, so a render's tar holds the code and not the footage
* (StreetTalk's 1.9 GB of interviews went in every render's tar, even one frame's). null when the farm has no cache.
* `skip`: the tar's excludes. Links are left to the tar, as before. */
export async function farmInputs(root: string, farm: FarmBlobs, skip: (p: string) => boolean = () => false, said: (s: string) => void = () => {}, store = path.join(os.homedir(), ".cache", "raea-offload", "hashes.json")): Promise<{ media: Media[]; sent: number } | null> {
const found: { path: string; abs: string; id: string; size: number; mtime: number }[] = []
const walk = (dir: string) => {
for (const e of readdirSync(dir, { withFileTypes: true })) {
const abs = path.join(dir, e.name)
const rel = path.relative(root, abs).split(path.sep).join("/")
if (skip(rel)) continue
if (e.isDirectory()) walk(abs)
else if (e.isFile()) {
const st = statSync(abs)
const ext = e.name.includes(".") ? e.name.split(".").pop()!.toLowerCase() : ""
if (st.size >= LARGE || (st.size >= SMALL && MEDIA.has(ext))) found.push({ path: rel, abs, id: `${st.dev}:${st.ino}`, size: st.size, mtime: st.mtimeMs })
}
}
}
walk(root)
if (!found.length) return { media: [], sent: 0 }
const h = hashes(store)
const media: (Media & { abs: string })[] = []
for (const f of found) media.push({ path: f.path, oid: await h.of(f.abs, f.id, f.size, f.mtime), size: f.size, abs: f.abs })
h.save()
const have = await farm.have(media.map(({ oid, size }) => ({ oid, size })))
if (!have) return null
let sent = 0
const todo = media.filter((m, i) => !have.has(m.oid) && media.findIndex((x) => x.oid === m.oid) === i)
if (todo.length) said(`sending ${todo.length} media files (${(todo.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) to the farm's cache, once`)
for (const m of todo) {
await farm.put(m.abs, m.oid, m.size)
sent += m.size
}
return { media: media.map(({ abs: _, ...m }) => m), sent }
}
/** tar's exclude-from lines for paths that go by hash: each matched as written (glob characters escaped) */
export const excludes = (media: Media[]) => media.map((m) => "./" + m.path.replace(/[\\*?[\]]/g, (c) => "\\" + c)).join("\n") + "\n"
+89
View File
@@ -0,0 +1,89 @@
// The box's memory, kept from running out (11-25): StreetTalk's agent, its renders failing on the farm, found raea's
// own binary and rendered a cut of 4K interviews on the box's CPU; the 8 GB box ran out and stopped answering, every
// agent's socket with it. A box is a VM whose processes share one cgroup that can't be split, so there's no kernel
// cap to set: like earlyoom, this looks at the box's free memory every second and, when it runs low, kills the
// largest thing the box's agents started (a render, an ffmpeg), never the server and never an agent itself (they're
// a few hundred MB; only a process over MIN_RSS is a candidate). The command it was part of fails, said in its
// output by the shell ("Killed"), and the agent carries on.
import { readdirSync, readFileSync } from "node:fs"
/** below this much available memory (the larger of the two) the guard acts */
export const FLOOR_MB = 700
export const FLOOR_SHARE = 0.08
/** a process smaller than this is never killed: the agents, the server, a shell */
export const MIN_RSS_MB = 1024
export interface Proc {
pid: number
ppid: number
rssMb: number
name: string
}
/** every process on the box (Linux /proc) */
export function procs(root = "/proc"): Proc[] {
const out: Proc[] = []
for (const d of readdirSync(root)) {
if (!/^\d+$/.test(d)) continue
try {
const stat = readFileSync(`${root}/${d}/stat`, "utf8")
// the name is in parentheses and may hold spaces: the fields after its last ")" are fixed
const close = stat.lastIndexOf(")")
const name = stat.slice(stat.indexOf("(") + 1, close)
const f = stat.slice(close + 2).split(" ")
const status = readFileSync(`${root}/${d}/status`, "utf8")
const rss = /VmRSS:\s+(\d+) kB/.exec(status)
out.push({ pid: Number(d), ppid: Number(f[1]), rssMb: rss ? Number(rss[1]) / 1024 : 0, name })
} catch {} // gone since the listing
}
return out
}
/** the box's memory: total and available, in MB */
export function memory(file = "/proc/meminfo"): { totalMb: number; availableMb: number } {
const m = readFileSync(file, "utf8")
const kb = (k: string) => Number(new RegExp(`${k}:\\s+(\\d+) kB`).exec(m)?.[1] ?? 0)
return { totalMb: kb("MemTotal") / 1024, availableMb: kb("MemAvailable") / 1024 }
}
/** the process to kill when memory is low: the largest of `root`'s descendants over MIN_RSS_MB, or none */
export function victim(all: Proc[], root: number, keep: Set<number> = new Set()): Proc | null {
const kids = new Map<number, Proc[]>()
for (const p of all) kids.set(p.ppid, [...(kids.get(p.ppid) ?? []), p])
const under: Proc[] = []
const walk = (pid: number) => {
for (const k of kids.get(pid) ?? []) {
under.push(k)
walk(k.pid)
}
}
walk(root)
const big = under.filter((p) => p.rssMb >= MIN_RSS_MB && !keep.has(p.pid)).sort((a, b) => b.rssMb - a.rssMb)
return big[0] ?? null
}
export interface Guard {
stop(): void
}
/** watch the box's memory and kill the largest runaway under `root` (this server) when it runs low; `said` hears why */
export function guard(said: (line: string) => void, o: { root?: number; everyMs?: number; keep?: () => Set<number>; mem?: typeof memory; list?: typeof procs; kill?: (pid: number) => void } = {}): Guard {
const root = o.root ?? process.pid
const mem = o.mem ?? memory
const list = o.list ?? procs
const kill = o.kill ?? ((pid: number) => process.kill(pid, "SIGKILL"))
const t = setInterval(() => {
try {
const m = mem()
if (m.availableMb >= Math.max(FLOOR_MB, m.totalMb * FLOOR_SHARE)) return
const v = victim(list(), root, o.keep?.())
if (!v) return
kill(v.pid)
said(`raea cloud: the box was running out of memory (${Math.round(m.availableMb)} MB of ${Math.round(m.totalMb)} MB left), so ${v.name} (pid ${v.pid}, ${(v.rssMb / 1024).toFixed(1)} GB) was stopped. Render on the GPU with raea render, not on this box`)
} catch (e) {
said(`raea cloud: the memory guard: ${(e as Error).message}`)
}
}, o.everyMs ?? 1000)
t.unref()
return { stop: () => clearInterval(t) }
}
+56 -7
View File
@@ -7,7 +7,7 @@
// 2. `raea render` runs there with the same arguments, its paths made relative to that folder, and prints here as
// it comes;
// 3. the files it made or changed land back here: an output path outside the folder (-o /tmp/x.mp4) is written
// there under .raea-cloud-out and moved to its place after.
// there as .raea-cloud-out-N-NAME at its top and moved to its place after.
// In a raea repo, with this box signed in, the project's media goes by hash instead (media.ts, CR23): the farm fetches
// it from R2, and the media the render makes goes to R2 from the farm, here only as pointer files.
//
@@ -21,7 +21,7 @@ import os from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { RaeaCloud } from "../src/index.ts"
import { excluded, excludes as mediaExcludes, inputs, lfsOf, outputs } from "./media.ts"
import { excluded, excludes as mediaExcludes, farmBlobs, farmInputs, inputs, lfsOf, outputs } from "./media.ts"
const REAL = process.env.RAEA_REAL ?? "/opt/raea/bin/raea"
// flags whose value is a path raea writes; the rest of a render's path arguments are read
@@ -75,7 +75,9 @@ export function plan(args: string[], cwd: string, root?: string): Plan | string
const abs = path.resolve(cwd, a)
if (inside(r, abs)) out.push(path.relative(r, abs) || ".")
else if (WRITES.has(flag)) {
const rel = path.join(".raea-cloud-out", `${moves.length}-${path.basename(abs)}`)
// a file at the top of the project, not in a folder: the folder isn't sent, and a still's writer (unlike a video's
// encoder) doesn't make one, so a PNG made outside the project was never written (11-25, StreetTalk's storyboards)
const rel = `.raea-cloud-out-${moves.length}-${path.basename(abs)}`
moves.push({ from: rel, to: abs })
out.push(rel)
} else return `${a} is outside the project sent to the GPU (${r})`
@@ -85,6 +87,14 @@ export function plan(args: string[], cwd: string, root?: string): Plan | string
async function main() {
const args = process.argv.slice(2)
// a video's render manifest (every text's size and place, frame by frame) beside it, for the frames check's text
// sizes (frames.ts), unless the render already asks for one
{
const oi = args.indexOf("-o")
const o = oi >= 0 ? (args[oi + 1] ?? "") : ""
if (args[0] === "render" && /\.(mp4|mov|m4v|webm)$/i.test(o) && !args.includes("--manifest") && process.env.RAEA_CLOUD_FRAMES !== "0")
args.push("--manifest", `${o.slice(0, o.length - path.extname(o).length)}.render.json`)
}
const url = process.env.RAEA_CLOUD_GPU_URL
const token = process.env.RAEA_CLOUD_GPU_TOKEN ?? ""
if (!url) local(args)
@@ -93,13 +103,23 @@ async function main() {
const tmp = mkdtempSync(path.join(os.tmpdir(), "raea-offload-"))
try {
const excludes = (process.env.RAEA_CLOUD_GPU_EXCLUDE ?? "./.git ./out/* ./.raea-cloud-out").split(/\s+/).filter(Boolean)
// kits/ (raea-game-kit) is a link into the box's shared cache, hundreds of MB, that the farm can't follow: a
// composition uses copies of the kit files it needs in its own folder (11-21: the dangling link hung farm jobs)
const excludes = (process.env.RAEA_CLOUD_GPU_EXCLUDE ?? "./.git ./out/* ./.raea-cloud-out ./.raea-cloud-out-* ./kits").split(/\s+/).filter(Boolean)
// zstd with GNU tar (the image's); gzip with another tar (a Mac's), whose zstd needs a program of its own
const gnu = spawnSync("tar", ["--version"], { encoding: "utf8" }).stdout?.includes("GNU")
const sent = path.join(tmp, "in.tar")
// the media that goes by hash: out of the tar, named in its manifest
const lfs = lfsOf(p.root)
const byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs, excluded(excludes))
let byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs, excluded(excludes))
// not in raea's LFS: the media goes into the farm's own cache by hash, once, instead of in every render's tar
// (RAEA_CLOUD_GPU_BLOBS=0 puts it back in the tar). A farm without the cache, or one that can't be reached here,
// leaves it in the tar, and the health check below says why the farm can't be reached
let viaFarm: { media: typeof byHash; sent: number } | null = null
if (typeof lfs === "string" && process.env.RAEA_CLOUD_GPU_BLOBS !== "0") {
viaFarm = await farmInputs(p.root, farmBlobs(url, token), excluded(excludes), say).catch((e) => (say(`the farm's media cache: ${(e as Error).message}; the media goes in the tar`), null))
if (viaFarm) byHash = viaFarm.media
}
const extra: string[] = []
if (byHash.length) {
writeFileSync(path.join(tmp, "media-excludes"), mediaExcludes(byHash))
@@ -120,7 +140,8 @@ async function main() {
throw new Error(`the GPU worker at ${url} didn't answer: ${(e as Error).message} (RAEA_CLOUD_GPU_FALLBACK=cpu renders here instead)`)
}
say(`rendering on ${new URL(url).host}, ${h.device.renders === "gpu" ? `GPU ${h.device.name}` : `its CPU (${h.device.name})`}: ${p.root} (${(folder.length / 1e6).toFixed(1)} MB) sent`)
if (byHash.length) say(`${byHash.length} media files (${(byHash.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) go by hash: the farm fetches them from R2`)
if (viaFarm && byHash.length) say(`${byHash.length} media files (${(byHash.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) go by hash from the farm's cache${viaFarm.sent ? `, ${(viaFarm.sent / 1e6).toFixed(1)} MB of it sent now` : ""}`)
else if (byHash.length) say(`${byHash.length} media files (${(byHash.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) go by hash: the farm fetches them from R2`)
else if (typeof lfs === "string" && existsSync(path.join(p.root, ".lfsconfig"))) say(`media goes in the tar: ${lfs}`)
// a render farm's choices (deploy/modal/farm.py): RAEA_CLOUD_GPUS, RAEA_CLOUD_GPU_KIND, RAEA_CLOUD_MAX_USD
const n = (v?: string) => (v ? Number(v) : undefined)
@@ -131,7 +152,9 @@ async function main() {
finish = o.done
return o.send
}
const { exit, files } = await cloud.job(p.args, folder, { as: gnu ? "zst" : "gz", farm, media, onOutput: (t, s) => (s === "out" ? process.stdout : process.stderr).write(t) })
// what the job said, kept to spot a file it wanted that stayed here (out/ isn't sent: it's renders)
let said = ""
const { exit, files } = await cloud.job(p.args, folder, { as: gnu ? "zst" : "gz", farm, media, onOutput: (t, s) => ((said = (said + t).slice(-20000)), (s === "out" ? process.stdout : process.stderr).write(t)) })
const back = path.join(tmp, "out.tar")
writeFileSync(back, files)
@@ -149,12 +172,38 @@ async function main() {
}
}
rmSync(path.join(p.root, ".raea-cloud-out"), { recursive: true, force: true })
for (const m of p.moves) rmSync(path.join(p.root, m.from), { force: true })
if (finish) {
const bytes = await finish()
say(`its media (${(bytes / 1e6).toFixed(1)} MB) went from the farm to R2; here it's pointers (git lfs pull PATH brings one here)`)
}
say(`done on the GPU worker in ${((performance.now() - t0) / 1000).toFixed(1)} s, exit ${exit}`)
// 11-25: an agent kept its words in out/words/ and four renders failed on "No such file" with no reason given
const missed = exit ? /(?:^|[\s/])(out\/[^\s:]+): No such file/m.exec(said) : null
if (missed && excludes.includes("./out/*")) say(`${missed[1]} wasn't sent: out/ stays here, as it holds renders. Keep what a composition reads (words, data, stills it uses) in media/ or beside the composition`)
process.exitCode = exit
// a video's words, heard as soon as it's back (words.ts): the cut is held to OUT.lines.txt when it has one, so a
// word clipped by a cut or faded under a crossfade is caught before anyone reviews it (11-25, Shane)
// the -o asked for (an output outside the project came back there by its move)
const oi = args.indexOf("-o")
const made = oi >= 0 ? path.resolve(process.cwd(), args[oi + 1] ?? "") : ""
if (!exit && /\.(mp4|mov|m4v|webm)$/i.test(made) && existsSync(made) && process.env.RAEA_CLOUD_WORDS !== "0") {
const { afterRender } = await import("./words.ts")
const code = await afterRender(made, say)
if (code) process.exitCode = code
}
// what its pictures get wrong (frames.ts): faces cut by the frame or a split screen's seam, text too small to read
// (11-25, Shane: "it cuts out faces all the time", "it makes text too small")
if (!exit && /\.(mp4|mov|m4v|webm)$/i.test(made) && existsSync(made) && process.env.RAEA_CLOUD_FRAMES !== "0") {
const { main: frames } = await import("./frames.ts")
say(`the frames check: ${path.basename(made)}'s faces and text sizes`)
const mi = args.indexOf("--manifest")
const code = await frames(["check", made, ...(mi >= 0 ? ["--manifest", path.resolve(process.cwd(), args[mi + 1] ?? "")] : [])]).catch((e) => (say(`the frames check couldn't run: ${(e as Error).message}`), 0))
if (code) {
say(`${path.basename(made)} has a face cut or text too small: fix every ERROR above (reframe on the person, make the text bigger), then render again. A face at the edge that's meant goes in ${path.basename(made, path.extname(made))}.despite.txt with why`)
process.exitCode = code
}
}
} finally {
rmSync(tmp, { recursive: true, force: true })
}
+294
View File
@@ -0,0 +1,294 @@
// `raea words` on a raea cloud box: what a take or an export says, word by word, and whether an export says what its
// cut meant it to. raea's own transcriber is parakeet-mlx (Mac only), so a box had none: agents guessed `raea
// transcribe`, cut on guessed frames and shipped words clipped by a cut or faded under a crossfade (11-25, Shane: "cuts
// where it applies crossfades on audio that make it so you can't hear it, and cuts where it will cut early over
// someone speaking ... before exporting the audio requires a transcription pass to be sure it matches").
//
// raea words FILE [-o OUT.words.json] [--language en] [--fades]
// FILE's sound heard by Whisper large-v3 (the farm's POST /v1/words, the model raea cloud's library index uses)
// into FILE's words.json beside it ([{text, start_ms, end_ms}], what `raea cut`, captions and --words read)
// raea words check VIDEO --expect LINES.txt [-o REPORT.json] [--language en]
// VIDEO heard, then held to the lines its cut should say (plain text, in order): a word missing or cut short is
// an error; a word heard differently, speech fading under a crossfade, or a word running into the first or last
// frame is a warning. Exit 1 on any error. The VIDEO's words.json is kept for its captions.
//
// The sound goes as 16 kHz mono MP3 in 10-minute pieces (`raea media ffmpeg`), to RAEA_CLOUD_GPU_URL with its token.
import { spawnSync } from "node:child_process"
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
const REAL = process.env.RAEA_REAL ?? "/opt/raea/bin/raea"
const PIECE_S = 600
export type Word = { text: string; start: number; end: number }
export type Finding = { level: "error" | "warn" | "note"; kind: "missing" | "clipped" | "changed" | "faded" | "edge" | "extra"; at: number | null; says: string }
/** a word as it's compared: lower case, letters and digits only ("$1,000." and "1000" are the same word) */
export const norm = (w: string) => w.toLowerCase().normalize("NFKD").replace(/[^\p{L}\p{N}]+/gu, "")
/** the lines' words and the heard words aligned (longest common subsequence), as pairs: [expected index | -1, heard index | -1] */
export function align(want: string[], heard: string[]): [number, number][] {
const n = want.length
const m = heard.length
const L = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1))
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = want[i] === heard[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1])
const out: [number, number][] = []
let i = 0
let j = 0
while (i < n && j < m) {
if (want[i] === heard[j]) out.push([i++, j++])
// a word for a word costs the alignment nothing: kept side by side, so a word heard cut short reads as one
else if (L[i + 1][j + 1] === L[i][j]) out.push([i++, -1], [-1, j++])
else if (L[i + 1][j] >= L[i][j + 1]) out.push([i++, -1])
else out.push([-1, j++])
}
while (i < n) out.push([i++, -1])
while (j < m) out.push([-1, j++])
return out
}
/** one heard word is the other cut short: "test" for "tests", "abl" for "able" (three letters at least) */
const cutShort = (want: string, got: string) => got.length >= 2 && got.length < want.length && (want.startsWith(got) || want.endsWith(got))
/** the expected lines against what was heard */
export function compare(lines: string, heard: Word[]): Finding[] {
const wantRaw = lines.split(/\s+/).filter((w) => norm(w))
const want = wantRaw.map(norm)
const got = heard.map((w) => norm(w.text))
const pairs = align(want, got)
const out: Finding[] = []
// a missing word next to an extra one is one word heard differently (or cut short): pair them up
for (let k = 0; k < pairs.length; k++) {
const [i, j] = pairs[k]
if (i >= 0 && j >= 0) continue
const next = pairs[k + 1]
if (i >= 0 && next && next[0] < 0 && next[1] >= 0) {
const h = heard[next[1]]
out.push(cutShort(want[i], got[next[1]]) ? { level: "error", kind: "clipped", at: h.start, says: `"${wantRaw[i]}" is cut short: heard "${h.text}" at ${h.start.toFixed(2)} s. Move the cut into the gap after the word` } : { level: "warn", kind: "changed", at: h.start, says: `"${wantRaw[i]}" heard as "${h.text}" at ${h.start.toFixed(2)} s: listen there; if the word is clipped or muddied, fix the cut` })
k++
continue
}
if (i < 0 && next && next[0] >= 0 && next[1] < 0) {
const h = heard[j]
out.push(cutShort(want[next[0]], got[j]) ? { level: "error", kind: "clipped", at: h.start, says: `"${wantRaw[next[0]]}" is cut short: heard "${h.text}" at ${h.start.toFixed(2)} s. Move the cut into the gap after the word` } : { level: "warn", kind: "changed", at: h.start, says: `"${wantRaw[next[0]]}" heard as "${h.text}" at ${h.start.toFixed(2)} s: listen there; if the word is clipped or muddied, fix the cut` })
k++
continue
}
if (i >= 0) {
// where it should have been: after the last word heard before it
const before = pairs.slice(0, k).reverse().find((p) => p[1] >= 0)
const at = before ? heard[before[1]].end : 0
out.push({ level: "error", kind: "missing", at, says: `"${wantRaw[i]}" isn't heard (expected near ${at.toFixed(2)} s): a cut, a fade or the mix took it` })
} else out.push({ level: "note", kind: "extra", at: heard[j].start, says: `"${heard[j].text}" at ${heard[j].start.toFixed(2)} s isn't in the lines` })
}
return out
}
/** the level every 10 ms, in dB, of 16 kHz mono 16-bit samples */
export function levels(pcm: Int16Array): number[] {
const hop = 160
const out: number[] = []
for (let s = 0; s + hop <= pcm.length; s += hop) {
let e = 0
for (let k = s; k < s + hop; k++) e += (pcm[k] / 32768) ** 2
out.push(10 * Math.log10(e / hop + 1e-10))
}
return out
}
/** speech that fades under a crossfade: inside the heard words, a run of 120 ms or more at least 14 dB under the speech's
* own median, that comes back up within the same word or the next (a fade out and in across a cut). And a word running
* into the first or last 40 ms of the piece, which is speech cut by the piece's own edge */
export function fades(db: number[], heard: Word[], seconds: number): Finding[] {
const inside: number[] = []
for (const w of heard) for (let f = Math.floor(w.start * 100); f < Math.min(db.length, Math.ceil(w.end * 100)); f++) inside.push(db[f])
if (inside.length < 20) return []
const median = [...inside].sort((a, b) => a - b)[Math.floor(inside.length / 2)]
const out: Finding[] = []
const quiet = (f: number) => db[f] < median - 14
let lastAt = -9
for (let n = 0; n < heard.length; n++) {
const w = heard[n]
const a = Math.floor(w.start * 100)
const b = Math.min(db.length, Math.ceil(w.end * 100))
// a dip that comes back up inside the word: a fade out and in across a join. One that runs on to the word's end is
// the word trailing off (Whisper's spans take in the quiet after a word), not a fade
let run = 0
let deepest = 0
for (let f = a; f < b; f++) {
if (quiet(f)) {
run++
deepest = Math.max(deepest, median - db[f])
continue
}
if (run >= 12 && db[f] > median - 8 && f / 100 - lastAt > 1) {
lastAt = f / 100
out.push({ level: "warn", kind: "faded", at: (f - run) / 100, says: `"${w.text}" at ${w.start.toFixed(2)} s dips ${deepest.toFixed(0)} dB under the speech for ${run * 10} ms and comes back: a crossfade or fade over speech? Dialogue joins are hard cuts in the gap between words, with fades of 20 ms at most` })
}
run = 0
deepest = 0
}
}
const first = heard[0]
const last = heard[heard.length - 1]
// Whisper puts a first word at 0 whether or not it's cut: only a sound already at speech level on the first (or last)
// 30 ms is speech the edge cut into
const loud = (fs: number[]) => fs.length > 0 && fs.every((f) => db[f] !== undefined && db[f] > median - 8)
const n0 = db.length
if (first && first.start < 0.04 && loud([0, 1, 2])) out.push({ level: "warn", kind: "edge", at: 0, says: `the first word "${first.text}" starts on the first frame: is its start cut off?` })
if (last && seconds - last.end < 0.04 && loud([n0 - 3, n0 - 2, n0 - 1])) out.push({ level: "warn", kind: "edge", at: last.end, says: `the last word "${last.text}" runs to the last frame: is its end cut off?` })
return out
}
function ffmpeg(args: string[]) {
const r = spawnSync(REAL, ["media", "ffmpeg", ...args], { encoding: "utf8" })
if (r.status !== 0) {
const r2 = spawnSync("ffmpeg", args, { encoding: "utf8" })
if (r2.status !== 0) throw new Error(`ffmpeg ${args.join(" ")}: ${(r.stderr || r2.stderr || "").slice(-400)}`)
}
}
function seconds(file: string): number {
const r = spawnSync(REAL, ["media", "ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file], { encoding: "utf8" })
const s = Number.parseFloat(r.stdout)
if (Number.isFinite(s)) return s
const r2 = spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file], { encoding: "utf8" })
const s2 = Number.parseFloat(r2.stdout)
if (!Number.isFinite(s2)) throw new Error(`${file}: no length (is it a video or sound file?)`)
return s2
}
/** what FILE says, by the farm's Whisper */
export async function hear(file: string, language?: string, f: typeof fetch = fetch): Promise<Word[]> {
const url = process.env.RAEA_CLOUD_GPU_URL
const token = process.env.RAEA_CLOUD_GPU_TOKEN ?? ""
if (!url) throw new Error("raea words needs the farm (RAEA_CLOUD_GPU_URL), which hears it with Whisper; this box has none set")
const len = seconds(file)
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-words-"))
try {
const out: Word[] = []
for (let at = 0; at < len; at += PIECE_S) {
const mp3 = path.join(dir, `p${at}.mp3`)
ffmpeg(["-v", "error", "-y", "-ss", String(at), "-t", String(PIECE_S), "-i", file, "-vn", "-ac", "1", "-ar", "16000", "-b:a", "32k", mp3])
if (!existsSync(mp3)) throw new Error(`${file} has no sound to hear`)
let r: Response | undefined
let why = ""
for (let k = 0; k < 4; k++) {
r = await f(`${url.replace(/\/$/, "")}/v1/words${language ? `?language=${encodeURIComponent(language)}` : ""}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "audio/mpeg" }, body: readFileSync(mp3), signal: AbortSignal.timeout(330_000) })
if (r.ok) break
why = `${r.status} ${(await r.text()).slice(0, 300)}`
if (r.status < 500) break
await new Promise((ok) => setTimeout(ok, 1000 * 2 ** k))
}
if (!r?.ok) throw new Error(`the farm couldn't hear ${path.basename(file)}: ${why}`)
const b = (await r.json()) as { words: Word[] }
out.push(...split(b.words).map((w) => ({ text: w.text, start: at + w.start, end: at + w.end })))
}
return out
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
/** Whisper sometimes hands back two words as one ("for $60"): one word each, sharing its time by their lengths */
export function split(ws: Word[]): Word[] {
return ws.flatMap((w) => {
const parts = w.text.split(/\s+/).filter(Boolean)
if (parts.length < 2) return [w]
const total = parts.reduce((n, p) => n + p.length, 0)
let t = w.start
return parts.map((p) => {
const d = ((w.end - w.start) * p.length) / total
const x = { text: p, start: t, end: t + d }
t += d
return x
})
})
}
const wordsPath = (file: string) => `${file.slice(0, file.length - path.extname(file).length)}.words.json`
const asRaea = (ws: Word[]) => ws.map((w) => ({ text: w.text, start_ms: Math.round(w.start * 1000), end_ms: Math.round(w.end * 1000) }))
function flag(args: string[], name: string): string | undefined {
const i = args.indexOf(name)
return i >= 0 ? args[i + 1] : undefined
}
export async function main(args: string[]): Promise<number> {
const language = flag(args, "--language")
if (args[0] === "check") {
const video = args[1]
const expect = flag(args, "--expect")
if (!video || !expect || !existsSync(video) || !existsSync(expect)) {
console.error("usage: raea words check VIDEO --expect LINES.txt [-o REPORT.json] [--language en] (LINES.txt: the words the cut should say, in order)")
return 2
}
const heard = await hear(video, language)
writeFileSync(wordsPath(video), `${JSON.stringify(asRaea(heard))}\n`)
const findings = [...compare(readFileSync(expect, "utf8"), heard), ...soundFindings(video, heard)].sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
const errors = findings.filter((x) => x.level === "error").length
const warns = findings.filter((x) => x.level === "warn").length
const report = { object: "words.check", video, expect, passed: errors === 0, errors, warnings: warns, heard: heard.map((w) => w.text).join(" "), findings }
const o = flag(args, "-o") ?? `${video.slice(0, video.length - path.extname(video).length)}.words-check.json`
writeFileSync(o, `${JSON.stringify(report, null, 2)}\n`)
for (const x of findings.filter((x) => x.level !== "note")) console.log(`${x.level === "error" ? "ERROR" : "WARN "} ${x.at === null ? "" : `${x.at.toFixed(2)} s `}${x.says}`)
const extra = findings.filter((x) => x.level === "note").length
console.log(`${errors ? "FAILED" : "PASSED"} ${path.basename(video)}: ${heard.length} words heard, ${errors} errors, ${warns} warnings${extra ? `, ${extra} words not in the lines` : ""}; ${o}`)
return errors ? 1 : 0
}
const file = args.find((a, i) => !a.startsWith("-") && args[i - 1] !== "-o" && args[i - 1] !== "--language")
if (!file || !existsSync(file)) {
console.error("usage: raea words FILE [-o OUT.words.json] [--language en] | raea words check VIDEO --expect LINES.txt [-o REPORT.json]")
return 2
}
const heard = await hear(file, language)
const o = flag(args, "-o") ?? wordsPath(file)
writeFileSync(o, `${JSON.stringify(asRaea(heard))}\n`)
console.log(`${o}: ${heard.length} words, ${heard.length ? heard[heard.length - 1].end.toFixed(1) : 0} s`)
console.log(heard.map((w) => w.text).join(" "))
if (args.includes("--fades")) for (const x of soundFindings(file, heard)) console.log(`WARN ${x.at === null ? "" : `${x.at.toFixed(2)} s `}${x.says}`)
return 0
}
/** fades and edge words in FILE's sound against what was heard */
function soundFindings(file: string, heard: Word[]): Finding[] {
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-words-"))
try {
const raw = path.join(dir, "a.raw")
ffmpeg(["-v", "error", "-y", "-i", file, "-vn", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", "-f", "s16le", raw])
const b = readFileSync(raw)
return fades(levels(new Int16Array(b.buffer, b.byteOffset, Math.floor(b.length / 2))), heard, seconds(file))
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
/** after a video render (offload.ts): its words heard and kept beside it, held to OUT.lines.txt when there is one. The
* exit code is the check's when it ran (1 on an error), else 0; a farm that can't hear it never fails the render */
export async function afterRender(out: string, say: (s: string) => void): Promise<number> {
const lines = `${out.slice(0, out.length - path.extname(out).length)}.lines.txt`
try {
if (existsSync(lines)) {
say(`the words check: ${path.basename(out)} held to ${path.basename(lines)}`)
const code = await main(["check", out, "--expect", lines])
if (code) say(`${path.basename(out)} doesn't say its lines: fix every ERROR above (move the cut into the gap between words, take the fade off the speech) and render again before any review`)
return code
}
say(`the words heard in ${path.basename(out)} (no ${path.basename(lines)} beside it to hold them to: write the lines this cut should say there, and the next render checks them)`)
await main([out, "--fades"])
} catch (e) {
say(`the words pass couldn't run: ${(e as Error).message}`)
}
return 0
}
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
// `raea transcribe` is the name agents reach for: the same thing
const a = process.argv.slice(2)
main(a[0] === "words" || a[0] === "transcribe" ? a.slice(1) : a).then(
(c) => process.exit(c),
(e) => (console.error(`raea words: ${(e as Error).message}`), process.exit(1)),
)
}
+11 -3
View File
@@ -5,7 +5,7 @@
// await cloud.health() // {raea, agent, agents, workspace}
// await cloud.write("card/edit.tsx", source) // into the workspace
// await cloud.run(["render", "edit.tsx", "-o", "card.mp4"], { cwd: "card" })
// const s = await cloud.session() // the default agent, over ACP
// const s = await cloud.session() // the agent RAEA_AGENT names, over ACP
// await s.prompt("Make card/edit.tsx a 3 s title card that says hello", (u) => console.log(u.sessionUpdate))
// const mp4 = await cloud.read("card/card.mp4")
// s.close()
@@ -164,7 +164,15 @@ export class RaeaCloud {
/** A finished job's files: the ones its run made or changed, as a tar (zstd unless `as` says gz or tar). The server
* drops the job after. */
async jobFiles(id: string, as: "zst" | "gz" | "tar" = "zst"): Promise<Uint8Array> {
return new Uint8Array(await (await this.fetch(`/v1/jobs/${id}/out?as=${as}`)).arrayBuffer())
// a farm whose volume is busy answers 503 and keeps the job (11-25: a 500 there lost a finished render): ask again
for (let i = 0; ; i++) {
try {
return new Uint8Array(await (await this.fetch(`/v1/jobs/${id}/out?as=${as}`)).arrayBuffer())
} catch (e) {
if (i >= 4 || !/: 503 /.test((e as Error).message)) throw e
await new Promise((r) => setTimeout(r, 1000 * 2 ** i))
}
}
}
/** A finished job's media outputs (a job started with farm.media), held on the farm until sendMedia. */
@@ -220,7 +228,7 @@ export class RaeaCloud {
return this.fetch(`/v1/login${agent ? `?agent=${encodeURIComponent(agent)}` : ""}`).then((r) => r.json())
}
/** An ACP session with an agent in the workspace (the default agent unless one is named). */
/** An ACP session with an agent in the workspace (the one named, else the one the box's RAEA_AGENT names; with neither, the box refuses). */
async session(o: { agent?: string; cwd?: string; onPermission?: (p: Permission) => string | Promise<string> } = {}): Promise<Session> {
const work = (this.ws ??= this.health().then((h) => h.workspace))
const q = new URLSearchParams({ token: this.token, ...(o.agent ? { agent: o.agent } : {}) })
+98
View File
@@ -0,0 +1,98 @@
// A box's media by hash into the farm's own cache (server/media.ts farmInputs, 11-25), against a local stand-in for
// the farm's POST /v1/blobs/have and PUT /v1/blobs/OID: node test/farm-blobs.ts from sdk/cloud.
// Checked: a project's footage and large files go by hash and its code and small files stay in the tar; the first
// render sends each once (streamed, checked against its hash), the next sends nothing and hashes nothing again; a
// file changed since is sent again; out/ and links are left alone; a farm without the cache answers null.
import { createHash } from "node:crypto"
import { linkSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs"
import { createServer } from "node:http"
import type { AddressInfo } from "node:net"
import { tmpdir } from "node:os"
import path from "node:path"
import { excluded, farmBlobs, farmInputs } from "../server/media.ts"
const ok = (m: string) => console.log(`ok ${m}`)
const assert = (c: unknown, m: string) => {
if (!c) throw new Error(`not ok: ${m}`)
}
const held = new Map<string, number>()
let puts = 0
let cache = true
const farm = createServer((req, res) => {
const u = new URL(req.url!, "http://x")
if (req.headers.authorization !== "Bearer farm-token") return void res.writeHead(401).end()
if (!cache) return void res.writeHead(404).end()
if (req.method === "POST" && u.pathname === "/v1/blobs/have") {
let b = ""
req.on("data", (c) => (b += c)).on("end", () => {
const objects = (JSON.parse(b).objects ?? []) as { oid: string; size: number }[]
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ have: objects.filter((o) => held.get(o.oid) === o.size).map((o) => o.oid) }))
})
return
}
const m = /^\/v1\/blobs\/([0-9a-f]{64})$/.exec(u.pathname)
if (req.method === "PUT" && m) {
const h = createHash("sha256")
let n = 0
req.on("data", (c: Buffer) => (h.update(c), (n += c.length))).on("end", () => {
if (h.digest("hex") !== m[1] || n !== Number(u.searchParams.get("size"))) return void res.writeHead(400).end("wrong hash")
held.set(m[1], n)
puts++
res.writeHead(200).end("{}")
})
return
}
res.writeHead(404).end()
})
await new Promise<void>((r) => farm.listen(0, "127.0.0.1", r))
const url = `http://127.0.0.1:${(farm.address() as AddressInfo).port}`
const root = mkdtempSync(path.join(tmpdir(), "farm-blobs-"))
const store = path.join(root, "..", `${path.basename(root)}-hashes.json`)
mkdirSync(path.join(root, "media"), { recursive: true })
mkdirSync(path.join(root, "out"), { recursive: true })
mkdirSync(path.join(root, "brand"), { recursive: true })
writeFileSync(path.join(root, "media", "interview.MOV"), Buffer.alloc(5 << 20, 7))
writeFileSync(path.join(root, "media", "copy.MOV"), Buffer.alloc(5 << 20, 7)) // the same bytes: one upload
writeFileSync(path.join(root, "brand", "logo.png"), Buffer.alloc(300 << 10, 3))
writeFileSync(path.join(root, "brand", "icon.png"), Buffer.alloc(2 << 10, 3)) // small: stays in the tar
writeFileSync(path.join(root, "data.bin"), Buffer.alloc(6 << 20, 1)) // large, of no media type
writeFileSync(path.join(root, "edit.tsx"), "export default () => null\n")
writeFileSync(path.join(root, "out", "old.mp4"), Buffer.alloc(5 << 20, 9)) // an old render: the tar's excludes leave it
symlinkSync(path.join(root, "media", "interview.MOV"), path.join(root, "media", "link.MOV"))
const skip = excluded(["./.git", "./out/*", "./.raea-cloud-out", "./kits"])
const blobs = farmBlobs(url, "farm-token")
const first = await farmInputs(root, blobs, skip, () => {}, store)
assert(first, "a farm with the cache answers")
const paths = first!.media.map((m) => m.path).sort()
assert(JSON.stringify(paths) === JSON.stringify(["brand/logo.png", "data.bin", "media/copy.MOV", "media/interview.MOV"]), `what goes by hash: ${paths}`)
assert(first!.media.every((m) => !m.href), "no href: the farm's own cache")
assert(puts === 3 && first!.sent === (5 << 20) + (300 << 10) + (6 << 20), `sent once each, the same bytes once: ${puts} puts, ${first!.sent}`)
ok("footage, large files and media over 256 KB go by hash, each sent once; code, small files, out/ and links stay in the tar")
const second = await farmInputs(root, blobs, skip, () => {}, store)
assert(second!.sent === 0 && puts === 3, "the next render sends nothing")
ok("the next render sends nothing: the farm has it all")
writeFileSync(path.join(root, "brand", "logo.png"), Buffer.alloc(300 << 10, 4))
const third = await farmInputs(root, blobs, skip, () => {}, store)
assert(third!.sent === 300 << 10 && puts === 4, `a changed file is sent again: ${third!.sent}`)
ok("a file changed since is hashed and sent again")
// a new folder that hard-links the same footage (a thread started again) hashes nothing again
const again = mkdtempSync(path.join(tmpdir(), "farm-blobs-linked-"))
mkdirSync(path.join(again, "media"))
linkSync(path.join(root, "media", "interview.MOV"), path.join(again, "media", "interview.MOV"))
const linked = await farmInputs(again, blobs, skip, () => {}, store)
assert(linked!.sent === 0 && linked!.media[0].oid === first!.media.find((m) => m.path === "media/interview.MOV")!.oid, "the linked file is known")
const known = JSON.parse(readFileSync(store, "utf8")) as Record<string, unknown>
assert(Object.keys(known).length === 4, `one entry a file (logo.png rewritten in place is the same file), not a path: ${Object.keys(known).length}`)
ok("a new folder that links the same footage hashes and sends nothing again")
cache = false
assert((await farmInputs(root, blobs, skip, () => {}, store)) === null, "an older farm")
ok("a farm without the cache answers null: the media goes in the tar")
farm.close()
+17
View File
@@ -70,6 +70,23 @@ def job(objects):
obj = {"path": "footage/take.mov", "oid": oid, "size": len(take), "href": f"{base}/{oid}", "header": {}}
# footage the box sent the farm itself (PUT /v1/blobs, no href): used from the cache as a link, never fetched
sent = b"interview " * 5000
soid = hashlib.sha256(sent).hexdigest()
open(os.path.join(cache, soid), "wb").write(sent)
ws = job([{"path": "media/int1.MOV", "oid": soid, "size": len(sent)}])
gets = hits["GET"]
ss = fm.fetch(ws, cache, log=lambda _: None)
assert open(os.path.join(ws, "media/int1.MOV"), "rb").read() == sent and os.path.islink(os.path.join(ws, "media/int1.MOV"))
assert ss == {"objects": 1, "fetched": 0, "cached": len(sent)} and hits["GET"] == gets, ss
try:
fm.fetch(job([{"path": "media/gone.MOV", "oid": "ab" * 32, "size": 10}]), cache, log=lambda _: None)
raise AssertionError("footage never sent was used")
except ValueError as e:
assert "never sent" in str(e)
ok("footage the box sent the farm itself comes from the cache as a link, and footage it never sent is refused")
w1 = job([obj])
s1 = fm.fetch(w1, cache, log=lambda _: None)
assert open(os.path.join(w1, "footage/take.mov"), "rb").read() == take
+16 -1
View File
@@ -1,6 +1,7 @@
# The farm's planner (deploy/modal/farm_plan.py) with stand-in GPUs: python3 test/farm_plan.py from sdk/cloud. The
# stand-ins write the frames they're asked for, so a split render is checked end to end, ffmpeg's encode included.
import json
import os
import shutil
import subprocess
@@ -33,8 +34,12 @@ class FakeGpu:
def remote(self, id, args, frames=None, first=0, probe=False, video=False):
self.calls.append(("probe" if probe else "run", frames, first))
self.args = getattr(self, "args", []) + [list(args)]
if probe:
return {"code": 0, "out": "", "s": 12.5, "length": self.length, "fps": 30, "w": 1920, "h": 1080}
# as raea does with two --manifest: the first wins, so the probe's own says nothing
if args.count("--manifest") > 0:
return {"code": 0, "out": "APPLIED 1 frames", "s": 12.5, "length": None, "fps": None, "w": None, "h": None, "manifest": {}}
return {"code": 0, "out": "", "s": 12.5, "length": self.length, "fps": 30, "w": 1920, "h": 1080, "manifest": {"length": self.length, "fps": 30}}
dest = os.path.join(self.root, "jobs", id, "frames")
os.makedirs(dest, exist_ok=True)
if video:
@@ -90,6 +95,16 @@ frames = int(subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select
assert frames == 60, frames
ok("a 60-frame render: frame 0, a timed run of 8, the rest on one more GPU, the runs joined into 60 frames")
# the render's own --manifest (as an agent passes it): the GPUs never get it, and it's written from frame 0's at the end
lines.clear()
m = FakeGpu(root)
os.makedirs(os.path.join(root, "jobs", "jm", "work"))
code = fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4", "--manifest", "out/a.render.json", "--quality", "high"], {"id": "jm", "gpu": "L4", "gpus": 10}, os.path.join(root, "jobs", "jm", "work"), log, m, {}, run)
assert code == 0, lines
assert all("--manifest" not in a and "--quality" in a for a in m.args), m.args
assert json.load(open(os.path.join(root, "jobs", "jm", "work", "out", "a.render.json")))["length"] == 60
ok("a render's own --manifest isn't passed to the GPUs (the probe would lose the length), and is written at the end")
lines.clear()
long = FakeGpu(root, length=1000)
os.makedirs(os.path.join(root, "jobs", "j2", "work"))
+55
View File
@@ -0,0 +1,55 @@
// The box's memory guard (server/memguard.ts): node test/memguard.ts from sdk/cloud. Offline, on a made-up process
// table; and on Linux, against a real process that grows past the floor (set high for the test), which it kills.
import { spawn } from "node:child_process"
import { existsSync } from "node:fs"
import { guard, MIN_RSS_MB, type Proc, victim } from "../server/memguard.ts"
const ok = (m: string) => console.log(`ok ${m}`)
const assert = (c: unknown, m: string) => {
if (!c) throw new Error(`not ok: ${m}`)
}
// the server (1), an agent (2) and its helper (3), a shell (4) running a render (5) and an ffmpeg (6); another box
// process (9) outside the server
const table: Proc[] = [
{ pid: 1, ppid: 0, rssMb: 120, name: "node" },
{ pid: 2, ppid: 1, rssMb: 300, name: "agy_acp_server" },
{ pid: 3, ppid: 2, rssMb: 180, name: "localharness" },
{ pid: 4, ppid: 3, rssMb: 4, name: "bash" },
{ pid: 5, ppid: 4, rssMb: 5200, name: "raea" },
{ pid: 6, ppid: 4, rssMb: 1500, name: "ffmpeg" },
{ pid: 9, ppid: 0, rssMb: 9000, name: "other" },
]
assert(victim(table, 1)?.pid === 5, "the largest runaway under the server")
assert(victim(table, 1, new Set([5]))?.pid === 6, "a kept one is passed over")
assert(victim(table.filter((p) => p.pid !== 5 && p.pid !== 6), 1) === null, `nothing under ${MIN_RSS_MB} MB is killed: not an agent, not the server`)
ok("it picks the largest process an agent started, never the agent, the server or anything outside it")
// the loop: memory fine, nothing happens; memory low, the victim is killed and said
let avail = 4000
const killed: number[] = []
const said: string[] = []
const g = guard((l) => said.push(l), { root: 1, everyMs: 10, mem: () => ({ totalMb: 8192, availableMb: avail }), list: () => table, kill: (p) => killed.push(p) })
await new Promise((r) => setTimeout(r, 60))
assert(killed.length === 0, "memory fine: nothing killed")
avail = 500
await new Promise((r) => setTimeout(r, 30))
g.stop()
assert(killed[0] === 5 && /raea \(pid 5, 5\.1 GB\)/.test(said[0]), `low: the render is stopped and said: ${said[0]}`)
ok("memory low: the render is stopped, and the guard says why")
if (existsSync("/proc/meminfo")) {
// a real child that grows to 1.5 GB, under a floor set just below what's free now, so its growth trips it
const { memory } = await import("../server/memguard.ts")
const start = memory().availableMb
const hog = spawn(process.execPath, ["-e", "const a=[]; for (let i=0;i<150;i++) a.push(Buffer.alloc(10<<20, 1)); setInterval(()=>{}, 1000)"], { stdio: "ignore" })
const lines: string[] = []
const real = guard((l) => lines.push(l), { everyMs: 200, mem: () => { const m = memory(); return { totalMb: m.totalMb, availableMb: m.availableMb + 700 - (start - 1200) } } })
const code = await new Promise<number | null>((r) => {
hog.on("exit", (c, sig) => r(sig === "SIGKILL" ? -9 : c))
setTimeout(() => (hog.kill("SIGKILL"), r(null)), 30_000)
})
real.stop()
assert(code === -9 && lines.length === 1, `the hog was killed by the guard: ${code} ${lines}`)
ok(`on this box: a 1.5 GB runaway was stopped (${lines[0].slice(0, 90)}…)`)
}
+62 -3
View File
@@ -7,8 +7,10 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { parseSummary, pick } from "../server/gpu.ts"
import { cutFaces, smallText, splitsOf } from "../server/frames.ts"
import { plan, projectRoot } from "../server/offload.ts"
import { shellEnv } from "../server/shell-os.ts"
import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
const L4 = `Devices:
========
@@ -56,11 +58,11 @@ try {
args: ["render", "scenes/edit.tsx", "-o", "out/x.mp4", "--frames", "30"],
moves: [],
})
// an output outside the project is written under .raea-cloud-out and moved after
// an output outside the project is written at its top as .raea-cloud-out-N-NAME (no folder to make) and moved after
const p = plan(["render", "scenes/edit.tsx", "-o", "/tmp/x.mp4", "--words", "words.json"], proj)
assert.ok(typeof p !== "string")
assert.deepEqual(p.args, ["render", "scenes/edit.tsx", "-o", ".raea-cloud-out/0-x.mp4", "--words", "words.json"])
assert.deepEqual(p.moves, [{ from: ".raea-cloud-out/0-x.mp4", to: "/tmp/x.mp4" }])
assert.deepEqual(p.args, ["render", "scenes/edit.tsx", "-o", ".raea-cloud-out-0-x.mp4", "--words", "words.json"])
assert.deepEqual(p.moves, [{ from: ".raea-cloud-out-0-x.mp4", to: "/tmp/x.mp4" }])
// an input outside the project can't go
assert.match(plan(["render", "scenes/edit.tsx", "-o", "x.mp4", "--words", "../elsewhere.json"], proj) as string, /outside the project/)
// no composition: nothing to send
@@ -76,3 +78,60 @@ assert.deepEqual(shellEnv({ Path: "C:\\w" }, true, "C:\\g\\usr\\bin\\sh.exe"), {
assert.deepEqual(shellEnv({ PATH: "C:\\w" }, true, "bash"), { PATH: "C:\\w" })
assert.deepEqual(shellEnv({ PATH: "/usr/bin" }, false, "/bin/bash"), { PATH: "/usr/bin" })
console.log("units: ok")
// google-token.ts: Antigravity's Google sign-in link, the address the browser lands on, the credential's files
{
const out = `I1124 credential_manager.py:561] Launching browser login flow...\nhttps://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=x.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A54616%2F&state=abc123&access_type=offline\n`
const l = linkIn(out)!
assert.equal(l.port, 54616)
assert.equal(l.state, "abc123")
assert.equal(linkIn("https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https%3A%2F%2Fevil.example%2F&state=x"), undefined, "a link back anywhere but this box is refused")
assert.equal(landedQuery("http://127.0.0.1:54616/?state=abc123&code=4/0Ab&scope=email", l), "/?state=abc123&code=4/0Ab&scope=email")
assert.throws(() => landedQuery("http://127.0.0.1:54616/?state=other&code=4/0Ab", l), /another sign-in/)
assert.throws(() => landedQuery("http://127.0.0.1:9999/?state=abc123&code=4/0Ab", l), /isn't the page/)
assert.throws(() => landedQuery("http://127.0.0.1:54616/?state=abc123", l), /no code/)
assert.throws(() => landedQuery("http://127.0.0.1:54616/?error=access_denied&state=abc123", l), /access_denied/)
assert.throws(() => landedQuery("4/0Ab-just-a-code", l), /whole address/)
const home = mkdtempSync(path.join(os.tmpdir(), "units-gemini-"))
mkdirSync(path.join(home, "antigravity-acp"), { recursive: true })
writeFileSync(path.join(home, "antigravity-acp", "oauth.json"), '{"refresh_token":"1//x","email":"[email protected]"}')
writeFileSync(path.join(home, "antigravity-acp", "settings.json"), '{"theme":"dark"}')
const c = packCredential(home)!
assert.ok(c.startsWith("agy1:"))
assert.deepEqual(Object.keys(JSON.parse(Buffer.from(c.slice(5), "base64").toString())), ["antigravity-acp/oauth.json"], "only the token file goes")
const other = mkdtempSync(path.join(os.tmpdir(), "units-gemini-"))
unpackCredential(c, other)
assert.equal(packCredential(other), c)
assert.throws(() => unpackCredential(`agy1:${Buffer.from(JSON.stringify({ "../../etc/x": "y" })).toString("base64")}`, other), /outside its folder/)
rmSync(home, { recursive: true, force: true })
rmSync(other, { recursive: true, force: true })
console.log("ok google-token")
}
{
// frames.ts: a face at the frame's edge for a second is an error, for half a second a warning; a face too small to be
// someone in the shot is left alone
const fr = (faces: number[][], seams: [string, number, number][] = []) => ({ w: 540, h: 960, faces, seams })
const edge = [0, 400, 40, 90, 0.9]
const whole = [200, 300, 80, 100, 0.9]
let f = cutFaces([fr([whole]), fr([edge]), fr([edge]), fr([whole]), fr([edge]), fr([[0, 50, 10, 12, 0.9]])])
assert.deepEqual(f.map((x) => [x.level, x.at, x.until]), [["error", 0.5, 1.5], ["warn", 2, 2.5]])
assert.match(f[0].says, /left edge/)
// a split screen: a lone line held; a caption's box (two lines close together) isn't one
assert.deepEqual(splitsOf(fr([], [["h", 480, 0.8]])), [{ axis: "h", at: 480 }])
assert.deepEqual(splitsOf(fr([], [["h", 446, 0.8], ["h", 513, 0.8]])), [])
assert.deepEqual(splitsOf(fr([], [["h", 60, 0.9]])), [], "near the edge: a letterbox or a header")
const seam: [string, number, number][] = [["h", 480, 0.8]]
f = cutFaces([fr([[200, 430, 80, 50, 0.9]], seam), fr([[200, 430, 80, 50, 0.9]], seam), fr([[200, 430, 80, 50, 0.9]], seam)])
assert.ok(f.some((x) => x.kind === "face-cut" && /seam/.test(x.says) && x.level === "error"))
f = cutFaces([fr([[200, 200, 80, 100, 0.9]], seam), fr([[200, 200, 80, 100, 0.9]], seam), fr([[200, 200, 80, 100, 0.9]], seam)])
assert.deepEqual(f.map((x) => x.kind), ["split"], "one face over a split: a split for nothing")
f = cutFaces([0, 1, 2].map(() => fr([[200, 200, 80, 100, 0.9], [200, 650, 80, 100, 0.9]], seam)))
assert.deepEqual(f, [], "two people, one each side")
// text sizes in pixels of a 1080-wide frame: a 720-wide render's 28 px is 42 px
const m = (w: number, size: number) => ({ width: w, height: (w * 16) / 9, fps: 30, frames: [{ frame: 0, text: [{ text: "Not for surgeries", size, opacity: 1 }] }] })
assert.equal(smallText(m(1080, 28))[0].level, "error")
assert.equal(smallText(m(720, 28))[0].level, "warn")
assert.deepEqual(smallText(m(1080, 64)), [])
console.log("ok frames")
}
+22
View File
@@ -0,0 +1,22 @@
// raea words (server/words.ts) offline: a word cut short is an error, words after a cut missing, the same words pass,
// a different word a warning, a crossfade dip inside a word found, a word on the first frame flagged only when the
// sound is already at speech level there, and two words handed back as one split. Run: node test/words.ts
import { compare, fades, norm, split } from "../server/words.ts"
const w = (t: string, s: number, e: number) => ({ text: t, start: s, end: e })
const ok = (c: boolean, m: string) => { if (!c) { console.log("not ok", m); process.exitCode = 1 } else console.log("ok", m) }
ok(norm("$1,000.") === "1000", "norm money")
const heard = [w("So", 0.1, 0.3), w("he", 0.3, 0.4), w("hurt", 0.4, 0.6), w("his", 0.6, 0.7), w("paw,", 0.7, 0.9), w("and", 1.0, 1.1), w("some", 1.1, 1.3), w("test", 1.3, 1.5)]
const f = compare("So he hurt his paw and some tests. Because it's expensive", heard)
ok(f.some((x) => x.kind === "clipped" && x.says.includes("tests")), "tests cut short to test is an error")
ok(f.filter((x) => x.kind === "missing").length === 3, "the three words after the cut are missing")
ok(compare("So he hurt his paw", heard.slice(0, 5)).length === 0, "the same words pass")
ok(compare("So he hurt his dog", heard.slice(0, 5)).some((x) => x.kind === "changed"), "a different word is a warning")
// levels: speech at -20 dB, a 300 ms dip to -40 inside "hurt"
const db = Array.from({ length: 200 }, (_, i) => (i >= 40 && i < 70 ? -40 : -20))
const hw = [w("So", 0.1, 0.3), w("hurt", 0.35, 0.8), w("his", 0.8, 1.2), w("paw", 1.2, 1.9)]
ok(fades(db, hw, 2).some((x) => x.kind === "faded"), "a crossfade dip inside a word is found")
ok(!fades(Array(200).fill(-20), hw, 2).some((x) => x.kind === "faded"), "even speech has no dip")
ok(!fades(Array.from({ length: 200 }, (_, i) => (i >= 60 && i < 80 ? -40 : -20)), hw, 2).some((x) => x.kind === "faded"), "a word trailing off to its end is not a fade")
ok(fades(Array(200).fill(-20), [w("Hi", 0.0, 0.3), ...hw.slice(1)], 2).some((x) => x.kind === "edge"), "a word on the first frame is flagged when the sound is loud there")
ok(!fades([-60, -60, -60, ...Array(197).fill(-20)], [w("Hi", 0.0, 0.3), ...hw.slice(1)], 2).some((x) => x.kind === "edge"), "Whisper putting a word at 0 over silence is not")
ok(split([w("for $60", 1, 2)]).map((x) => x.text).join("|") === "for|$60", "two words handed back as one are split")
@@ -41,3 +41,59 @@ test("an Image's load fires once its src is set", async () => {
await Promise.resolve();
expect([seen, img.complete, img.src]).toEqual([["onload", "listener"], true, "/media/x.png"]);
});
// #253: a loaded Image has the picture's size (a canvas sized from it was 0 high, and its CanvasTexture refused)
const host = globalThis as { __raea_call?: (n: string, j: string) => string | undefined };
const loaded = (img: any) => new Promise<string>((ok) => {
img.onload = () => ok("load");
img.onerror = () => ok("error");
});
test("a loaded Image's width, height and natural size are the picture's, from the host (asset.load)", async () => {
const calls: string[] = [];
host.__raea_call = (name, json) => {
calls.push(`${name} ${json}`);
return name === "asset.load" ? JSON.stringify({ path: "/edit/public/site.png", bytes: 999, width: 400, height: 300 }) : undefined;
};
try {
const img = new ours.Image();
const done = loaded(img);
img.src = "/media/site.png";
expect([img.naturalWidth, img.width]).toEqual([0, 0]);
expect(await done).toBe("load");
expect([img.width, img.height, img.naturalWidth, img.naturalHeight]).toEqual([400, 300, 400, 300]);
expect(calls).toEqual([`asset.load {"path":"/media/site.png"}`]);
// width and height given (the constructor's, or set) stay as given; the natural size is still the picture's
const sized = new ours.Image(50, 20);
const both = loaded(sized);
sized.src = "/media/site.png";
await both;
expect([sized.width, sized.height, sized.naturalWidth, sized.naturalHeight]).toEqual([50, 20, 400, 300]);
sized.height = 10;
expect([sized.width, sized.height]).toEqual([50, 10]);
} finally {
delete host.__raea_call;
}
});
test("a data: URL Image's size comes from its header; a file the host can't find fires error", async () => {
// a 3 x 2 PNG
const png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAEklEQVR4nGP4z8DwH4YZYBwAaG8H+VKwN2UAAAAASUVORK5CYII=";
const img = new ours.Image();
const done = loaded(img);
img.src = png;
expect(await done).toBe("load");
expect([img.width, img.height, img.naturalWidth, img.naturalHeight]).toEqual([3, 2, 3, 2]);
host.__raea_call = () => {
throw new Error("asset.load: asset /media/gone.png: No such file or directory");
};
try {
const gone = new ours.Image();
const failed = loaded(gone);
gone.src = "/media/gone.png";
expect(await failed).toBe("error");
expect([gone.complete, gone.naturalWidth, gone.width]).toEqual([true, 0, 0]);
} finally {
delete host.__raea_call;
}
});
+47 -2
View File
@@ -227,9 +227,18 @@ rounds?: number,
/**
* a cut job's contract: the brief as rules (cut.rs)
*/
cut?: MakeCut, };
cut?: MakeCut,
/**
* a goal job's contract: the goal and its rules (goal.rs)
*/
goal?: MakeGoal,
/**
* what the job shows but never delivers, relative to the brief (pictures, render tests, examples): each a file or a
* `dir/` (review/ and previews/ when left out). Deliverables are what it hands over; previews are how it got there
*/
previews?: Array<string>, };
export type MakeKind = "scene" | "kit" | "shot" | "cut";
export type MakeKind = "scene" | "kit" | "shot" | "cut" | "goal";
export type MakeSource = "customer" | "reference";
@@ -398,6 +407,10 @@ text: string, from: string,
every?: boolean, };
export type MakeCta = { text: string, from: string,
/**
* the other lines a brief rotates (two host lines, a paid take's): any one lands it, each found in the brief
*/
also?: Array<string>,
/**
* how near the end it must land, in seconds (8 when left out)
*/
@@ -412,3 +425,35 @@ about?: string,
* the person's answer, as they gave it, and who gave it: until then the job can't be done
*/
answer?: string, by?: string, };
export type MakeGoal = {
/**
* the goal as the person said it
*/
goal: string,
/**
* what must hold before the agent may stop: every one, each checked in code or by a fresh critic
*/
rules?: Array<MakeGoalRule>, };
export type MakeGoalRule = {
/**
* a short name: [a-z0-9_], how status, the critic and NOTES.md name it
*/
id: string,
/**
* a command that must exit 0, run in the brief's folder (`bun test`, `raea check edit.tsx`)
*/
run?: string,
/**
* the seconds `run` gets before it counts as failed (300 when left out)
*/
timeout?: number,
/**
* a file that must exist, relative to the brief (`a|b`: either; `dir/`: three or more pictures in it)
*/
file?: string,
/**
* words that must be true of the work, judged by a fresh critic (`raea make judge`), never by the agent that did it
*/
says?: string, };
+5 -1
View File
@@ -7,7 +7,7 @@
//
// The types are generated from the Rust schemas (core/brief, raea-core-brief) into brief.gen.ts, so what tsc checks is
// what raea reads: `raea context` evaluates the module and Rust validates its default export again.
import type { Brief, Make, Parts, Script, Taste } from "./brief.gen";
import type { Brief, Make, MakeGoal, Parts, Script, Taste } from "./brief.gen";
export type * from "./brief.gen";
export { fingerprint } from "./fingerprint";
@@ -37,3 +37,7 @@ export const kit = (m: Omit<Make, "kind">): Make => ({ kind: "kit", ...m });
export const shot = (m: Omit<Make, "kind">): Make => ({ kind: "shot", ...m });
/** ads cut from footage to a client's brief: `cut: {...}` is the brief as rules, each quoting it (docs/make.feature MK25) */
export const cut = (m: Omit<Make, "kind">): Make => ({ kind: "cut", ...m });
/** any other work held to a goal (`/goal`): the goal in the person's words and the rules that must hold before the agent
* stops, each a command that must pass (`run`), a file that must exist (`file`) or words a fresh critic judges
* (`says`, by `raea make judge`). `raea make status` holds the agent to every one. */
export const goal = ({ goal, rules, ...m }: MakeGoal & Omit<Make, "kind" | "goal">): Make => ({ kind: "goal", goal: { goal, rules }, ...m });
+56 -11
View File
@@ -2,8 +2,13 @@
// for a web page call them. requestAnimationFrame's callbacks run once per frame the composition draws, given that frame's
// time (f * 1000 / fps ms), so a frame drawn again (a resumed render, `--at`) gets the same calls; one asked for while a
// frame draws runs at the next frame. `new Image()` loads: setting its src fires load (and onload) on the next microtask,
// so a preload resolves. It has no pixel size (naturalWidth and the rest stay 0): nothing reads a file's size
// synchronously here, and `<img>` draws the file itself.
// so a preload resolves, and by then naturalWidth and naturalHeight are the picture's size (#253): a data: URL's from its
// header, a file's or URL's from the host (native asset.load, which finds staticFile's /media/ paths as <Img> does).
// width and height are the ones given (the constructor's, or set) else the natural size, as a browser has them. A file
// the host can't find fires error (and onerror) instead. Under plain bun, with no host, a file's size stays 0.
import { hasNative, native } from "@raea/app/native";
import { sniffSize } from "@raea/ui/canvas";
type FrameCallback = (time: number) => void;
@@ -54,13 +59,20 @@ export function frameCallbacks(f: number, fps: number): void {
type Listener = (e: { type: string; target: unknown; currentTarget: unknown }) => void;
/** A preloadable image: its src set, load fires. */
/** A picture's size: a data: URL's from its header, anything else from the host (asset.load); null when it has none
* (no host, or a format the header doesn't say). Throws the host's error for a file that isn't there. */
function pictureSize(src: string): [number, number] | null {
if (src.startsWith("data:")) return sniffSize(src);
if (src.startsWith("blob:") || !hasNative()) return null;
const got = native("asset.load", { path: src });
return got && typeof got.width === "number" && typeof got.height === "number" ? [got.width, got.height] : null;
}
/** A preloadable image: its src set, load fires, with the picture's size. */
class FrameImage {
onload: Listener | null = null;
onerror: Listener | null = null;
complete = true;
width = 0;
height = 0;
naturalWidth = 0;
naturalHeight = 0;
alt = "";
@@ -68,11 +80,30 @@ class FrameImage {
decoding = "auto";
loading = "eager";
#src = "";
#width: number | null;
#height: number | null;
#loads = 0;
#listeners = new Map<string, Set<Listener>>();
constructor(width?: number, height?: number) {
this.width = width ?? 0;
this.height = height ?? 0;
this.#width = width ?? null;
this.#height = height ?? null;
}
get width(): number {
return this.#width ?? this.naturalWidth;
}
set width(v: number) {
this.#width = Number(v) || 0;
}
get height(): number {
return this.#height ?? this.naturalHeight;
}
set height(v: number) {
this.#height = Number(v) || 0;
}
get src(): string {
@@ -80,13 +111,27 @@ class FrameImage {
}
set src(v: string) {
this.#src = String(v);
const src = String(v);
this.#src = src;
this.complete = false;
this.naturalWidth = 0;
this.naturalHeight = 0;
const load = ++this.#loads;
queueMicrotask(() => {
// a src set again before this one loaded: only the last one's load fires, as in a browser
if (load !== this.#loads) return;
let type = "load";
try {
const size = pictureSize(src);
if (size) [this.naturalWidth, this.naturalHeight] = size;
} catch (err) {
type = "error";
console.warn(`new Image(): ${src} didn't load: ${err instanceof Error ? err.message : String(err)}`);
}
this.complete = true;
const e = { type: "load", target: this, currentTarget: this };
this.onload?.call(this, e);
for (const l of this.#listeners.get("load") ?? []) l.call(this, e);
const e = { type, target: this, currentTarget: this };
(type === "load" ? this.onload : this.onerror)?.call(this, e);
for (const l of this.#listeners.get(type) ?? []) l.call(this, e);
});
}
+1 -1
Submodule skills updated: ae1c222713...98de983bca.
+2
View File
@@ -9,6 +9,8 @@ description = "raea's one mixer core: the same Firewheel graph plays live in the
[dependencies]
# the mix before the master: dialogue at one level, room tone at the joins
raea-sys-mix-level = { path = "level" }
# the system's output: the stream live play runs in, moved onto the device in use
raea-sys-mix-device = { path = "device" }
raea-io-trace = { path = "../../io/trace" }
# the bounce's scratch file, as the frames come (SG4a)
raea-io-home = { path = "../../io/home" }
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "raea-sys-mix-device"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea's mixer on the system's output: Firewheel's processor driven from cpal's callback, and moved onto the device in use when the output changes or the stream breaks"
[dependencies]
raea-io-trace = { path = "../../../io/trace" }
# the mixer's graph, as raea-sys-mix pins it
firewheel = { version = "=0.12.1", default-features = false, features = ["std", "scheduled_events"] }
# the cpal react and the legacy app use (0.15): Firewheel's own CPAL backend needs 0.18, which can't link beside 0.15
cpal = "0.15"
# the processor's output, pulled into a stereo buffer
audioadapter-buffers = { version = "4.0.0", default-features = false, features = ["std"] }
+130
View File
@@ -0,0 +1,130 @@
//! The mixer's output: the system's default device, with Firewheel's processor pulled from cpal's callback, followed
//! when the system's output changes (headphones in, AirPods away, a display's speakers) or cpal says the stream broke
//! (11-26, Shane: "sometimes i dont hear any sound": the stream stayed on the device it opened on, gone or not the one
//! being listened to).
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use audioadapter_buffers::direct::InterleavedSlice;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
pub use cpal::Stream;
use firewheel::backend::BackendProcessInfo;
use firewheel::node::StreamStatus;
use firewheel::{ActivateInfo, FirewheelContext};
/// The output a mixer plays on: the device's name (empty while there's none), the rate and block size it asks for,
/// and whether cpal said the stream broke.
pub struct Output {
pub name: String,
rate: u32,
block: u32,
lost: Arc<AtomicBool>,
looked: Instant,
}
impl Output {
/// The default device's stream, and the rate it runs at (`rate` when the device takes it).
pub fn open(cx: &mut FirewheelContext, rate: u32, block: u32) -> Result<(Output, Stream, u32), String> {
let lost = Arc::new(AtomicBool::new(false));
let (stream, got, name) = start(cx, rate, block, lost.clone())?;
Ok((Output { name, rate, block, lost, looked: Instant::now() }, stream, got))
}
/// Whether the stream should move: at once after cpal said it broke, else when the system's default output, looked
/// at once a second, is another device.
pub fn moved(&mut self) -> bool {
let lost = self.lost.load(Ordering::Relaxed);
if !lost && self.looked.elapsed() < Duration::from_secs(1) {
return false;
}
self.looked = Instant::now();
let now = cpal::default_host().default_output_device().and_then(|d| d.name().ok()).unwrap_or_default();
lost || (!now.is_empty() && now != self.name)
}
/// The stream started again on the default device: `old` is let go first, which hands the graph back (its
/// processor dropped). The new stream and its rate, or no device to play on (looked for again in a second).
pub fn reopen(&mut self, cx: &mut FirewheelContext, old: Option<Stream>) -> Result<(Stream, u32), String> {
drop(old);
let t0 = Instant::now();
while cx.is_active() && t0.elapsed() < Duration::from_millis(500) {
let _ = cx.update();
std::thread::sleep(Duration::from_millis(1));
}
self.lost.store(false, Ordering::Relaxed);
match start(cx, self.rate, self.block, self.lost.clone()) {
Ok((stream, rate, name)) => {
eprintln!("raea mixer: sound now on {name} (was {})", if self.name.is_empty() { "nothing" } else { &self.name });
self.name = name;
Ok((stream, rate))
}
Err(e) => {
if !self.name.is_empty() {
eprintln!("raea mixer: no sound: {e}");
}
self.name.clear();
Err(e)
}
}
}
}
/// The default output device, at `want` Hz when it takes it, `block` frames a callback when it takes that: Firewheel's
/// processor pulled from cpal's callback, as the bounce pulls it into a buffer (stereo, spread over the device's
/// channels).
fn start(cx: &mut FirewheelContext, want: u32, block: u32, lost: Arc<AtomicBool>) -> Result<(Stream, u32, String), String> {
let host = cpal::default_host();
let dev = host.default_output_device().ok_or("no audio output device")?;
let name = dev.name().unwrap_or_default();
let def = dev.default_output_config().map_err(|e| format!("audio output: {e}"))?;
let channels = def.channels();
let takes_48k = dev.supported_output_configs().map(|mut c| c.any(|r| r.channels() == channels && r.sample_format() == cpal::SampleFormat::F32 && r.min_sample_rate().0 <= want && r.max_sample_rate().0 >= want)).unwrap_or(false);
let rate = if takes_48k { want } else { def.sample_rate().0 };
let max_block = 8192usize;
let mut proc = cx
.activate(ActivateInfo { sample_rate: std::num::NonZeroU32::new(rate).unwrap(), max_block_frames: std::num::NonZeroU32::new(max_block as u32).unwrap(), num_stream_in_channels: 0, num_stream_out_channels: 2, input_to_output_latency_seconds: 0.0 })
.map_err(|e| format!("the mixer's graph: {e:?}"))?;
let ch = channels as usize;
let began = std::time::Instant::now();
let mut stereo = vec![0f32; max_block * 2];
let empty: [f32; 0] = [];
let mut callback = move |out: &mut [f32], info: &cpal::OutputCallbackInfo| {
let ts = info.timestamp();
let delay = ts.playback.duration_since(&ts.callback);
let frames = out.len() / ch.max(1);
let mut done = 0;
while done < frames {
let k = (frames - done).min(max_block);
let pi = BackendProcessInfo { frames: k, process_timestamp: Some(std::time::Instant::now()), duration_since_stream_start: began.elapsed(), input_stream_status: StreamStatus::empty(), output_stream_status: StreamStatus::empty(), dropped_frames: 0, process_to_playback_delay: delay };
if let (Ok(input), Ok(mut output)) = (InterleavedSlice::new(&empty[..], 0, 0), InterleavedSlice::new_mut(&mut stereo[..k * 2], 2, k)) {
proc.process(&input, &mut output, pi);
}
for i in 0..k {
let (l, r) = (stereo[2 * i], stereo[2 * i + 1]);
let o = &mut out[(done + i) * ch..(done + i + 1) * ch];
match ch {
1 => o[0] = 0.5 * (l + r),
_ => {
o[0] = l;
o[1] = r;
o[2..].fill(0.0);
}
}
}
done += k;
}
};
// the block size when the device's range takes it, else its own
let fits = dev.supported_output_configs().map(|mut c| c.any(|r| r.channels() == channels && matches!(r.buffer_size(), cpal::SupportedBufferSize::Range { min, max } if *min <= block && block <= *max))).unwrap_or(false);
let config = cpal::StreamConfig { channels, sample_rate: cpal::SampleRate(rate), buffer_size: if fits { cpal::BufferSize::Fixed(block) } else { cpal::BufferSize::Default } };
let mut said = raea_io_trace::once::said_once::<cpal::StreamError>("raea mixer");
let broke = move |e: cpal::StreamError| {
lost.store(true, Ordering::Relaxed);
said(e)
};
let stream = dev.build_output_stream(&config, move |o: &mut [f32], i: &cpal::OutputCallbackInfo| callback(o, i), broke, None).map_err(|e| format!("audio stream: {e}"))?;
stream.play().map_err(|e| format!("audio stream: {e}"))?;
Ok((stream, rate, name))
}
+38 -62
View File
@@ -11,12 +11,11 @@ use std::sync::atomic::Ordering;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex};
use audioadapter_buffers::direct::InterleavedSlice;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use firewheel::backend::BackendProcessInfo;
use cpal::traits::StreamTrait;
use firewheel::clock::{EventInstant, InstantSamples};
use firewheel::node::{NodeID, StreamStatus};
use firewheel::{ActivateInfo, FirewheelConfig, FirewheelContext};
use firewheel::node::NodeID;
use firewheel::{FirewheelConfig, FirewheelContext};
use raea_sys_mix_device::Output;
use crate::nodes::{Stats, event};
use raea_io_media::pcm::Pcm;
@@ -34,7 +33,10 @@ const SLEW: f64 = 0.00025;
pub struct Live {
cx: FirewheelContext,
_stream: cpal::Stream,
/// the device's stream: None for the moment it's reopened on another device (follow_device)
_stream: Option<cpal::Stream>,
/// the output it plays on, followed when the system's output changes (raea-sys-mix-device)
out: Output,
voices: NodeID,
master: NodeID,
score: Option<Score>,
@@ -85,7 +87,7 @@ impl Live {
let mut cx = FirewheelContext::new(FirewheelConfig::default());
let (voices, master) = crate::graph(&mut cx, stats.clone(), tap.as_ref().map(|t| t.1.clone()), mute)?;
let block = std::env::var("RAEA_AUDIO_BLOCK").ok().and_then(|v| v.parse().ok()).unwrap_or(256u32);
let (stream, rate) = start(&mut cx, block)?;
let (out, stream, rate) = Output::open(&mut cx, RATE, block)?;
if rate != RATE {
eprintln!("raea mixer: the device runs at {rate} Hz, not {RATE}: live play can't be the bounce sample for sample");
}
@@ -97,7 +99,7 @@ impl Live {
// a device opened beside the edit's open waits for nothing by then
Ok(Live {
opened: std::time::Instant::now(),
settled: false, cx, _stream: stream, voices, master, score: None, pcm: HashMap::new(), opening: HashMap::new(), loader: raea_io_media::pcm::loader(), rate, head, head_base: head, origin: None, drift_ms: Vec::new(), anchors: Vec::new(), slews: 0, load_ms: Vec::new(), load_wait: std::time::Duration::from_millis(std::env::var("RAEA_AUDIO_LOAD_WAIT_MS").ok().and_then(|v| v.parse().ok()).unwrap_or(80)), used: HashMap::new(), items: Vec::new(), keep: HashMap::new(), blocks: Vec::new(), master_set: (0.0, 20.0 * (crate::nodes::CEILING as f64).log10()), bypass: false, resting: false, built: Default::default(), stats, tap })
settled: false, cx, _stream: Some(stream), out, voices, master, score: None, pcm: HashMap::new(), opening: HashMap::new(), loader: raea_io_media::pcm::loader(), rate, head, head_base: head, origin: None, drift_ms: Vec::new(), anchors: Vec::new(), slews: 0, load_ms: Vec::new(), load_wait: std::time::Duration::from_millis(std::env::var("RAEA_AUDIO_LOAD_WAIT_MS").ok().and_then(|v| v.parse().ok()).unwrap_or(80)), used: HashMap::new(), items: Vec::new(), keep: HashMap::new(), blocks: Vec::new(), master_set: (0.0, 20.0 * (crate::nodes::CEILING as f64).log10()), bypass: false, resting: false, built: Default::default(), stats, tap })
}
/// The master: `gain_db` on the sum, then the limiter at `ceiling_db` (dBTP).
@@ -209,6 +211,7 @@ impl Live {
/// Frame `f`'s sounds and notes, the frame stepped `lag` seconds after its own time.
pub fn sync(&mut self, f: i64, fps: f64, sounds: &[Sound], tone: &ToneCue, lag: f64) {
self.follow_device();
self.wake();
let rate = self.rate;
let score = self.score.get_or_insert_with(|| Score::new(fps, rate));
@@ -344,13 +347,36 @@ impl Live {
let _ = self.cx.update();
}
/// The system's output, followed: once a second (and at once after cpal says the stream broke) the default output
/// device is looked at, and a different one (headphones in, AirPods away, a display's speakers) gets the stream: the
/// old one is let go, which hands the graph back (its processor dropped), and it starts again on the new device. The
/// timeline is placed again on the next frame, as after a rest.
fn follow_device(&mut self) {
if !self.out.moved() {
return;
}
let Ok((stream, rate)) = self.out.reopen(&mut self.cx, self._stream.take()) else { return };
if rate != self.rate {
// the head and the score count samples: both at the new device's rate
self.head_base = (self.head_base as f64 * rate as f64 / self.rate as f64).round() as i64;
self.rate = rate;
self.score = None;
}
self._stream = Some(stream);
self.resting = false;
self.origin = None;
self.settled = false;
self.opened = std::time::Instant::now();
let _ = self.cx.update();
}
/// The device stream stopped (after stop_all and its fade-outs: nothing is heard): no callback runs, so neither the
/// graph nor the device works while a stage sits paused. The next sync starts it again and places the timeline.
pub fn rest(&mut self) {
if self.resting || self.origin.is_some() {
return;
}
if self._stream.pause().is_ok() {
if self._stream.as_ref().is_some_and(|s| s.pause().is_ok()) {
self.resting = true;
}
}
@@ -362,7 +388,9 @@ impl Live {
return;
}
self.resting = false;
let _ = self._stream.play();
if let Some(s) = &self._stream {
let _ = s.play();
}
let (s0, t0) = (self.cx.audio_clock().samples.0, std::time::Instant::now());
while self.cx.audio_clock().samples.0 == s0 && t0.elapsed() < std::time::Duration::from_millis(100) {
std::thread::sleep(std::time::Duration::from_millis(1));
@@ -404,58 +432,6 @@ impl Live {
}
}
/// The default output device, at 48 kHz when it takes it, `block` frames a callback when it takes that: Firewheel's
/// processor pulled from cpal's callback, as the bounce pulls it into a buffer (stereo, spread over the device's
/// channels).
fn start(cx: &mut FirewheelContext, block: u32) -> Result<(cpal::Stream, u32), String> {
let host = cpal::default_host();
let dev = host.default_output_device().ok_or("no audio output device")?;
let def = dev.default_output_config().map_err(|e| format!("audio output: {e}"))?;
let channels = def.channels();
let takes_48k = dev.supported_output_configs().map(|mut c| c.any(|r| r.channels() == channels && r.sample_format() == cpal::SampleFormat::F32 && r.min_sample_rate().0 <= RATE && r.max_sample_rate().0 >= RATE)).unwrap_or(false);
let rate = if takes_48k { RATE } else { def.sample_rate().0 };
let max_block = 8192usize;
let mut proc = cx
.activate(ActivateInfo { sample_rate: std::num::NonZeroU32::new(rate).unwrap(), max_block_frames: std::num::NonZeroU32::new(max_block as u32).unwrap(), num_stream_in_channels: 0, num_stream_out_channels: 2, input_to_output_latency_seconds: 0.0 })
.map_err(|e| format!("the mixer's graph: {e:?}"))?;
let ch = channels as usize;
let began = std::time::Instant::now();
let mut stereo = vec![0f32; max_block * 2];
let empty: [f32; 0] = [];
let mut callback = move |out: &mut [f32], info: &cpal::OutputCallbackInfo| {
let ts = info.timestamp();
let delay = ts.playback.duration_since(&ts.callback);
let frames = out.len() / ch.max(1);
let mut done = 0;
while done < frames {
let k = (frames - done).min(max_block);
let pi = BackendProcessInfo { frames: k, process_timestamp: Some(std::time::Instant::now()), duration_since_stream_start: began.elapsed(), input_stream_status: StreamStatus::empty(), output_stream_status: StreamStatus::empty(), dropped_frames: 0, process_to_playback_delay: delay };
if let (Ok(input), Ok(mut output)) = (InterleavedSlice::new(&empty[..], 0, 0), InterleavedSlice::new_mut(&mut stereo[..k * 2], 2, k)) {
proc.process(&input, &mut output, pi);
}
for i in 0..k {
let (l, r) = (stereo[2 * i], stereo[2 * i + 1]);
let o = &mut out[(done + i) * ch..(done + i + 1) * ch];
match ch {
1 => o[0] = 0.5 * (l + r),
_ => {
o[0] = l;
o[1] = r;
o[2..].fill(0.0);
}
}
}
done += k;
}
};
// the block size when the device's range takes it, else its own
let fits = dev.supported_output_configs().map(|mut c| c.any(|r| r.channels() == channels && matches!(r.buffer_size(), cpal::SupportedBufferSize::Range { min, max } if *min <= block && block <= *max))).unwrap_or(false);
let config = cpal::StreamConfig { channels, sample_rate: cpal::SampleRate(rate), buffer_size: if fits { cpal::BufferSize::Fixed(block) } else { cpal::BufferSize::Default } };
let stream = dev.build_output_stream(&config, move |o: &mut [f32], i: &cpal::OutputCallbackInfo| callback(o, i), raea_io_trace::once::said_once::<cpal::StreamError>("raea mixer"), None).map_err(|e| format!("audio stream: {e}"))?;
stream.play().map_err(|e| format!("audio stream: {e}"))?;
Ok((stream, rate))
}
impl Drop for Live {
fn drop(&mut self) {
let Some((path, buf)) = self.tap.take() else { return };
+6
View File
@@ -159,6 +159,12 @@ pub fn draw(mut scenes: ResMut<Scenes>, mut vello: ResMut<Vello>, device: Res<Re
}
// the image atlas (each filtered element is an image in it) as large as the device can make, not Vello's 8192
vello::low_level::vello_encoding::set_max_atlas_size(device.limits().max_texture_dimension_2d);
// and the blend spill, grown for a scene whose layers nest past four (raea #247), within what the device binds
let limits = device.limits();
vello::low_level::vello_encoding::set_max_buffer_size((limits.max_storage_buffer_binding_size as u64).min(limits.max_buffer_size));
// and an image larger than the atlas (16384 at most, whatever the device allows) decoded at a size that fits it
// (raea#245: an M5's GPU allows 32768, and a 1080x18000 picture was kept whole and refused)
blitz_dom::net::set_max_image_side(vello::low_level::vello_encoding::max_atlas_size());
vello::Renderer::new(
device,
vello::RendererOptions { antialiasing_support: vello::AaSupport::area_only(), num_init_threads: std::num::NonZeroUsize::new(1), ..default() },
+92
View File
@@ -0,0 +1,92 @@
//! Three of 0.1.11's layout misses, each laid out from its issue's own repro: `font-variant: small-caps` drew in normal
//! case (#249), a flex row whose items fit but for f32 rounding wrapped (#252), and a `display: table` element around
//! its text drew nothing at all (#254).
use bevy::math::UVec2;
use blitz_dom::BaseDocument;
use raea_sys_page::{Page, config};
fn laid_out(body: &str) -> BaseDocument {
let html = format!("<!doctype html><html><body style=\"margin:0\">{body}</body></html>");
let mut doc = blitz_html::HtmlDocument::from_html(&html, config(Page { size: UVec2::new(700, 400), scale: 1.0 })).into_inner();
doc.resolve(0.0);
doc
}
/// The border box of the element with `id`: x, y, width, height.
fn rect(doc: &BaseDocument, id: &str) -> (f64, f64, f64, f64) {
let node = doc.query_selector(&format!("#{id}")).unwrap().unwrap_or_else(|| panic!("no #{id}"));
let r = doc.get_client_bounding_rect(node).unwrap_or_else(|| panic!("#{id} has no box"));
(r.x, r.y, r.width, r.height)
}
/// #249: small capitals in a face without an `smcp` feature (Georgia) are synthesised as Chrome does: each lower-case
/// letter drawn as its capital at 70% of the font size. So the line is as wide as those capitals written out at 28 px,
/// and narrower than the text in full capitals.
#[test]
fn small_caps_are_synthesised_capitals_at_70_percent() {
let doc = laid_out(
r#"<div style="font-size: 40px; font-family: Georgia, serif">
<span id="caps" style="font-variant: small-caps">Compliance Audit</span><br>
<span id="spelled">C<span style="font-size: 28px">OMPLIANCE</span> A<span style="font-size: 28px">UDIT</span></span><br>
<span id="plain">Compliance Audit</span><br>
<span id="upper">COMPLIANCE AUDIT</span>
</div>"#,
);
let width = |id| rect(&doc, id).2;
let (caps, spelled, plain, upper) = (width("caps"), width("spelled"), width("plain"), width("upper"));
assert!((caps - spelled).abs() < 0.5, "small caps {caps} px wide, the capitals written out at 28 px {spelled}");
assert!(caps < upper - 20.0, "small caps {caps} px wide, full capitals {upper}");
assert!((caps - plain).abs() > 5.0, "small caps {caps} px wide, the text in normal case {plain}: drawn as it is");
}
/// #252: three 183.6 px items and two 54 px gaps add up to the 658.8 px container in exact arithmetic, a few ulps over
/// it in f32. Chrome lays out in 1/64 px units and keeps them on one line: rows of 3 and 2, not 2, 2 and 1.
#[test]
fn a_flex_row_that_fits_but_for_rounding_stays_one_row() {
let (w, size, cols) = (1080.0_f64, 0.17, 3.0);
let items: String = (0..5).map(|i| format!(r#"<div id="i{i}" style="width: {}px; height: 60px"></div>"#, size * w)).collect();
let doc = laid_out(&format!(
r#"<div style="display: flex; flex-wrap: wrap; justify-content: center; gap: {}px {}px; width: {}px">{items}</div>"#,
0.04 * w,
0.05 * w,
(cols * size + (cols - 1.0) * 0.05) * w
));
let y = |i: usize| rect(&doc, &format!("i{i}")).1;
assert_eq!((y(1), y(2)), (y(0), y(0)), "the first three items share a row");
assert!(y(3) > y(0) && y(4) == y(3), "the last two share the second row: {:?}", (0..5).map(y).collect::<Vec<_>>());
}
/// #254: a `display: table` element holding only text is laid out as Chrome lays it out, its text in an anonymous row
/// and cell: a block as wide as its text (shrink-to-fit), with the next block below it.
#[test]
fn a_table_around_its_text_is_as_wide_as_its_text() {
let doc = laid_out(
r#"<div style="font-size: 30px">
<div id="table" style="display: table; background: #FFD43B">Line one as a table</div>
<div id="next">Line two, block</div>
<span id="text">Line one as a table</span>
</div>"#,
);
let (tx, ty, tw, th) = rect(&doc, "table");
let text = rect(&doc, "text");
let next = rect(&doc, "next");
assert!(th > 30.0, "the table is a line tall: {th}");
assert!((tw - text.2).abs() < 0.5, "the table is {tw} px wide, its text {}", text.2);
assert_eq!((tx, ty), (0.0, 0.0));
assert!((next.1 - (ty + th)).abs() < 0.5, "the next block starts below the table: {} against {}", next.1, ty + th);
}
/// #254, the rest of css-tables-3's wrapping: a table's stray text beside a row of its own gets an anonymous row of its
/// own above it, and a table of rows alone builds no anonymous box (its cells as before).
#[test]
fn stray_text_beside_a_row_gets_a_row_of_its_own() {
let doc = laid_out(
r#"<div id="t" style="display: table; font-size: 20px">loose
<div style="display: table-row"><div id="cell" style="display: table-cell">in a cell</div></div></div>
<table id="plain"><tr><td id="td">a</td></tr></table>"#,
);
let cell = rect(&doc, "cell");
assert!(cell.1 >= 20.0, "the cell is in the second row, below the loose text: {cell:?}");
let td = rect(&doc, "td");
assert!(td.2 > 0.0 && td.3 > 0.0, "a plain table's cell keeps its box: {td:?}");
}
+124
View File
@@ -0,0 +1,124 @@
//! 0.1.11's paint reports, each the issue's own repro as HTML, painted by blitz-paint into a recording scene and read
//! back: what is filled, in what colour or brush, and under which clips (no GPU, so every runner checks them).
use anyrender::recording::RenderCommand;
use anyrender::{Paint, Scene};
use bevy::math::UVec2;
use vello::kurbo::{Point, Rect, Shape};
use raea_sys_page::{Page, config};
fn painted(html: &str, w: u32, h: u32) -> Scene {
let mut doc = blitz_html::HtmlDocument::from_html(html, config(Page { size: UVec2::new(w, h), scale: 1.0 })).into_inner();
doc.resolve(0.0);
let mut scene = Scene::new();
blitz_paint::paint_scene(&mut scene, &mut doc, 1.0, w, h, 0, 0);
scene
}
/// Each fill: its brush, its box on the page, and the boxes of the layers it's clipped by.
fn fills(scene: &Scene) -> Vec<(Paint, Rect, Vec<Rect>)> {
let (mut clips, mut out) = (Vec::new(), Vec::new());
for c in &scene.commands {
match c {
RenderCommand::PushLayer(l) => clips.push(l.transform.transform_rect_bbox(l.clip.bounding_box())),
RenderCommand::PushClipLayer(l) => clips.push(l.transform.transform_rect_bbox(l.clip.bounding_box())),
RenderCommand::PopLayer => drop(clips.pop()),
RenderCommand::Fill(f) => out.push((f.brush.clone(), f.transform.transform_rect_bbox(f.shape.bounding_box()), clips.clone())),
_ => {}
}
}
out
}
fn rgb(p: &Paint) -> Option<[u8; 3]> {
match p {
Paint::Solid(c) => {
let c = c.to_rgba8();
(c.a > 0).then_some([c.r, c.g, c.b])
}
_ => None,
}
}
/// What of `color` is drawn: the fills in it, each cut by its clips (None when a clip leaves none of it).
fn drawn(scene: &Scene, color: [u8; 3]) -> Vec<Rect> {
fills(scene)
.into_iter()
.filter(|(p, ..)| rgb(p) == Some(color))
.filter_map(|(_, r, clips)| {
let cut = clips.iter().fold(r, |a, c| a.intersect(*c));
(cut.width() > 0.0 && cut.height() > 0.0).then_some(cut)
})
.collect()
}
/// raea #250: `clip-path: inset(0 0 0 100%)` clips the element away (it drew whole); 99% leaves a sliver
#[test]
fn a_clip_path_inset_that_clips_everything_draws_nothing() {
let page = |inset: &str| {
format!(
r#"<body style="margin:0;background:#fff"><div style="padding:40px"><div style="position:relative;width:400px;height:300px;background:#0f0">
<div style="position:absolute;inset:0;background:#f00;clip-path:inset({inset})"></div></div></div></body>"#
)
};
for inset in ["0 0 0 100%", "100% 0 0 0", "0 60% 0 50%", "0 0 0 120%"] {
let s = painted(&page(inset), 700, 400);
assert_eq!(drawn(&s, [255, 0, 0]), vec![], "inset({inset}) drew red");
assert_eq!(drawn(&s, [0, 255, 0]).len(), 1, "inset({inset}) lost the green box");
}
let sliver = drawn(&painted(&page("0 0 0 99%"), 700, 400), [255, 0, 0]);
assert_eq!(sliver.len(), 1);
assert!((sliver[0].width() - 4.0).abs() < 0.01 && (sliver[0].height() - 300.0).abs() < 0.01, "{sliver:?}");
}
/// raea #251: an <svg> with `overflow: visible` draws past its viewport (a 1x1 svg drew nothing); without it, the
/// UA sheet still clips it to its box, as Chrome does
#[test]
fn an_svg_with_overflow_visible_draws_past_its_viewport() {
let page = |overflow: &str| {
format!(
r##"<body style="margin:0;background:#fff"><svg xmlns="http://www.w3.org/2000/svg" style="position:absolute;left:0;top:0;{overflow}" width="1" height="1">
<circle cx="200" cy="200" r="80" fill="#ff6600"/><polygon points="0,-40 32,24 -28,20" transform="translate(400 200) rotate(30)" fill="#3366ff"/></svg></body>"##
)
};
let s = painted(&page("overflow:visible"), 700, 400);
let circle = drawn(&s, [255, 102, 0]);
assert_eq!(circle.len(), 1, "the circle: {circle:?}");
assert!(circle[0].contains(Point::new(200.0, 200.0)) && circle[0].width() > 150.0, "{circle:?}");
let triangle = drawn(&s, [51, 102, 255]);
assert!(triangle.len() == 1 && triangle[0].contains(Point::new(400.0, 200.0)), "the triangle: {triangle:?}");
// the UA's clip, and an author's overflow: hidden, keep it in its 1x1 box
for overflow in ["", "overflow:hidden"] {
let s = painted(&page(overflow), 700, 400);
assert_eq!(drawn(&s, [255, 102, 0]), vec![], "{overflow:?} drew the circle past the box");
}
}
/// raea #248: a background-image on an inline element is drawn on each of its line fragments (it drew nothing, its
/// background-color did), laid out across the fragments side by side, so `background-size: 10% 100%` covers part of the
/// first line's fragment and nothing of the others'
#[test]
fn an_inline_elements_background_image_fills_its_line_fragments() {
let page = |size: &str| {
format!(
r#"<body style="margin:0;background:#fff"><div style="padding:40px;font-size:40px;line-height:50px"><div style="width:300px">Before <span id="m" style="background-image:linear-gradient(#FFD43B, #FFD43B);background-repeat:no-repeat;background-size:{size}">this marked phrase wraps over lines</span> after.</div></div></body>"#
)
};
let gradients = |s: &Scene| -> Vec<Rect> {
fills(s)
.into_iter()
.filter(|(p, ..)| matches!(p, Paint::Gradient(_)))
.filter_map(|(_, r, clips)| {
let cut = clips.iter().fold(r, |a, c| a.intersect(*c));
(cut.width() > 1.0 && cut.height() > 1.0).then_some(cut)
})
.collect()
};
let full = gradients(&painted(&page("100% 100%"), 700, 400));
assert!(full.len() >= 2, "a fill on each line's fragment: {full:?}");
let mut tops: Vec<i64> = full.iter().map(|r| r.y0.round() as i64).collect();
tops.dedup();
assert!(tops.len() >= 2, "on more than one line: {full:?}");
// 10% of the fragments side by side: on the first line alone
let half = gradients(&painted(&page("10% 100%"), 700, 400));
assert!(!half.is_empty() && half.iter().all(|r| r.y0 < full.iter().map(|f| f.y0).fold(f64::MAX, f64::min) + 1.0), "{half:?} vs {full:?}");
}
+4
View File
@@ -55,6 +55,7 @@ raea-core-ask = "core"
raea-sys-k = "systems"
raea-sys-mix = "systems"
raea-sys-mix-level = "systems"
raea-sys-mix-device = "systems"
raea-sys-tone = "systems"
raea-seedling = "systems"
raea-sys-ml = "systems"
@@ -168,6 +169,7 @@ raea-runtime-twins = "runtime"
raea-runtime-dom = "runtime"
raea-runtime-dom-media = "runtime"
raea-runtime-edit = "runtime"
raea-runtime-goal-plan = "runtime"
raea-runtime-input = "runtime"
raea-runtime-bake = "runtime"
raea-runtime-bundle = "runtime"
@@ -294,6 +296,8 @@ raea-sys-rt = true
raea-sys-mix = true
# the mix before the master: dialogue at one level, room tone at the joins (the mix masters what it gives)
raea-sys-mix-level = true
# the mixer's output: the device stream live play runs in, followed when the system's output changes
raea-sys-mix-device = true
raea-sys-tone = true
raea-sys-ml = true
raea-sys-mlx = true
+14 -1
View File
@@ -43,11 +43,18 @@ function Hello() {
}
registerRoot(() => <Composition id="hello" component={Hello} width={640} height={360} fps={30} durationInFrames={30} />);
TSX
# RAEA_CHECK_NO_GPU=1 leaves out what draws (these renders, styles.gen's and the app checks): the Windows on ARM build's
# runner has no GPU it can draw on (WARP crashes in Bevy's compute shaders, and Mesa's lavapipe has no ARM64 build), so
# there the archive's other checks run, and a Snapdragon PC draws (#82)
nogpu=${RAEA_CHECK_NO_GPU:-}
[ -z "$nogpu" ] || echo "release: RAEA_CHECK_NO_GPU=1: nothing is drawn here (renders, styles.gen, app checks)"
if [ -z "$nogpu" ]; then
(cd "$check/p" && RAEA_NO_TREE=1 RUST_BACKTRACE=1 "$raea" render hello.tsx --frame 12 -o hello.png > render.log 2>&1) || { s=$?; tail -40 "$check/p/render.log" >&2; fail "the unpacked raea didn't render (exit $s)"; }
[ -s "$check/p/hello.png" ] || fail "no frame written"
# hello.tsx draws white text on black, so a frame raea finds all black lost its page (Windows' c:\ paths read as a URL
# scheme drew nothing but the black behind it, 11-05)
! grep -q "is all black" "$check/p/render.log" || { grep "all black" "$check/p/render.log" >&2; fail "the unpacked raea rendered a black frame"; }
fi
# a 3D frame too, Bevy's camera, lights and a mesh: on Linux every 3D render panicked in a build whose Engines each made
# an event loop (#182), while the page above rendered. On black, so a 3D pass that drew nothing is all black; on Linux
# once more with no display at all, as a render needs none. Not on Windows, whose runners have only WARP
@@ -107,6 +114,7 @@ TS
(cd "$check/plugins" && RAEA_NO_TREE=1 "$raea" run check.ts > run.log 2>&1; grep -q "plugins: avian and the virtual gamepad" run.log) || { tail -20 "$check/plugins/run.log" >&2; fail "the unpacked raea has no plugin catalog (build raea with --features \"\$(tools/bevy-plugins.sh features sdk/raea/bench/bevy-plugins)\")"; }
# and its guides and styles.gen come from the release too
(cd "$check/p" && RAEA_NO_TREE=1 "$raea" guide music | grep -q "music") || fail "the unpacked raea has no craft guides"
if [ -z "$nogpu" ]; then
mkdir -p "$check/styled" && { echo 'import { css } from "./styles.gen";'; cat "$check/p/hello.tsx"; echo 'void css;'; } > "$check/styled/hello.tsx"
(cd "$check/styled" && RAEA_NO_TREE=1 "$raea" render hello.tsx --frame 1 -o hello.png > render.log 2>&1 && [ -s styles.gen.ts ]) \
|| { tail -20 "$check/styled/render.log" >&2; fail "the unpacked raea didn't write styles.gen.ts"; }
@@ -141,6 +149,7 @@ for t in web native; do
done
grep -q "unsigned" "$check/app/native.log" || { tail -5 "$check/app/native.log" >&2; fail "the native film's report doesn't say it's unsigned"; }
! grep -qa c2pa "$check/app/native.mp4" || fail "the public engine's native film carries Content Credentials"
fi
# raea song on every platform (#43): the raea-perceive beside raea maps a 12 s drum loop at 120 BPM (perl writes it:
# every runner has perl, Git's bash too) with the beat model the release ships, copied into a models folder of the
# check's own (HOME, and LOCALAPPDATA on Windows)
@@ -214,5 +223,9 @@ if [ "${RAEA_CHECK_HARD:-}" = 1 ]; then
[ -s "$hard/a/out.mp4" ] && [ -s "$hard/b/out.mp4" ] || fail "two renders at once didn't both write their MP4"
echo "release: the hard pass too: a folder with a space and letters outside ASCII, 3D on this GPU, $n runs of one render, two at once"
fi
echo "release: $archive checked: an unpacked copy rendered a frame and checked an app on both targets with RAEA_NO_TREE=1"
if [ -n "$nogpu" ]; then
echo "release: $archive checked without a GPU: an unpacked copy ran its plugins, guides and song map with RAEA_NO_TREE=1; nothing was drawn"
else
echo "release: $archive checked: an unpacked copy rendered a frame and checked an app on both targets with RAEA_NO_TREE=1"
fi
rm -rf "$check"
+9 -7
View File
@@ -1,5 +1,5 @@
#!/bin/bash
# A release of the raea engine for macOS on Apple Silicon, Linux on x86_64 or Windows on x86_64 (whichever machine runs
# A release of the raea engine for macOS on Apple Silicon, Linux on x86_64 or Windows on x86_64 or ARM64 (whichever machine runs
# it; .github/workflows/release.yml builds all three on GitHub's runners for a tag, Windows in Git's bash): raea and
# its bundler, with raea's own files beside them (share/raea: the raea SDK's TypeScript, the lite runtime and its
# packages, the shell's sources, the tools that install the local music and foley models, and the agent skills), laid
@@ -24,7 +24,7 @@
# tools/cpu-heartbeat.sh (a line while rustc's CPU grows) and keep `--stall 25m`; a raised stall would only wait longer
# on a real hang.
#
# Writes dist/raea-VERSION-macos-arm64.tar.gz (-linux-x86_64.tar.gz, or -windows-x86_64.zip) and its .sha256, then
# Writes dist/raea-VERSION-macos-arm64.tar.gz (-linux-x86_64.tar.gz, -windows-x86_64.zip or -windows-arm64.zip) and its .sha256, then
# checks the archive with tools/release-check.sh: unpacked into a fresh folder, its raea renders a frame with
# RAEA_NO_TREE=1 (so it can't be reading this checkout), has the plugin catalog, names none of raea's API and holds
# nothing key-shaped (on Windows, no Microsoft file). Nothing is published.
@@ -37,7 +37,9 @@ cd "$root"
out=$root/dist
case $(uname -s) in
Linux) platform=linux-x86_64 ;;
MINGW*|MSYS*|CYGWIN*) platform=windows-x86_64 ;;
# RAEA_WIN_ARCH=arm64: the Windows on ARM build (#82), whose bin\ tools/release/onnxruntime.sh and win-bundle.sh fill
# with the same variable; Git's bash on that runner may be x64 itself, so uname -m can't say
MINGW*|MSYS*|CYGWIN*) [ "${RAEA_WIN_ARCH:-x64}" = arm64 ] && platform=windows-arm64 || platform=windows-x86_64 ;;
*) platform=macos-arm64 ;;
esac
name=raea-$version-$platform
@@ -52,7 +54,7 @@ untar() {
local err rc=0
err=$(tar -x -C "$1" 2>&1 >/dev/null) || rc=$?
[ $rc -eq 0 ] && return 0
if [ "$platform" = windows-x86_64 ] && ! grep -v -e "Cannot create symlink" -e "Exiting with failure status" <<< "$err" | grep -q .; then
if [ "${platform%%-*}" = windows ] && ! grep -v -e "Cannot create symlink" -e "Exiting with failure status" <<< "$err" | grep -q .; then
echo "release.sh: note: the skills gate left out $(grep -c "Cannot create symlink" <<< "$err") symlinks (Windows makes none)"
return 0
fi
@@ -129,7 +131,7 @@ Install a CJK font for Japanese, Chinese and Korean text (Debian and Ubuntu: apt
An app's window, on either target (raea app run, raea-rune-host and raea-page-host), needs a display (X11 or
Wayland; Xvfb on a server, as raea app check does there too), libxkbcommon-x11, the X client libraries and the Vulkan
loader (Debian and Ubuntu: apt install libxkbcommon-x11-0 libxcursor1 libxi6 libxrandr2 libx11-xcb1 libvulkan1)." > "$stage/README" ;;
windows-x86_64)
windows-*)
cp "$bin/raea.exe" "$bin/raea_bundle.dll" "$bin/raea-perceive.exe" "$bin/raea-rune-host.exe" "$bin/raea-page-host.exe" "$stage/bin/"
# ONNX Runtime as Microsoft builds it (MIT), which raea.exe and raea-perceive.exe load when a model first runs (#110),
# with its licence and notices; tools/release/onnxruntime.sh put them beside the build
@@ -144,7 +146,7 @@ loader (Debian and Ubuntu: apt install libxkbcommon-x11-0 libxcursor1 libxi6 lib
[ -f "$bin/$f" ] || { echo "release.sh: $bin has no $f (tools/release/win-bundle.sh $bin)" >&2; exit 1; }
cp "$bin/$f" "$stage/bin/"
done
printf '%s\r\n' "raea $version for Windows x86_64 (Windows 10 or 11, a DirectX 12 or Vulkan GPU driver; with no GPU, Mesa's lavapipe and WGPU_BACKEND=vulkan)." \
printf '%s\r\n' "raea $version for Windows ${platform#windows-} (Windows 10 or 11, a DirectX 12 or Vulkan GPU driver; with no GPU, Mesa's lavapipe and WGPU_BACKEND=vulkan)." \
"bin\\ carries what raea needs from outside it: Microsoft's Visual C++ runtime, ONNX Runtime and DXC, FFmpeg (LGPL) and uv," \
"each with its licence beside it (ffmpeg-README.txt says where FFmpeg's source is)." > "$stage/README.txt" ;;
*) cp "$bin/raea" "$bin/libraea_bundle.dylib" "$bin/raea-perceive" "$bin/raea-rune-host" "$bin/raea-page-host" "$stage/bin/"
@@ -205,7 +207,7 @@ printf '%s\n' "$version" > "$stage/share/raea/VERSION"
for md in "$stage"/share/raea/skills/*/SKILL.md; do
perl -0pi -e 's/\A---\n(.*?)\n---\n/"---\n" . join("\n", grep { !\/^version:\/ } split(\/\n\/, $1)) . "\nversion: '"$version"'\n---\n"/se' "$md"
done
if [ $platform = windows-x86_64 ]; then
if [ "${platform%%-*}" = windows ]; then
# RAEA_WIN_SIGN=1: raea's own programs signed before they're zipped (tools/release/win-sign.sh, #221). Off, the zip is
# as it was: unsigned, which Smart App Control blocks on a PC that has it on
if [ "${RAEA_WIN_SIGN:-}" = 1 ]; then
+6 -3
View File
@@ -7,10 +7,13 @@
# CPU without AVX2 and BMI2 (an Ivy Bridge, a Celeron), whatever was asked of it. Microsoft's runtime picks its kernels
# by the CPU it finds; it loads and opens raea's models under Intel's emulator as an Ivy Bridge and a Sandy Bridge.
# 1.28.0 is the runtime the static build was (ort-sys 2.0.0-rc.13's [email protected]); ort asks for API 17 or newer.
# RAEA_WIN_ARCH=arm64 takes the package's win-arm64 runtime instead, for raea's Windows on ARM build (#82).
# tools/release/onnxruntime.sh DEST
set -euo pipefail
die() { echo "onnxruntime: $*" >&2; exit 1; }
dest=${1:?DEST}
arch=${RAEA_WIN_ARCH:-x64}
case $arch in x64|arm64) ;; *) die "RAEA_WIN_ARCH is $arch: x64 or arm64" ;; esac
v=1.28.0
# the package's sha256; its sha512 is the one NuGet records for it (packageHash)
sum=769d1d3ea8ab6cd69f737c9dd4d4462aa4ad0ccfa106eaf506efc40d7bead5db
@@ -20,9 +23,9 @@ trap 'rm -rf "$tmp"' EXIT
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 30 -o "$tmp/ort.nupkg" "$url" || die "couldn't download $url"
got=$( (sha256sum "$tmp/ort.nupkg" 2>/dev/null || shasum -a 256 "$tmp/ort.nupkg") | cut -d' ' -f1)
[ "$got" = "$sum" ] || die "Microsoft.ML.OnnxRuntime $v is $got, not the $sum pinned here"
unzip -q -o "$tmp/ort.nupkg" runtimes/win-x64/native/onnxruntime.dll LICENSE ThirdPartyNotices.txt -d "$tmp/x"
unzip -q -o "$tmp/ort.nupkg" runtimes/win-$arch/native/onnxruntime.dll LICENSE ThirdPartyNotices.txt -d "$tmp/x"
mkdir -p "$dest"
cp "$tmp/x/runtimes/win-x64/native/onnxruntime.dll" "$dest/onnxruntime.dll"
cp "$tmp/x/runtimes/win-$arch/native/onnxruntime.dll" "$dest/onnxruntime.dll"
cp "$tmp/x/LICENSE" "$dest/onnxruntime-LICENSE.txt"
cp "$tmp/x/ThirdPartyNotices.txt" "$dest/onnxruntime-ThirdPartyNotices.txt"
echo "onnxruntime: Microsoft.ML.OnnxRuntime $v's onnxruntime.dll ($(wc -c < "$dest/onnxruntime.dll" | tr -d ' ') bytes) and its notices in $dest"
echo "onnxruntime: Microsoft.ML.OnnxRuntime $v's win-$arch onnxruntime.dll ($(wc -c < "$dest/onnxruntime.dll" | tr -d ' ') bytes) and its notices in $dest"
+5 -2
View File
@@ -18,9 +18,12 @@ die() { echo "promoted-from: $*" >&2; exit 1; }
# tests include tools/release.sh and an sdk/guides page, and tests aren't in a release build). The skills (skills/, the
# raea-skills pin) and docs/ are read by no build either (11-11, Shane: "promote skills to the latest possible"):
# release.sh packs the skills the release's commit pins, and the skills gate (its skills-passed line) and check-cli
# hold them to the candidate's binaries, so newer skills go out on a candidate's binaries
# hold them to the candidate's binaries, so newer skills go out on a candidate's binaries. The layers gate's files
# (tools/layers.sh and its layers.toml) are read by CI's check of the crate graph only (11-26: 0.1.11-rc2's commit failed
# CI on a crate with no layer, and the one-line fix would have forced a rebuild)
SAME=(':(exclude)README.md' ':(exclude).github' ':(exclude)tools/release.sh' ':(exclude)tools/release-check.sh' ':(exclude)tools/release-appimage.sh'
':(exclude)tools/release' ':(exclude)tools/agents' ':(exclude)tools/raea-app' ':(exclude)skills' ':(exclude)docs')
':(exclude)tools/release' ':(exclude)tools/agents' ':(exclude)tools/raea-app' ':(exclude)skills' ':(exclude)docs'
':(exclude)tools/layers.sh' ':(exclude)tools/layers.toml' ':(exclude)tools/layers.allow')
fetch_tag() { git cat-file -e "refs/tags/$1" 2>/dev/null || git fetch -q --depth=1 origin "refs/tags/$1:refs/tags/$1"; }
differ() { git diff --name-only "$1^{commit}" "$2^{commit}" -- . "${SAME[@]}"; }
+18 -10
View File
@@ -13,11 +13,19 @@
# three licences: wgpu compiles DX12's shaders with it when it sits beside raea.exe, else with the old FXC, which cost
# 6 to 13 s of hitches at start and as new 3D appeared on every PC DX12 is chosen for: Intel, AMD and Arc (#215; the
# chat page 17.7 s with FXC, 12.0 s with DXC on the test PC)
# The pins are setup.rs's, so what ships and what's fetched are the same build.
# The pins are setup.rs's, so what ships and what's fetched are the same build. RAEA_WIN_ARCH=arm64 (raea's Windows on
# ARM build, #82) takes the ARM64 runtime, uv and DXC; FFmpeg stays x64, which Windows on ARM runs emulated in its own
# process, as setup.rs fetches it there.
# tools/release/win-bundle.sh DEST (on the Windows runner, in Git's bash)
set -euo pipefail
die() { echo "win-bundle: $*" >&2; exit 1; }
dest=${1:?DEST}
arch=${RAEA_WIN_ARCH:-x64}
case $arch in
x64) vc=x86.x64 uvt=x86_64-pc-windows-msvc ;;
arm64) vc=ARM64 uvt=aarch64-pc-windows-msvc ;;
*) die "RAEA_WIN_ARCH is $arch: x64 or arm64" ;;
esac
root=$(cd "$(dirname "$0")/../.." && pwd)
setup=$root/io/assets/src/setup.rs
const() { sed -n "s/^const $1: &str = \"\\(.*\\)\";$/\\1/p" "$setup"; }
@@ -30,10 +38,10 @@ mkdir -p "$dest"
# the VC++ runtime, from the newest Visual Studio with the C++ tools
vswhere="/c/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe"
[ -x "$vswhere" ] || die "no vswhere at $vswhere: the C runtime comes from the runner's Visual Studio"
vs=$(cygpath -u "$("$vswhere" -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath | tr -d '\r')")
vs=$(cygpath -u "$("$vswhere" -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.$vc -property installationPath | tr -d '\r')")
ver=$(tr -d '\r\n ' < "$vs/VC/Auxiliary/Build/Microsoft.VCRedistVersion.default.txt")
crt=$(ls -d "$vs/VC/Redist/MSVC/$ver/x64"/Microsoft.VC14*.CRT 2>/dev/null | tail -1)
[ -n "$crt" ] || die "no Microsoft.VC14*.CRT under $vs/VC/Redist/MSVC/$ver/x64"
crt=$(ls -d "$vs/VC/Redist/MSVC/$ver/$arch"/Microsoft.VC14*.CRT 2>/dev/null | tail -1)
[ -n "$crt" ] || die "no Microsoft.VC14*.CRT under $vs/VC/Redist/MSVC/$ver/$arch"
for f in vcruntime140.dll vcruntime140_1.dll msvcp140.dll msvcp140_1.dll; do
[ -f "$crt/$f" ] || die "$crt has no $f"
cp "$crt/$f" "$dest/$f"
@@ -55,18 +63,18 @@ cp "$tmp/ff/$top/libvpx-PATENTS" "$dest/libvpx-PATENTS.txt"
# uv, and its licences from its source at the same tag
uv=$(const UV)
uvsum=$(sed -n 's/^ *("x86_64-pc-windows-msvc", "\([0-9a-f]*\)"),$/\1/p' "$setup")
[ -n "$uv" ] && [ -n "$uvsum" ] || die "no UV and its x86_64-pc-windows-msvc sha256 in $setup"
fetch "https://github.com/astral-sh/uv/releases/download/$uv/uv-x86_64-pc-windows-msvc.zip" "$tmp/uv.zip" "$uvsum"
uvsum=$(sed -n 's/^ *("'"$uvt"'", "\([0-9a-f]*\)"),$/\1/p' "$setup")
[ -n "$uv" ] && [ -n "$uvsum" ] || die "no UV and its $uvt sha256 in $setup"
fetch "https://github.com/astral-sh/uv/releases/download/$uv/uv-$uvt.zip" "$tmp/uv.zip" "$uvsum"
unzip -q -o "$tmp/uv.zip" uv.exe -d "$dest"
[ "$uv" = 0.12.24 ] || die "uv is $uv: pin its LICENSE-MIT and LICENSE-APACHE here for that tag"
fetch "https://raw.githubusercontent.com/astral-sh/uv/$uv/LICENSE-MIT" "$dest/uv-LICENSE-MIT.txt" 860e3d7a86b84e6a7012c7a635fc64df475cebc6cce34dfeb73a5982ec58176c
fetch "https://raw.githubusercontent.com/astral-sh/uv/$uv/LICENSE-APACHE" "$dest/uv-LICENSE-APACHE.txt" c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4
# DXC: Microsoft's distributable dxcompiler.dll and dxil.dll (LICENSE-MS.txt), the x64 ones, and the release's licences
# DXC: Microsoft's distributable dxcompiler.dll and dxil.dll (LICENSE-MS.txt), the architecture's, and the release's licences
dxc=v1.8.2502
fetch "https://github.com/microsoft/DirectXShaderCompiler/releases/download/$dxc/dxc_2025_02_20.zip" "$tmp/dxc.zip" 70b1913a1bfce4a3e1a5311d16246f4ecdf3a3e613abec8aa529e57668426f85
unzip -q -o -j "$tmp/dxc.zip" bin/x64/dxcompiler.dll bin/x64/dxil.dll -d "$dest"
unzip -q -o -j "$tmp/dxc.zip" bin/$arch/dxcompiler.dll bin/$arch/dxil.dll -d "$dest"
for l in MS LLVM MIT; do unzip -p "$tmp/dxc.zip" "LICENSE-$l.txt" > "$dest/dxc-LICENSE-$l.txt"; done
echo "win-bundle: in $dest: the VC++ runtime $ver, FFmpeg ($top), uv $uv, DXC $dxc, with their licences"
echo "win-bundle: in $dest ($arch): the VC++ runtime $ver, FFmpeg ($top), uv $uv, DXC $dxc, with their licences"
+6
View File
@@ -11,6 +11,12 @@
svg|*:not(svg|svg), svg|*:not(svg|foreignObject) > svg|svg {
transform-origin: 0 0;
}
/* raea: Chrome's svg.css clips an inner <svg> to its viewport (`svg:not(:root) { overflow: hidden }`), which
* `overflow: visible` lifts (raea #251). `clip` rather than `hidden`, so an svg is no scroll container and lays out
* as it did (a flex item keeps its automatic minimum size); blitz-paint's draw_svg reads it */
svg|svg:not(:root) {
overflow: clip;
}
@font-face {
font-family: -moz-bullet-font;
+2 -1
View File
@@ -13,7 +13,8 @@ use style::{
};
/// Query fontique for the fonts matching `font_styles` (family list and attributes).
fn query_for_font_styles<'a>(
/// raea: small_caps.rs asks it for the face it checks for `smcp` (#249)
pub(crate) fn query_for_font_styles<'a>(
font_ctx: &'a mut FontContext,
font_styles: &'a FontStyles,
) -> parley::fontique::Query<'a> {
+60 -2
View File
@@ -573,7 +573,9 @@ fn collect_layout_children_with_wrap(
}
DisplayInside::Table => {
let (table_context, tlayout_children) = build_table_context(doc, container_node_id);
let wrapped = wrap_table_strays(doc, container_node_id, out);
let (table_context, tlayout_children) =
build_table_context(doc, container_node_id, wrapped);
#[allow(clippy::arc_with_non_send_sync)]
let data = SpecialElementData::TableRoot(Arc::new(table_context));
doc.nodes[container_node_id]
@@ -802,6 +804,49 @@ fn flush_pseudo_elements(doc: &mut BaseDocument, node_id: NodeId) {
}
}
/// raea: a table's children with each run of children that are no table box (text, a block or inline element, a
/// table inside it) wrapped in an anonymous block, which table.rs lays out as an anonymous row holding one anonymous
/// cell (css-tables-3 § 3.3, as Chrome does). Blitz dropped them, so a `display: table` element around its text (a
/// shrink-wrapped line) drew nothing, not even its background (#254). None when there is no such run (no text but
/// whitespace), so a table of rows builds no anonymous block. The blocks are `out`'s to free on reconstruction.
fn wrap_table_strays(
doc: &mut BaseDocument,
table_id: NodeId,
out: &mut LayoutChildren,
) -> Option<Vec<NodeId>> {
fn is_stray(node: &Node) -> bool {
match node.data.kind() {
NodeKind::Text => true,
NodeKind::Element => node.primary_styles().is_some_and(|style| {
let display = style.clone_display();
matches!(display.outside(), DisplayOutside::Block | DisplayOutside::Inline)
&& display.inside() != DisplayInside::Contents
&& !style.clone_position().is_absolutely_positioned()
}),
_ => false,
}
}
let children = doc.nodes[table_id].children.clone();
let any = children.iter().any(|&id| {
let node = &doc.nodes[id];
is_stray(node) && !node.is_whitespace_node()
});
if !any {
return None;
}
let mut runs = LayoutChildren::default();
for id in children {
match doc.nodes[id].data.kind() {
NodeKind::Comment => {}
_ if is_stray(&doc.nodes[id]) => runs.push_wrapped(table_id, id, doc),
_ => runs.push(id, doc),
}
}
runs.maybe_push_anon_block(doc);
out.anonymous_blocks.extend(runs.anonymous_blocks.iter().copied());
Some(runs.children.into_iter().collect())
}
/// Handles the cases where there are text nodes or inline nodes that need to be wrapped in an anonymous block node
fn collect_complex_layout_children(
doc: &mut BaseDocument,
@@ -1085,6 +1130,10 @@ pub(crate) fn build_inline_layout_into(
..Default::default()
});
// raea: which of its elements' text gets synthesised small capitals, asked of the fonts before the builder holds
// them (#249)
let small_caps = super::small_caps::synthesized(nodes, inline_context_root_node_id, font_ctx);
// Create a parley tree builder
let mut builder = layout_ctx.tree_builder(font_ctx, scale, true, &parley_style);
if let Some(style) = root_node_style.as_deref() {
@@ -1124,6 +1173,7 @@ pub(crate) fn build_inline_layout_into(
};
// The marker is a separate box, so words in the content don't continue from it.
let mut text_transformer = TextTransformer::default();
text_transformer.small_caps = small_caps;
text_transformer.word_break(&builder);
// raea: the root's bidi override around its content (stylo_to_parley::bidi_controls)
@@ -1395,10 +1445,18 @@ pub(crate) fn build_inline_layout_into(
s.clone_white_space_collapse() != stylo_to_parley::stylo::WhiteSpaceCollapse::Collapse
});
let bidi = if keeps_newlines { std::mem::take(&mut text_transformer.bidi) } else { Vec::new() };
// raea: the font size its synthesised small capitals scale, when they're its parent's (#249)
let small_caps = node
.parent
.filter(|p| text_transformer.small_caps.contains(p))
.and_then(|p| nodes[p].primary_styles().map(|s| s.get_font().font_size.used_size.0.px()));
let text =
text_transformer.transform(&data.content, parent_text_transform, builder);
let start = builder.text().len();
builder.push_text(&bidi_newlines(text, &bidi));
match small_caps {
Some(font_size) => super::small_caps::push(builder, &bidi_newlines(text, &bidi), font_size),
None => builder.push_text(&bidi_newlines(text, &bidi)),
}
text_transformer.texts.push((node_id, start, builder.text().len()));
if keeps_newlines {
text_transformer.bidi = bidi;
+2
View File
@@ -28,6 +28,8 @@ pub(crate) mod inline;
pub(crate) mod list;
pub(crate) mod paint_tree;
pub(crate) mod replaced;
// raea: synthesised small capitals (#249)
pub(crate) mod small_caps;
pub(crate) mod table;
pub(crate) mod text_transform;
#[cfg(feature = "writing-mode")]
+143
View File
@@ -0,0 +1,143 @@
//! raea: `font-variant: small-caps` as Chrome draws it (#249). A face with an `smcp` feature gets it
//! (stylo_to_parley::font_variant_caps); for a face without one (Georgia, Times, Helvetica: most system faces) Chrome
//! synthesises the small capitals, each lower-case letter drawn as its capital at 70% of the font size (Blink's
//! kSmallCapsFontSizeMultiplier). Blitz only asked for the feature, so such text drew in normal case, with no warning.
use std::cell::RefCell;
use std::collections::HashMap;
use blitz_traits::node_id::NodeId;
use parley::fontique::{QueryFont, QueryStatus};
use parley::{FontContext, StyleProperty, TreeBuilder};
use skrifa::MetadataProvider as _;
use skrifa::raw::TableProvider as _;
use style::properties::style_structs::Font as FontStyles;
use crate::font_metrics::query_for_font_styles;
use crate::node::TextBrush;
use crate::stylo_to_parley::stylo::FontVariantCaps;
/// The size of a synthesised small capital, as a fraction of the font size (Blink's)
pub(crate) const SCALE: f32 = 0.7;
thread_local! {
/// whether a face (its blob's id and index in it) has an `smcp` feature, read once
static SMCP: RefCell<HashMap<(u64, u32), bool>> = RefCell::new(HashMap::new());
}
/// The elements whose text under `root` (an inline layout's root) is drawn in synthesised small capitals: each text
/// node's parent (its DOM parent, which an anonymous block wrapping the text isn't) whose font-variant-caps is
/// small-caps, in a face whose lower-case letters have no `smcp` feature.
pub(crate) fn synthesized(nodes: &crate::NodeTree, root: NodeId, fcx: &mut FontContext) -> Vec<NodeId> {
let mut out = Vec::new();
let mut stack = vec![root];
while let Some(id) = stack.pop() {
let node = &nodes[id];
if node.is_text_node() {
let Some(parent) = node.parent.filter(|p| !out.contains(p)) else { continue };
let Some(style) = nodes[parent].primary_styles() else { continue };
let font = style.get_font();
if font.font_variant_caps == FontVariantCaps::SmallCaps && !has_smcp(fcx, font) {
out.push(parent);
}
continue;
}
stack.extend(node.children.iter().copied());
stack.extend(node.before());
stack.extend(node.after());
}
out
}
/// Whether the face `font` draws a lower-case `a` in has an `smcp` feature (true when no face has the letter: then
/// there is nothing to synthesise).
fn has_smcp(fcx: &mut FontContext, font: &FontStyles) -> bool {
let mut query = query_for_font_styles(fcx, font);
let mut face = None;
query.matches_with(|q: &QueryFont| {
let maps = skrifa::FontRef::from_index(q.blob.as_ref(), q.index).is_ok_and(|f| f.charmap().map('a').is_some());
if !maps {
return QueryStatus::Continue;
}
face = Some((q.blob.clone(), q.index));
QueryStatus::Stop
});
let Some((blob, index)) = face else { return true };
SMCP.with(|seen| *seen.borrow_mut().entry((blob.id(), index)).or_insert_with(|| has_feature(blob.as_ref(), index, b"smcp")))
}
/// Whether the face at `index` in `data` lists the GSUB feature `tag`.
pub(crate) fn has_feature(data: &[u8], index: u32, tag: &[u8; 4]) -> bool {
let tag = skrifa::Tag::new(tag);
let Ok(font) = skrifa::FontRef::from_index(data, index) else { return false };
let Ok(list) = font.gsub().and_then(|gsub| gsub.feature_list()) else { return false };
list.feature_records().iter().any(|record| record.feature_tag() == tag)
}
/// A lower-case letter a synthesised small capital replaces: one with a capital of its own.
fn is_small(c: char) -> bool {
c.is_lowercase() && !c.to_uppercase().eq(std::iter::once(c))
}
/// `text` pushed with each run of lower-case letters as their capitals at SCALE of `font_size` (px), the rest as it is.
pub(crate) fn push(builder: &mut TreeBuilder<TextBrush>, text: &str, font_size: f32) {
let mut rest = text;
while let Some(first) = rest.chars().next() {
let small = is_small(first);
let end = rest.char_indices().find(|&(_, c)| is_small(c) != small).map_or(rest.len(), |(i, _)| i);
let (run, tail) = rest.split_at(end);
if small {
builder.push_style_modification_span(&[StyleProperty::FontSize(font_size * SCALE)]);
builder.push_text(&run.to_uppercase());
builder.pop_style_span();
} else {
builder.push_text(run);
}
rest = tail;
}
}
#[cfg(test)]
mod tests {
use super::*;
use parley::{LayoutContext, TextStyle};
/// Each glyph run's text and font size, for `text` pushed as small capitals at 40 px.
fn runs(text: &str) -> Vec<(String, f32)> {
let mut font_ctx = FontContext::new();
let mut layout_ctx: LayoutContext<TextBrush> = LayoutContext::new();
let style = TextStyle { font_size: 40.0, ..TextStyle::default() };
let mut builder = layout_ctx.tree_builder(&mut font_ctx, 1.0, true, &style);
push(&mut builder, text, 40.0);
let mut layout = parley::Layout::new();
let built = builder.build_into(&mut layout);
layout.break_all_lines(None);
let mut out = Vec::new();
for line in layout.lines() {
for item in line.items() {
if let parley::PositionedLayoutItem::GlyphRun(run) = item {
out.push((built[run.run().text_range()].to_string(), run.run().font_size()));
}
}
}
out
}
#[test]
fn lower_case_letters_are_capitals_at_70_percent() {
let want = [("C", 40.0), ("OMPLIANCE", 28.0), (" A", 40.0), ("UDIT", 28.0)];
let want: Vec<(String, f32)> = want.iter().map(|(t, s)| (t.to_string(), *s)).collect();
assert_eq!(runs("Compliance Audit"), want);
}
#[test]
fn capitals_digits_and_spaces_keep_their_size() {
assert_eq!(runs("A1 B"), vec![("A1 B".to_string(), 40.0)]);
}
#[test]
fn a_letter_without_a_capital_of_its_own_keeps_its_size() {
// U+0138 kra is lower-case and has no capital
assert!(!is_small('ĸ') && is_small('a') && !is_small('A') && !is_small('1'));
}
}
+19 -4
View File
@@ -208,9 +208,12 @@ fn percent_plus_length(
dim.into()
}
/// raea: `wrapped` is the table's children with each run of children that are no table box (its text, a block or
/// an inline element) in an anonymous block (construct.rs `wrap_table_strays`, #254); None when it has no such run
pub(crate) fn build_table_context(
doc: &mut BaseDocument,
table_root_node_id: NodeId,
wrapped: Option<Vec<NodeId>>,
) -> (TableContext, Vec<NodeId>) {
let mut cells: Vec<TableCell> = Vec::new();
let mut oof_children: Vec<(NodeId, taffy::Position)> = Vec::new();
@@ -221,7 +224,8 @@ pub(crate) fn build_table_context(
let wm = table_wm(doc, table_root_node_id);
let root_node = &mut doc.nodes[table_root_node_id];
let children = std::mem::take(&mut root_node.children);
let dom_children = std::mem::take(&mut root_node.children);
let children = wrapped.unwrap_or_else(|| dom_children.to_vec());
let Some(stylo_styles) = root_node.primary_styles() else {
panic!("Ignoring table because it has no styles");
@@ -469,7 +473,7 @@ pub(crate) fn build_table_context(
.chain(oof_children.iter().map(|(node_id, _)| *node_id))
.collect();
let root_node = &mut doc.nodes[table_root_node_id];
root_node.children = children;
root_node.children = dom_children;
(
TableContext {
@@ -582,7 +586,9 @@ fn collect_table_cells(
) {
let node = &mut doc.nodes[node_id];
if !node.is_element() {
// raea: an anonymous block here is one construct.rs wrapped a run of the table's stray children in (#254)
let anonymous = node.is_anonymous();
if !node.is_element() && !anonymous {
return;
}
@@ -605,7 +611,16 @@ fn collect_table_cells(
return;
}
match display.inside() {
// raea: it is an anonymous row holding one anonymous cell, as css-tables-3 § 3.3 wraps such a run (#254)
let inside = if anonymous {
*row += 1;
cursor.start_row();
rows.push(TableRow { node_id, group: None, height: None, is_constrained: false });
DisplayInside::TableCell
} else {
display.inside()
};
match inside {
DisplayInside::TableRowGroup
| DisplayInside::TableHeaderGroup
| DisplayInside::TableFooterGroup
+2
View File
@@ -117,6 +117,8 @@ pub(crate) struct TextTransformer {
pub(crate) bidi: Vec<(&'static str, &'static str)>,
/// raea: each text node's bytes in the builder's text, as pushed (TextLayout::text_nodes)
pub(crate) texts: Vec<(blitz_traits::node_id::NodeId, usize, usize)>,
/// raea: the elements whose own text is drawn in synthesised small capitals (layout/small_caps.rs, #249)
pub(crate) small_caps: Vec<blitz_traits::node_id::NodeId>,
}
impl TextTransformer {
+52 -5
View File
@@ -585,13 +585,27 @@ impl NetHandler for ResourceHandler<ImageHandler> {
/// cards ask theirs at the card's size (raea-feed src/feed/media.ts): a 2560x1440 still held 14.7 MB decoded on a card
/// drawn 1440 pixels wide at most, 4.7 MB fitted (raea-feed e2e/memory.spec.ts). Area-averaged (`thumbnail`), on
/// premultiplied pixels when any is see-through, so no edge takes the colour of the transparent pixels beside it.
pub fn fit(url: &str, w: u32, h: u32, mut rgba: Vec<u8>) -> (u32, u32, Vec<u8>) {
///
/// And one larger than the GPU's largest texture on either side (`set_max_image_side`, the side of Vello's image
/// atlas) is scaled down to fit it, its shape kept: Vello can only draw an image that fits its atlas, and a full-page
/// site capture (1080x18000) drawn 880 wide was refused outright (raea#245). Chrome draws it; here it's drawn from a
/// copy at most the atlas's side tall, which a page never draws larger than its own size anyway.
pub fn fit(url: &str, w: u32, h: u32, rgba: Vec<u8>) -> (u32, u32, Vec<u8>) {
fit_within(url, w, h, rgba, MAX_IMAGE_SIDE.load(std::sync::atomic::Ordering::Relaxed))
}
fn fit_within(url: &str, w: u32, h: u32, mut rgba: Vec<u8>, side: u32) -> (u32, u32, Vec<u8>) {
let query = url.split('#').next().and_then(|u| u.split_once('?')).map_or("", |(_, q)| q);
let want = |k: &str| query.split('&').find_map(|kv| kv.strip_prefix(k)?.strip_prefix('=')?.parse::<u32>().ok()).filter(|n| *n > 0);
let scale = [want("raea-w").map(|n| n as f64 / w.max(1) as f64), want("raea-h").map(|n| n as f64 / h.max(1) as f64)]
.into_iter()
.flatten()
.fold(1.0f64, f64::min);
let side = side.max(1) as f64;
let scale = [
want("raea-w").map(|n| n as f64 / w.max(1) as f64),
want("raea-h").map(|n| n as f64 / h.max(1) as f64),
(w.max(h) as f64 > side).then(|| side / w.max(h) as f64),
]
.into_iter()
.flatten()
.fold(1.0f64, f64::min);
if scale >= 1.0 || w == 0 || h == 0 || rgba.len() != w as usize * h as usize * 4 {
return (w, h, rgba);
}
@@ -620,6 +634,17 @@ pub fn fit(url: &str, w: u32, h: u32, mut rgba: Vec<u8>) -> (u32, u32, Vec<u8>)
(nw, nh, out)
}
/// raea: the longest side a decoded image keeps (`fit`): Vello's image atlas's side (the GPU's largest texture, 16384 at most).
/// 16384 until the page's renderer says (systems/page draw.rs, from the device's `max_texture_dimension_2d`)
static MAX_IMAGE_SIDE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(16384);
/// raea: the longest side an image is decoded at, from here on (the device's largest texture)
pub fn set_max_image_side(px: u32) {
if px > 0 {
MAX_IMAGE_SIDE.store(px, std::sync::atomic::Ordering::Relaxed);
}
}
impl ImageHandler {
fn parse(&self, bytes: Bytes, url: &str) -> Result<Resource, String> {
if let Some((width, height, rgba)) = IMAGE_DECODER.get().and_then(|d| d(url, &bytes)) {
@@ -728,3 +753,25 @@ mod tests {
);
}
}
#[cfg(test)]
mod fit_tests {
use super::fit_within;
// raea#245: a picture taller than the GPU's largest texture is decoded at a size that fits it, its shape kept
#[test]
fn an_image_past_the_atlas_side_is_fitted_to_it() {
let (w, h) = (54, 900);
let (nw, nh, px) = fit_within("tall.png", w, h, vec![200; (w * h * 4) as usize], 819);
assert_eq!((nw, nh), (49, 819));
assert_eq!(px.len(), (nw * nh * 4) as usize);
assert!(px.iter().all(|&c| c == 200));
}
#[test]
fn an_image_inside_it_is_left_alone_and_a_url_s_size_still_wins() {
let (w, h) = (54, 800);
assert_eq!(fit_within("a.png", w, h, vec![0; (w * h * 4) as usize], 819).0, 54);
assert_eq!(fit_within("a.png?raea-h=400", w, h, vec![0; (w * h * 4) as usize], 819).1, 400);
}
}
+36 -2
View File
@@ -882,13 +882,15 @@ impl<'dom, 'a> BlitzDomPainter<'dom, 'a> {
// The root element's overflow is propagated to the viewport (which is clipped by the
// window/surface bounds), so the root element must not clip its own overflow.
let is_root_element = self.root_element_id == Some(node_id);
// raea: an inline <svg>'s overflow clip is drawn by draw_svg, and only when its drawing spills past its
// viewport: the UA sheet's `overflow: clip` on every svg would otherwise be a clip layer for every icon (#251)
let is_inline_svg = node.element_data().is_some_and(|e| &*e.name.local == "svg" && matches!(e.image_data(), Some(blitz_dom::node::ImageData::Svg(_))));
let should_clip = !is_root_element
&& (is_image
|| is_sub_doc
|| is_text_input
|| contain_paint
|| !matches!(overflow_x, Overflow::Visible)
|| !matches!(overflow_y, Overflow::Visible));
|| (!is_inline_svg && (!matches!(overflow_x, Overflow::Visible) || !matches!(overflow_y, Overflow::Visible))));
// Apply padding/border offset to inline root
let taffy::Layout {
@@ -1167,6 +1169,11 @@ impl<'dom, 'a> BlitzDomPainter<'dom, 'a> {
// Compute clip-path (if any) and wrap all rendering in a clip layer
let clip_path_shape = cx.clip_path_shape();
// raea: a clip-path with no area (an inset that clips everything, a circle(0)) hides the element and all it
// draws, its shadows and outline included, as `clip: rect()` of no area does below (raea #250)
if clip_path_shape.as_ref().is_some_and(|(p, _)| p.bounding_box().is_zero_area()) {
return;
}
let has_clip_path = clip_path_shape.is_some();
let clip_fill = clip_path_shape.as_ref().map_or(peniko::Fill::NonZero, |s| s.1);
let default_clip = cx.frame.border_box_path();
@@ -1865,12 +1872,30 @@ impl ElementCx<'_, '_> {
(pos.y - text_layout.block_offset as f64 - (layout.padding.top + layout.border.top) as f64) * self.scale,
))
* Affine::scale(self.scale);
// raea: an inline element's background images (#248), drawn by an ElementCx whose box is `at` (its
// fragments side by side, in CSS px from the root's border box), with its own borders and padding (an
// inline box has no Taffy layout of its own; a percentage padding is of the root's content width)
let content_width = CSSPixelLength::new(layout.content_box_width());
let images = |scene: &mut _, id: NodeId, at: Rect| {
let Some(node) = self.context.dom.get_node(id) else { return };
let Some(st) = node.primary_styles() else { return };
let (b, p) = (st.get_border(), st.get_padding());
let pad = |v: &style::values::computed::NonNegativeLengthPercentage| v.0.resolve(content_width).px();
let mut l = taffy::Layout::new();
l.size = taffy::Size { width: at.width() as f32, height: at.height() as f32 };
l.border = taffy::Rect { left: b.border_left_width.0.to_f32_px(), right: b.border_right_width.0.to_f32_px(), top: b.border_top_width.0.to_f32_px(), bottom: b.border_bottom_width.0.to_f32_px() };
l.padding = taffy::Rect { left: pad(&p.padding_left), right: pad(&p.padding_right), top: pad(&p.padding_top), bottom: pad(&p.padding_bottom) };
// the box's corner at device scale: border_box is in CSS px, an ElementCx's transform in device px
let t = border_box * Affine::translate((at.x0, at.y0)) * Affine::scale(1.0 / self.scale);
self.context.element_cx(node, l, t, None).draw_inline_background_images(scene);
};
crate::text::draw_inline_backgrounds(
scene,
text_layout.layout.lines(),
self.context.dom,
border_box,
self.node.id,
images,
);
// Render text selection highlight (if any) using cached selection ranges
@@ -2372,6 +2397,15 @@ impl ElementCx<'_, '_> {
let b = tree.root().abs_stroke_bounding_box();
let (sw, sh) = (svg_size.width(), svg_size.height());
let spills = b.left() < -0.01 || b.top() < -0.01 || b.right() > sw + 0.01 || b.bottom() > sh + 0.01;
// raea: an inline <svg>'s clip is its `overflow` (the UA sheet's `svg|svg:not(:root) { overflow: clip }`), so
// `overflow: visible` draws what reaches past its viewport, as Chrome does: a 1x1 svg drawing particles in page
// coordinates drew nothing (raea #251). An SVG image (<img>) is always clipped to its box.
let b = self.style.get_box();
let clips = !inline || !matches!(b.overflow_x, Overflow::Visible) || !matches!(b.overflow_y, Overflow::Visible);
if spills && !clips {
anyrender_svg::render_svg_tree_in(scene, &tree, transform, host, in_css);
return;
}
if spills {
self.context.layer_manager.maybe_with_layer(scene, true, 1.0, self.transform, &self.frame.content_box_path(), None, None, |scene| {
anyrender_svg::render_svg_tree_in(scene, &tree, transform, host, in_css);
+41 -23
View File
@@ -137,7 +137,6 @@ impl<'a> ImageLayerStyles<'a> {
impl ElementCx<'_, '_> {
pub(super) fn draw_background(&self, scene: &mut impl PaintScene) {
let bg_styles = &self.style.get_background();
let image_data = &self.element.background_images;
let layer_count = bg_styles.background_image.0.len();
// The background color is clipped by the clip of the last layer in the list
@@ -156,28 +155,7 @@ impl ElementCx<'_, '_> {
self.context.layer_manager.maybe_with_blend_layer(scene, isolated, 1.0, Some(peniko::Mix::Normal.into()), self.transform, &bounds, None, None, |scene| {
// Draw background color (if any)
self.draw_solid_bg(scene, &background_clip_path);
for idx in (0..layer_count).rev() {
let layer = ImageLayerStyles::from_background(bg_styles, image_data, idx);
if layer_paints_nothing(&layer) {
continue;
}
let background_clip_path = self.box_path(layer.clip);
self.context.layer_manager.maybe_with_blend_layer(
scene,
true,
1.0,
blends[idx],
self.transform,
&background_clip_path,
None,
None,
|scene| {
self.draw_image_layer(scene, &layer);
},
);
}
self.draw_background_layers(scene, &blends);
if text {
let dest_in = peniko::BlendMode::new(peniko::Mix::Normal, peniko::Compose::DestIn);
self.context.layer_manager.maybe_with_blend_layer(scene, true, 1.0, Some(dest_in), self.transform, &bounds, None, None, |scene| self.draw_text_mask(scene));
@@ -185,6 +163,46 @@ impl ElementCx<'_, '_> {
});
}
/// The background's image layers, bottom first, each in its clip and blended by `blends` (draw_background's)
fn draw_background_layers(&self, scene: &mut impl PaintScene, blends: &[Option<peniko::BlendMode>]) {
let bg_styles = &self.style.get_background();
let image_data = &self.element.background_images;
for idx in (0..bg_styles.background_image.0.len()).rev() {
let layer = ImageLayerStyles::from_background(bg_styles, image_data, idx);
if layer_paints_nothing(&layer) {
continue;
}
let background_clip_path = self.box_path(layer.clip);
self.context.layer_manager.maybe_with_blend_layer(
scene,
true,
1.0,
blends.get(idx).copied().flatten(),
self.transform,
&background_clip_path,
None,
None,
|scene| {
self.draw_image_layer(scene, &layer);
},
);
}
}
/// raea: an inline element's background images on one of its fragments (text.rs draw_inline_backgrounds, raea
/// #248), its frame the box its fragments make side by side: the layers alone, as the fragments' colour, borders
/// and clip are text.rs's; in a group of their own when a layer blends (blended with each other, not its colour)
pub(super) fn draw_inline_background_images(&self, scene: &mut impl PaintScene) {
let n = self.style.get_background().background_image.0.len();
let blends: Vec<_> = (0..n).map(|i| crate::blend::background_blend(&self.style, i)).collect();
let bounds = self.frame.border_box_path().bounding_box();
let isolated = blends.iter().any(Option::is_some);
self.context.layer_manager.maybe_with_blend_layer(scene, isolated, 1.0, Some(peniko::Mix::Normal.into()), self.transform, &bounds, None, None, |scene| {
self.draw_background_layers(scene, &blends);
});
}
/// The path of the given CSS box model box for this element
pub(super) fn box_path(&self, css_box: BoxModelBox) -> crate::kurbo_css::BoxShape {
match css_box {
+3 -1
View File
@@ -174,8 +174,10 @@ impl ElementCx<'_, '_> {
let x1 = ox + w - right;
let y1 = oy + h - bottom;
// raea: an inset that meets or crosses itself clips everything (an empty clip region), not nothing:
// None meant no clip-path, so `inset(0 0 0 100%)` drew the whole element (raea #250)
if x1 <= x0 || y1 <= y0 {
return None;
return Some(BezPath::new());
}
// TODO: Support border-radius on inset()
+18 -3
View File
@@ -115,12 +115,18 @@ fn snap_glyph(x: f32, y: f32, at: Affine) -> (f32, f32) {
///
/// The inline root's own background is painted separately (as a normal block box). `transform` is the root's
/// border box at device scale.
pub(crate) fn draw_inline_backgrounds<'a>(
scene: &mut impl PaintScene,
///
/// raea: its background images too (raea #248: a highlighter's `linear-gradient` on a phrase drew nothing, its colour
/// alone did), by `images` (the element, and the box they're laid out in, in the root's CSS px): each fragment clipped
/// to itself from one box as wide as all its fragments side by side, as Chrome's `box-decoration-break: slice` lays a
/// background out, so a `background-size` of 0% to 100% sweeps across the lines in turn.
pub(crate) fn draw_inline_backgrounds<'a, S: PaintScene>(
scene: &mut S,
lines: impl Iterator<Item = Line<'a, TextBrush>>,
doc: &BaseDocument,
transform: Affine,
inline_root_id: NodeId,
mut images: impl FnMut(&mut S, NodeId, Rect),
) {
let mut seen: Vec<(usize, NodeId)> = Vec::new();
let mut add = |mut id: NodeId| {
@@ -169,12 +175,15 @@ pub(crate) fn draw_inline_backgrounds<'a>(
side(&border.border_bottom_width, &border.border_bottom_color, border.border_bottom_style),
side(&border.border_left_width, &border.border_left_color, border.border_left_style),
];
if bg == Color::TRANSPARENT && [top, right, bottom, left].iter().all(Option::is_none) {
let has_images = styles.get_background().background_image.0.iter().any(|i| !matches!(i, style::values::generics::image::GenericImage::None));
if bg == Color::TRANSPARENT && !has_images && [top, right, bottom, left].iter().all(Option::is_none) {
continue;
}
let Some(frags) = node.inline_fragment_boxes() else { continue };
let frags: Vec<_> = frags.collect();
let n = frags.len();
let slices = frags.iter().map(|f| (f.right - f.left) as f64).sum::<f64>();
let mut before = 0.0;
for (i, f) in frags.into_iter().enumerate() {
let r = Rect::new(f.left as f64, f.top as f64, f.right as f64, f.bottom as f64);
let (first, last) = (i == 0, i + 1 == n);
@@ -196,6 +205,12 @@ pub(crate) fn draw_inline_backgrounds<'a>(
if bg != Color::TRANSPARENT {
scene.fill(Fill::NonZero, transform, bg, None, &shape);
}
if has_images {
scene.push_clip_layer(Fill::NonZero, transform, &shape);
images(scene, id, Rect::new(r.x0 - before, r.y0, r.x0 - before + slices, r.y1));
scene.pop_layer();
}
before += r.width();
if rounded {
scene.push_clip_layer(Fill::NonZero, transform, &shape);
}
+67
View File
@@ -0,0 +1,67 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
name = "metis-sys"
version = "0.3.2"
authors = [
"Hubert Hirtz <[email protected]>",
"Cedric Chevalier <[email protected]>",
]
build = "build.rs"
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Raw FFI to METIS, the serial graph partitioner and fill-reducing matrix orderer"
readme = "README.md"
keywords = [
"graph",
"mesh",
"matrix",
"partitioning",
"ordering",
]
categories = [
"external-ffi-bindings",
"mathematics",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/LIHPC-Computational-Geometry/metis-rs"
[lib]
name = "metis_sys"
path = "src/lib.rs"
[build-dependencies.bindgen]
version = "0.69"
features = ["runtime"]
optional = true
default-features = false
[build-dependencies.cc]
version = "1"
features = ["parallel"]
optional = true
[features]
default = [
"vendored",
"force-optimize-vendor",
]
force-optimize-vendor = ["vendored"]
generate-bindings = [
"vendored",
"bindgen",
]
use-system = ["bindgen"]
vendored = ["dep:cc"]
+70
View File
@@ -0,0 +1,70 @@
# metis-rs
**metis-rs** is a Rust library providing idiomatic bindings to [libmetis][METIS_GH], a library for graph and mesh
partitioning. It is made to be used with Rust version 1.67.0 or above.
## Getting Started
Library released on [crates.io](https://crates.io/crates/metis). To use it, add the following to your `Cargo.toml`:
```toml
[dependencies]
metis = "0.2"
```
The list of available versions and a change log are available in the [CHANGELOG.md](CHANGELOG.md) file.
## Features
### Use of Vendored Feature
The `vendored` feature enables metis-rs to build METIS from source and link to it statically. If not enabled, metis-rs
looks for an existing installation and links to it dynamically.
### Use of System-wide Feature
The `use-system` feature enables metis-rs to use the system-wide installation of METIS. If not enabled, metis-rs will
refer to its own version of METIS.
Please note, `vendored` and `use-system` features are mutually exclusive.
## Guidance for non-standard METIS installations
If you enabled the `use-system` feature and METIS is installed in a non-standard location, you must set the following
environment variables:
```bash
export METISDIR=path/to/your/metis/installation
export CPATH="$METISDIR/include"
export RUSTFLAGS="-L$METISDIR/lib"
```
`$METISDIR` must point to a directory containing both `lib/` and `include/` directories with METIS's shared libraries and headers, respectively.
## Building the documentation
To build the documentation, especially if METIS is installed in a non-standard location, set the `RUSTDOCFLAGS` environment variable:
```bash
export RUSTDOCFLAGS="-L$METISDIR/lib"
```
Then the following command will generate and open the documentation:
```bash
cargo doc --no-deps --open
```
## License
> [!IMPORTANT]
> Our licensing policy applies only to the rust crate `metis-rs`, not the original METIS library.
>
> For information about METIS' licensing policy, refer to the original library's [repository][METIS_GH].
metis-rs is distributed under the terms of both the MIT license and the Apache License (Version 2.0). Refer to `LICENSE-APACHE` and `LICENSE-MIT` for more details.
### Note on the `vendored` feature
metis-rs comes with its `vendored` feature enabled by default. With this feature enabled, the original METIS code is compiled and is installed along metis-rs.
Please note that METIS code is **always** under Apache-2 license.
[METIS]: http://glaros.dtc.umn.edu/gkhome/metis/metis/overview
[METIS_GH]: https://github.com/KarypisLab/METIS
+213
View File
@@ -0,0 +1,213 @@
#[cfg(all(not(feature = "vendored"), not(feature = "use-system")))]
compile_error!(r#"either "use-system" or "vendored" must be enabled for `metis-sys`"#);
#[cfg(feature = "vendored")]
const IDX_SIZE: usize = 32;
#[cfg(feature = "vendored")]
const REAL_SIZE: usize = 32;
#[cfg(feature = "vendored")]
fn build_lib() {
use std::env;
use std::path::PathBuf;
let vendor = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("vendor");
println!("cargo:rerun-if-changed={}", vendor.display());
let mut build = cc::Build::new();
build
.define("IDXTYPEWIDTH", Some(IDX_SIZE.to_string().as_str()))
.define("REALTYPEWIDTH", Some(REAL_SIZE.to_string().as_str()))
.include(vendor.join("metis/include"));
fn add_sources(build: &mut cc::Build, root: PathBuf, files: &[&str]) {
build.files(files.iter().map(|src| root.join(src)));
build.include(root);
}
add_sources(
&mut build,
vendor.join("metis/libmetis"),
&[
"auxapi.c",
"balance.c",
"bucketsort.c",
"checkgraph.c",
"coarsen.c",
"compress.c",
"contig.c",
"debug.c",
"fm.c",
"fortran.c",
"frename.c",
"gklib.c",
"graph.c",
"initpart.c",
"kmetis.c",
"kwayfm.c",
"kwayrefine.c",
"mcutil.c",
"mesh.c",
"meshpart.c",
"minconn.c",
"mincover.c",
"mmd.c",
"ometis.c",
"options.c",
"parmetis.c",
"pmetis.c",
"refine.c",
"separator.c",
"sfm.c",
"srefine.c",
"stat.c",
"timing.c",
"util.c",
"wspace.c",
],
);
add_sources(
&mut build,
vendor.join("GKlib"),
&[
"b64.c",
"blas.c",
"cache.c",
"csr.c",
"error.c",
"evaluate.c",
"fkvkselect.c",
"fs.c",
"getopt.c",
"gk_util.c",
"gkregex.c",
"graph.c",
"htable.c",
"io.c",
"itemsets.c",
"mcore.c",
"memory.c",
"pqueue.c",
"random.c",
"rw.c",
"seq.c",
"sort.c",
"string.c",
"timers.c",
"tokenizer.c",
],
);
let target = env::var("TARGET").unwrap();
if target.contains("windows") {
add_sources(&mut build, vendor.join("GKlib/win32"), &["adapt.c"]);
build
.define("USE_GKREGEX", None)
.define("WIN32", None)
.define("__thread", Some("__declspec(thread)"));
if target.contains("msvc") {
build
.define("MSC", None)
.define("_CRT_SECURE_NO_WARNINGS", None);
// force inclusion of math.h to make sure INFINITY is defined before gk_arch.h is parsed
build.flag("/FImath.h");
}
} else if target.contains("linux") {
build
.define("LINUX", None)
.define("_FILE_OFFSET_BITS", Some("64"));
} else if target.contains("apple") {
build.define("MACOS", None);
}
#[cfg(any(not(debug_assertions), feature = "force-optimize-vendor"))]
build.define("NDEBUG", None).define("NDEBUG2", None);
// METIS triggers an infinite amount of warnings and showing them to users
// downstream does not really help.
build.warnings(false);
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let lib_dir = out_dir.join("lib");
build.out_dir(&lib_dir);
build.compile("metis");
println!("cargo:rustc-link-search=native={}", lib_dir.display());
println!("cargo:rustc-link-lib=static=metis");
println!("cargo:lib={}", lib_dir.display());
println!("cargo:out={}", out_dir.display());
}
#[cfg(not(feature = "vendored"))]
fn build_lib() {
println!("cargo:rustc-link-lib=metis");
}
// Always generate bindings when running from a locally installed METIS library.
// When building directly from source (feature = "vendored"), only regenerate
// bindings on command (feature = "generate-bindings").
#[cfg(all(
feature = "use-system",
any(not(feature = "vendored"), feature = "generate-bindings")
))]
fn generate_bindings() {
use std::env;
use std::path::PathBuf;
#[cfg(feature = "vendored")]
let builder = bindgen::builder()
.clang_arg(format!("-DIDXTYPEWIDTH={}", IDX_SIZE))
.clang_arg(format!("-DREALTYPEWIDTH={}", REAL_SIZE))
.header("../vendor/metis/include/metis.h");
#[cfg(not(feature = "vendored"))]
let builder = bindgen::builder().header("wrapper.h");
println!("cargo:rerun-if-changed=wrapper.h");
let bindings = builder
.allowlist_function("METIS_.*")
.allowlist_type("idx_t")
.allowlist_type("real_t")
.allowlist_type("rstatus_et")
.allowlist_type("m.*_et")
.allowlist_var("METIS_.*")
.generate()
.unwrap_or_else(|err| {
eprintln!("Failed to generate bindings to METIS: {err}");
std::process::exit(1);
});
let out_path = if cfg!(feature = "vendored") {
PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).join("gen/bindings.rs")
} else {
PathBuf::from(env::var("OUT_DIR").unwrap()).join("bindings.rs")
};
bindings.write_to_file(&out_path).unwrap_or_else(|err| {
eprintln!(
"Failed to write METIS bindings to {:?}: {}",
out_path.display(),
err,
);
std::process::exit(1);
});
}
#[cfg(not(all(
feature = "use-system",
any(not(feature = "vendored"), feature = "generate-bindings")
)))]
fn generate_bindings() {}
fn main() {
build_lib();
generate_bindings();
}
+257
View File
@@ -0,0 +1,257 @@
/* automatically generated by rust-bindgen 0.66.1 */
pub const METIS_VER_MAJOR: u32 = 5;
pub const METIS_VER_MINOR: u32 = 2;
pub const METIS_VER_SUBMINOR: u32 = 1;
pub const METIS_NOPTIONS: u32 = 40;
pub type idx_t = i32;
pub type real_t = f32;
extern "C" {
pub fn METIS_PartGraphRecursive(
nvtxs: *mut idx_t,
ncon: *mut idx_t,
xadj: *mut idx_t,
adjncy: *mut idx_t,
vwgt: *mut idx_t,
vsize: *mut idx_t,
adjwgt: *mut idx_t,
nparts: *mut idx_t,
tpwgts: *mut real_t,
ubvec: *mut real_t,
options: *mut idx_t,
edgecut: *mut idx_t,
part: *mut idx_t,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn METIS_PartGraphKway(
nvtxs: *mut idx_t,
ncon: *mut idx_t,
xadj: *mut idx_t,
adjncy: *mut idx_t,
vwgt: *mut idx_t,
vsize: *mut idx_t,
adjwgt: *mut idx_t,
nparts: *mut idx_t,
tpwgts: *mut real_t,
ubvec: *mut real_t,
options: *mut idx_t,
edgecut: *mut idx_t,
part: *mut idx_t,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn METIS_MeshToDual(
ne: *mut idx_t,
nn: *mut idx_t,
eptr: *mut idx_t,
eind: *mut idx_t,
ncommon: *mut idx_t,
numflag: *mut idx_t,
r_xadj: *mut *mut idx_t,
r_adjncy: *mut *mut idx_t,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn METIS_MeshToNodal(
ne: *mut idx_t,
nn: *mut idx_t,
eptr: *mut idx_t,
eind: *mut idx_t,
numflag: *mut idx_t,
r_xadj: *mut *mut idx_t,
r_adjncy: *mut *mut idx_t,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn METIS_PartMeshNodal(
ne: *mut idx_t,
nn: *mut idx_t,
eptr: *mut idx_t,
eind: *mut idx_t,
vwgt: *mut idx_t,
vsize: *mut idx_t,
nparts: *mut idx_t,
tpwgts: *mut real_t,
options: *mut idx_t,
objval: *mut idx_t,
epart: *mut idx_t,
npart: *mut idx_t,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn METIS_PartMeshDual(
ne: *mut idx_t,
nn: *mut idx_t,
eptr: *mut idx_t,
eind: *mut idx_t,
vwgt: *mut idx_t,
vsize: *mut idx_t,
ncommon: *mut idx_t,
nparts: *mut idx_t,
tpwgts: *mut real_t,
options: *mut idx_t,
objval: *mut idx_t,
epart: *mut idx_t,
npart: *mut idx_t,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn METIS_NodeND(
nvtxs: *mut idx_t,
xadj: *mut idx_t,
adjncy: *mut idx_t,
vwgt: *mut idx_t,
options: *mut idx_t,
perm: *mut idx_t,
iperm: *mut idx_t,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn METIS_Free(ptr: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn METIS_SetDefaultOptions(options: *mut idx_t) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn METIS_NodeNDP(
nvtxs: idx_t,
xadj: *mut idx_t,
adjncy: *mut idx_t,
vwgt: *mut idx_t,
npes: idx_t,
options: *mut idx_t,
perm: *mut idx_t,
iperm: *mut idx_t,
sizes: *mut idx_t,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn METIS_ComputeVertexSeparator(
nvtxs: *mut idx_t,
xadj: *mut idx_t,
adjncy: *mut idx_t,
vwgt: *mut idx_t,
options: *mut idx_t,
sepsize: *mut idx_t,
part: *mut idx_t,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn METIS_NodeRefine(
nvtxs: idx_t,
xadj: *mut idx_t,
vwgt: *mut idx_t,
adjncy: *mut idx_t,
where_: *mut idx_t,
hmarker: *mut idx_t,
ubfactor: real_t,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn METIS_CacheFriendlyReordering(
nvtxs: idx_t,
xadj: *mut idx_t,
adjncy: *mut idx_t,
part: *mut idx_t,
old2new: *mut idx_t,
) -> ::std::os::raw::c_int;
}
#[doc = "< Returned normally"]
pub const rstatus_et_METIS_OK: rstatus_et = 1;
#[doc = "< Returned due to erroneous inputs and/or options"]
pub const rstatus_et_METIS_ERROR_INPUT: rstatus_et = -2;
#[doc = "< Returned due to insufficient memory"]
pub const rstatus_et_METIS_ERROR_MEMORY: rstatus_et = -3;
#[doc = "< Some other errors"]
pub const rstatus_et_METIS_ERROR: rstatus_et = -4;
#[doc = " Return codes"]
pub type rstatus_et = ::std::os::raw::c_int;
pub const moptype_et_METIS_OP_PMETIS: moptype_et = 0;
pub const moptype_et_METIS_OP_KMETIS: moptype_et = 1;
pub const moptype_et_METIS_OP_OMETIS: moptype_et = 2;
#[doc = " Operation type codes"]
pub type moptype_et = ::std::os::raw::c_int;
pub const moptions_et_METIS_OPTION_PTYPE: moptions_et = 0;
pub const moptions_et_METIS_OPTION_OBJTYPE: moptions_et = 1;
pub const moptions_et_METIS_OPTION_CTYPE: moptions_et = 2;
pub const moptions_et_METIS_OPTION_IPTYPE: moptions_et = 3;
pub const moptions_et_METIS_OPTION_RTYPE: moptions_et = 4;
pub const moptions_et_METIS_OPTION_DBGLVL: moptions_et = 5;
pub const moptions_et_METIS_OPTION_NIPARTS: moptions_et = 6;
pub const moptions_et_METIS_OPTION_NITER: moptions_et = 7;
pub const moptions_et_METIS_OPTION_NCUTS: moptions_et = 8;
pub const moptions_et_METIS_OPTION_SEED: moptions_et = 9;
pub const moptions_et_METIS_OPTION_ONDISK: moptions_et = 10;
pub const moptions_et_METIS_OPTION_MINCONN: moptions_et = 11;
pub const moptions_et_METIS_OPTION_CONTIG: moptions_et = 12;
pub const moptions_et_METIS_OPTION_COMPRESS: moptions_et = 13;
pub const moptions_et_METIS_OPTION_CCORDER: moptions_et = 14;
pub const moptions_et_METIS_OPTION_PFACTOR: moptions_et = 15;
pub const moptions_et_METIS_OPTION_NSEPS: moptions_et = 16;
pub const moptions_et_METIS_OPTION_UFACTOR: moptions_et = 17;
pub const moptions_et_METIS_OPTION_NUMBERING: moptions_et = 18;
pub const moptions_et_METIS_OPTION_DROPEDGES: moptions_et = 19;
pub const moptions_et_METIS_OPTION_NO2HOP: moptions_et = 20;
pub const moptions_et_METIS_OPTION_TWOHOP: moptions_et = 21;
pub const moptions_et_METIS_OPTION_FAST: moptions_et = 22;
pub const moptions_et_METIS_OPTION_HELP: moptions_et = 23;
pub const moptions_et_METIS_OPTION_TPWGTS: moptions_et = 24;
pub const moptions_et_METIS_OPTION_NCOMMON: moptions_et = 25;
pub const moptions_et_METIS_OPTION_NOOUTPUT: moptions_et = 26;
pub const moptions_et_METIS_OPTION_BALANCE: moptions_et = 27;
pub const moptions_et_METIS_OPTION_GTYPE: moptions_et = 28;
pub const moptions_et_METIS_OPTION_UBVEC: moptions_et = 29;
#[doc = " Options codes (i.e., options[])"]
pub type moptions_et = ::std::os::raw::c_int;
pub const mptype_et_METIS_PTYPE_RB: mptype_et = 0;
pub const mptype_et_METIS_PTYPE_KWAY: mptype_et = 1;
#[doc = " Partitioning Schemes"]
pub type mptype_et = ::std::os::raw::c_int;
pub const mgtype_et_METIS_GTYPE_DUAL: mgtype_et = 0;
pub const mgtype_et_METIS_GTYPE_NODAL: mgtype_et = 1;
#[doc = " Graph types for meshes"]
pub type mgtype_et = ::std::os::raw::c_int;
pub const mctype_et_METIS_CTYPE_RM: mctype_et = 0;
pub const mctype_et_METIS_CTYPE_SHEM: mctype_et = 1;
#[doc = " Coarsening Schemes"]
pub type mctype_et = ::std::os::raw::c_int;
pub const miptype_et_METIS_IPTYPE_GROW: miptype_et = 0;
pub const miptype_et_METIS_IPTYPE_RANDOM: miptype_et = 1;
pub const miptype_et_METIS_IPTYPE_EDGE: miptype_et = 2;
pub const miptype_et_METIS_IPTYPE_NODE: miptype_et = 3;
pub const miptype_et_METIS_IPTYPE_METISRB: miptype_et = 4;
#[doc = " Initial partitioning schemes"]
pub type miptype_et = ::std::os::raw::c_int;
pub const mrtype_et_METIS_RTYPE_FM: mrtype_et = 0;
pub const mrtype_et_METIS_RTYPE_GREEDY: mrtype_et = 1;
pub const mrtype_et_METIS_RTYPE_SEP2SIDED: mrtype_et = 2;
pub const mrtype_et_METIS_RTYPE_SEP1SIDED: mrtype_et = 3;
#[doc = " Refinement schemes"]
pub type mrtype_et = ::std::os::raw::c_int;
#[doc = "< Shows various diagnostic messages"]
pub const mdbglvl_et_METIS_DBG_INFO: mdbglvl_et = 1;
#[doc = "< Perform timing analysis"]
pub const mdbglvl_et_METIS_DBG_TIME: mdbglvl_et = 2;
#[doc = "< Show the coarsening progress"]
pub const mdbglvl_et_METIS_DBG_COARSEN: mdbglvl_et = 4;
#[doc = "< Show the refinement progress"]
pub const mdbglvl_et_METIS_DBG_REFINE: mdbglvl_et = 8;
#[doc = "< Show info on initial partitioning"]
pub const mdbglvl_et_METIS_DBG_IPART: mdbglvl_et = 16;
#[doc = "< Show info on vertex moves during refinement"]
pub const mdbglvl_et_METIS_DBG_MOVEINFO: mdbglvl_et = 32;
#[doc = "< Show info on vertex moves during sep refinement"]
pub const mdbglvl_et_METIS_DBG_SEPINFO: mdbglvl_et = 64;
#[doc = "< Show info on minimization of subdomain connectivity"]
pub const mdbglvl_et_METIS_DBG_CONNINFO: mdbglvl_et = 128;
#[doc = "< Show info on elimination of connected components"]
pub const mdbglvl_et_METIS_DBG_CONTIGINFO: mdbglvl_et = 256;
#[doc = "< Show info related to wspace allocation"]
pub const mdbglvl_et_METIS_DBG_MEMORY: mdbglvl_et = 2048;
#[doc = " Debug Levels"]
pub type mdbglvl_et = ::std::os::raw::c_int;
pub const mobjtype_et_METIS_OBJTYPE_CUT: mobjtype_et = 0;
pub const mobjtype_et_METIS_OBJTYPE_VOL: mobjtype_et = 1;
pub const mobjtype_et_METIS_OBJTYPE_NODE: mobjtype_et = 2;
pub type mobjtype_et = ::std::os::raw::c_int;
+9
View File
@@ -0,0 +1,9 @@
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#[cfg(not(feature = "vendored"))]
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
#[cfg(feature = "vendored")]
include!("../gen/bindings.rs");
+57
View File
@@ -0,0 +1,57 @@
# Prerequisites
*.d
# Object files
*.o
*.ko
*.obj
*.elf
# Linker output
*.ilk
*.map
*.exp
# Precompiled Headers
*.gch
*.pch
# Libraries
*.lib
*.a
*.la
*.lo
# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib
# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
# Debug files
*.dSYM/
*.su
*.idb
*.pdb
# Kernel Module Compile Results
*.mod*
*.cmd
.tmp_versions/
modules.order
Module.symvers
Mkfile.old
dkms.conf
# GK things
build/
lib/
.svn/
+31
View File
@@ -0,0 +1,31 @@
cmake_minimum_required(VERSION 2.8)
project(GKlib C)
option(BUILD_SHARED_LIBS "Build shared libraries (.dll/.so) instead of static ones (.lib/.a)" OFF)
get_filename_component(abs "." ABSOLUTE)
set(GKLIB_PATH ${abs})
unset(abs)
include(GKlibSystem.cmake)
include_directories(".")
if(MSVC)
include_directories("win32")
file(GLOB win32_sources RELATIVE "win32" "*.c")
else(MSVC)
set(win32_sources, "")
endif(MSVC)
add_library(GKlib ${GKlib_sources} ${win32_sources})
if(UNIX)
target_link_libraries(GKlib m)
endif(UNIX)
include_directories("test")
add_subdirectory("test")
install(TARGETS GKlib
ARCHIVE DESTINATION lib/${LINSTALL_PATH}
LIBRARY DESTINATION lib/${LINSTALL_PATH})
install(FILES ${GKlib_includes} DESTINATION include/${HINSTALL_PATH})
+85
View File
@@ -0,0 +1,85 @@
/*
* GKlib.h
*
* George's library of most frequently used routines
*
* $Id: GKlib.h 14866 2013-08-03 16:40:04Z karypis $
*
*/
#ifndef _GKLIB_H_
#define _GKLIB_H_ 1
#define GKMSPACE
#if defined(_MSC_VER)
#define __MSC__
#endif
#if defined(__ICC)
#define __ICC__
#endif
#include "gk_arch.h" /*!< This should be here, prior to the includes */
/*************************************************************************
* Header file inclusion section
**************************************************************************/
#include <stddef.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <memory.h>
#include <errno.h>
#include <ctype.h>
#include <math.h>
#include <float.h>
#include <time.h>
#include <string.h>
#include <limits.h>
#include <signal.h>
#include <setjmp.h>
#include <assert.h>
#include <sys/stat.h>
#if defined(__WITHPCRE__)
#include <pcreposix.h>
#else
#if defined(USE_GKREGEX)
#include "gkregex.h"
#else
#include <regex.h>
#endif /* defined(USE_GKREGEX) */
#endif /* defined(__WITHPCRE__) */
#if defined(__OPENMP__)
#include <omp.h>
#endif
#include <gk_types.h>
#include <gk_struct.h>
#include <gk_externs.h>
#include <gk_defs.h>
#include <gk_macros.h>
#include <gk_getopt.h>
#include <gk_mksort.h>
#include <gk_mkblas.h>
#include <gk_mkmemory.h>
#include <gk_mkpqueue.h>
#include <gk_mkpqueue2.h>
#include <gk_mkrandom.h>
#include <gk_mkutils.h>
#include <gk_proto.h>
#endif /* GKlib.h */
+152
View File
@@ -0,0 +1,152 @@
# Helper modules.
include(CheckFunctionExists)
include(CheckIncludeFile)
# Setup options.
option(GDB "enable use of GDB" OFF)
option(ASSERT "turn asserts on" OFF)
option(ASSERT2 "additional assertions" OFF)
option(DEBUG "add debugging support" OFF)
option(GPROF "add gprof support" OFF)
option(VALGRIND "add valgrind support" OFF)
option(OPENMP "enable OpenMP support" OFF)
option(PCRE "enable PCRE support" OFF)
option(GKREGEX "enable GKREGEX support" OFF)
option(GKRAND "enable GKRAND support" OFF)
option(NO_X86 "enable NO_X86 support" OFF)
# Add compiler flags.
if(MSVC)
set(GKlib_COPTS "/Ox")
set(GKlib_COPTIONS "-DWIN32 -DMSC -D_CRT_SECURE_NO_DEPRECATE -DUSE_GKREGEX")
elseif(MINGW)
set(GKlib_COPTS "-DUSE_GKREGEX")
else()
set(GKlib_COPTIONS "-DLINUX -D_FILE_OFFSET_BITS=64")
endif(MSVC)
if(CYGWIN)
set(GKlib_COPTIONS "${GKlib_COPTIONS} -DCYGWIN")
endif(CYGWIN)
if(CMAKE_COMPILER_IS_GNUCC)
# GCC opts.
set(GKlib_COPTIONS "${GKlib_COPTIONS} -std=c99 -fno-strict-aliasing")
if(VALGRIND)
set(GKlib_COPTIONS "${GK_COPTIONS} -march=x86-64 -mtune=generic")
else()
# -march=native is not a valid flag on PPC:
if(CMAKE_SYSTEM_PROCESSOR MATCHES "power|ppc|powerpc|ppc64|powerpc64" OR (APPLE AND CMAKE_OSX_ARCHITECTURES MATCHES "ppc|ppc64"))
set(GKlib_COPTIONS "${GKlib_COPTIONS} -mtune=native")
else()
set(GKlib_COPTIONS "${GKlib_COPTIONS} -march=native")
endif()
endif(VALGRIND)
if(NOT MINGW)
set(GKlib_COPTIONS "${GKlib_COPTIONS} -fPIC")
endif(NOT MINGW)
# GCC warnings.
set(GKlib_COPTIONS "${GKlib_COPTIONS} -Werror -Wall -pedantic -Wno-unused-function -Wno-unused-but-set-variable -Wno-unused-variable -Wno-unknown-pragmas -Wno-unused-label")
elseif(${CMAKE_C_COMPILER_ID} MATCHES "Sun")
# Sun insists on -xc99.
set(GKlib_COPTIONS "${GKlib_COPTIONS} -xc99")
endif(CMAKE_COMPILER_IS_GNUCC)
# Intel compiler
if(${CMAKE_C_COMPILER_ID} MATCHES "Intel")
set(GKlib_COPTIONS "${GKlib_COPTIONS} -xHost -std=c99")
endif()
# Find OpenMP if it is requested.
if(OPENMP)
include(FindOpenMP)
if(OPENMP_FOUND)
set(GKlib_COPTIONS "${GKlib_COPTIONS} -D__OPENMP__ ${OpenMP_C_FLAGS}")
else()
message(WARNING "OpenMP was requested but support was not found")
endif(OPENMP_FOUND)
endif(OPENMP)
# Set the CPU type
if(NO_X86)
set(GKlib_COPTIONS "${GKlib_COPTIONS} -DNO_X86=${NO_X86}")
endif(NO_X86)
# Add various definitions.
if(GDB)
set(GKlib_COPTS "${GKlib_COPTS} -g")
set(GKlib_COPTIONS "${GKlib_COPTIONS} -Werror")
else()
set(GKlib_COPTS "-O3")
endif(GDB)
if(DEBUG)
set(GKlib_COPTS "-g")
set(GKlib_COPTIONS "${GKlib_COPTIONS} -DDEBUG")
endif(DEBUG)
if(GPROF)
set(GKlib_COPTS "-pg")
endif(GPROF)
if(NOT ASSERT)
set(GKlib_COPTIONS "${GKlib_COPTIONS} -DNDEBUG")
endif(NOT ASSERT)
if(NOT ASSERT2)
set(GKlib_COPTIONS "${GKlib_COPTIONS} -DNDEBUG2")
endif(NOT ASSERT2)
# Add various options
if(PCRE)
set(GKlib_COPTIONS "${GKlib_COPTIONS} -D__WITHPCRE__")
endif(PCRE)
if(GKREGEX)
set(GKlib_COPTIONS "${GKlib_COPTIONS} -DUSE_GKREGEX")
endif(GKREGEX)
if(GKRAND)
set(GKlib_COPTIONS "${GKlib_COPTIONS} -DUSE_GKRAND")
endif(GKRAND)
# Check for features.
check_include_file(execinfo.h HAVE_EXECINFO_H)
if(HAVE_EXECINFO_H)
set(GKlib_COPTIONS "${GKlib_COPTIONS} -DHAVE_EXECINFO_H")
endif(HAVE_EXECINFO_H)
check_function_exists(getline HAVE_GETLINE)
if(HAVE_GETLINE)
set(GKlib_COPTIONS "${GKlib_COPTIONS} -DHAVE_GETLINE")
endif(HAVE_GETLINE)
# Custom check for TLS.
if(MSVC)
set(GKlib_COPTIONS "${GKlib_COPTIONS} -D__thread=__declspec(thread)")
# This if checks if that value is cached or not.
if("${HAVE_THREADLOCALSTORAGE}" MATCHES "^${HAVE_THREADLOCALSTORAGE}$")
try_compile(HAVE_THREADLOCALSTORAGE
${CMAKE_BINARY_DIR}
${GKLIB_PATH}/conf/check_thread_storage.c)
if(HAVE_THREADLOCALSTORAGE)
message(STATUS "checking for thread-local storage - found")
else()
message(STATUS "checking for thread-local storage - not found")
endif()
endif()
if(NOT HAVE_THREADLOCALSTORAGE)
set(GKlib_COPTIONS "${GKlib_COPTIONS} -D__thread=")
endif()
endif()
# Finally set the official C flags.
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${GKlib_COPTIONS} ${GKlib_COPTS}")
# Find GKlib sources.
file(GLOB GKlib_sources ${GKLIB_PATH}/*.c)
file(GLOB GKlib_includes ${GKLIB_PATH}/*.h)
+18
View File
@@ -0,0 +1,18 @@
Copyright & License Notice
---------------------------
Copyright 1995-2018, Regents of the University of Minnesota
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
+87
View File
@@ -0,0 +1,87 @@
# Configuration options.
cc = gcc
prefix = ~/local
openmp = not-set
gdb = not-set
assert = not-set
assert2 = not-set
debug = not-set
gprof = not-set
valgrind = not-set
pcre = not-set
gkregex = not-set
gkrand = not-set
# Basically proxies everything to the builddir cmake.
cputype = $(shell uname -m | sed "s/\\ /_/g")
systype = $(shell uname -s)
BUILDDIR = build/$(systype)-$(cputype)
# Process configuration options.
CONFIG_FLAGS = -DCMAKE_VERBOSE_MAKEFILE=1
ifneq ($(gdb), not-set)
CONFIG_FLAGS += -DGDB=$(gdb)
endif
ifneq ($(assert), not-set)
CONFIG_FLAGS += -DASSERT=$(assert)
endif
ifneq ($(assert2), not-set)
CONFIG_FLAGS += -DASSERT2=$(assert2)
endif
ifneq ($(debug), not-set)
CONFIG_FLAGS += -DDEBUG=$(debug)
endif
ifneq ($(gprof), not-set)
CONFIG_FLAGS += -DGPROF=$(gprof)
endif
ifneq ($(valgrind), not-set)
CONFIG_FLAGS += -DVALGRIND=$(valgrind)
endif
ifneq ($(openmp), not-set)
CONFIG_FLAGS += -DOPENMP=$(openmp)
endif
ifneq ($(pcre), not-set)
CONFIG_FLAGS += -DPCRE=$(pcre)
endif
ifneq ($(gkregex), not-set)
CONFIG_FLAGS += -DGKREGEX=$(pcre)
endif
ifneq ($(gkrand), not-set)
CONFIG_FLAGS += -DGKRAND=$(pcre)
endif
ifneq ($(prefix), not-set)
CONFIG_FLAGS += -DCMAKE_INSTALL_PREFIX=$(prefix)
endif
ifneq ($(cc), not-set)
CONFIG_FLAGS += -DCMAKE_C_COMPILER=$(cc)
endif
ifneq ($(cputype), x86_64)
CONFIG_FLAGS += -DNO_X86=$(cputype)
endif
define run-config
mkdir -p $(BUILDDIR)
cd $(BUILDDIR) && cmake $(CURDIR) $(CONFIG_FLAGS)
endef
all clean install: $(BUILDDIR)
make -C $(BUILDDIR) $@
uninstall:
xargs rm < $(BUILDDIR)/install_manifest.txt
$(BUILDDIR):
$(run-config)
config: distclean
$(run-config)
distclean:
rm -rf $(BUILDDIR)
remake:
find . -name CMakeLists.txt -exec touch {} ';'
.PHONY: config distclean all clean install uninstall remake
+54
View File
@@ -0,0 +1,54 @@
# GKlib
A library of various helper routines and frameworks used by many of the lab's software
## Build requirements
- CMake 2.8, found at http://www.cmake.org/, as well as GNU make.
Assuming that the above are available, two commands should suffice to
build the software:
```
make config
make
```
## Configuring the build
It is primarily configured by passing options to make config. For example:
```
make config cc=icc
```
would configure it to be built using icc.
Configuration options are:
```
cc=[compiler] - The C compiler to use [default: gcc]
prefix=[PATH] - Set the installation prefix [default: ~/local]
openmp=set - To build a version with OpenMP support
```
## Building and installing
To build and install, run the following
```
make
make install
```
By default, the library file, header file, and binaries will be installed in
```
~/local/lib
~/local/include
~/local/bin
```
## Other make commands
make uninstall
Removes all files installed by 'make install'.
make clean
Removes all object files but retains the configuration options.
make distclean
Performs clean and completely removes the build directory.
+95
View File
@@ -0,0 +1,95 @@
/*!
\file b64.c
\brief This file contains some simple 8bit-to-6bit encoding/deconding routines
Most of these routines are outdated and should be converted using glibc's equivalent
routines.
\date Started 2/22/05
\author George
\version\verbatim $Id: b64.c 10711 2011-08-31 22:23:04Z karypis $ \endverbatim
\verbatim
$Copyright$
$License$
\endverbatim
*/
#include "GKlib.h"
#define B64OFFSET 48 /* This is the '0' number */
/******************************************************************************
* Encode 3 '8-bit' binary bytes as 4 '6-bit' characters
*******************************************************************************/
void encodeblock(unsigned char *in, unsigned char *out)
{
out[0] = (in[0] >> 2);
out[1] = (((in[0] & 0x03) << 4) | (in[1] >> 4));
out[2] = (((in[1] & 0x0f) << 2) | (in[2] >> 6));
out[3] = (in[2] & 0x3f);
out[0] += B64OFFSET;
out[1] += B64OFFSET;
out[2] += B64OFFSET;
out[3] += B64OFFSET;
// printf("%c %c %c %c %2x %2x %2x %2x %2x %2x %2x\n", out[0], out[1], out[2], out[3], out[0], out[1], out[2], out[3], in[0], in[1], in[2]);
}
/******************************************************************************
* Decode 4 '6-bit' characters into 3 '8-bit' binary bytes
*******************************************************************************/
void decodeblock(unsigned char *in, unsigned char *out)
{
in[0] -= B64OFFSET;
in[1] -= B64OFFSET;
in[2] -= B64OFFSET;
in[3] -= B64OFFSET;
out[0] = (in[0] << 2 | in[1] >> 4);
out[1] = (in[1] << 4 | in[2] >> 2);
out[2] = (in[2] << 6 | in[3]);
}
/******************************************************************************
* This function encodes an input array of bytes into a base64 encoding. Memory
* for the output array is assumed to have been allocated by the calling program
* and be sufficiently large. The output string is NULL terminated.
*******************************************************************************/
void GKEncodeBase64(int nbytes, unsigned char *inbuffer, unsigned char *outbuffer)
{
int i, j;
if (nbytes%3 != 0)
gk_errexit(SIGERR, "GKEncodeBase64: Input buffer size should be a multiple of 3! (%d)\n", nbytes);
for (j=0, i=0; i<nbytes; i+=3, j+=4)
encodeblock(inbuffer+i, outbuffer+j);
//printf("%d %d\n", nbytes, j);
outbuffer[j] = '\0';
}
/******************************************************************************
* This function decodes an input array of base64 characters into their actual
* 8-bit codes. Memory * for the output array is assumed to have been allocated
* by the calling program and be sufficiently large. The padding is discarded.
*******************************************************************************/
void GKDecodeBase64(int nbytes, unsigned char *inbuffer, unsigned char *outbuffer)
{
int i, j;
if (nbytes%4 != 0)
gk_errexit(SIGERR, "GKDecodeBase64: Input buffer size should be a multiple of 4! (%d)\n", nbytes);
for (j=0, i=0; i<nbytes; i+=4, j+=3)
decodeblock(inbuffer+i, outbuffer+j);
}
+37
View File
@@ -0,0 +1,37 @@
/*!
\file blas.c
\brief This file contains GKlib's implementation of BLAS-like routines
The BLAS routines that are currently implemented are mostly level-one.
They follow a naming convention of the type gk_[type][name], where
[type] is one of c, i, f, and d, based on C's four standard scalar
datatypes of characters, integers, floats, and doubles.
These routines are implemented using a generic macro template,
which is used for code generation.
\date Started 9/28/95
\author George
\version\verbatim $Id: blas.c 14330 2013-05-18 12:15:15Z karypis $ \endverbatim
*/
#include <GKlib.h>
/*************************************************************************/
/*! Use the templates to generate BLAS routines for the scalar data types */
/*************************************************************************/
GK_MKBLAS(gk_c, char, int)
GK_MKBLAS(gk_i, int, int)
GK_MKBLAS(gk_i32, int32_t, int32_t)
GK_MKBLAS(gk_i64, int64_t, int64_t)
GK_MKBLAS(gk_z, ssize_t, ssize_t)
GK_MKBLAS(gk_zu, size_t, size_t)
GK_MKBLAS(gk_f, float, float)
GK_MKBLAS(gk_d, double, double)
GK_MKBLAS(gk_idx, gk_idx_t, gk_idx_t)
+126
View File
@@ -0,0 +1,126 @@
/*!
\file
\brief Functions dealing with simulating cache behavior for performance
modeling and analysis;
\date Started 4/13/18
\author George
\author Copyright 1997-2011, Regents of the University of Minnesota
\version $Id: cache.c 21991 2018-04-16 03:08:12Z karypis $
*/
#include <GKlib.h>
/*************************************************************************/
/*! This function creates a cache
*/
/*************************************************************************/
gk_cache_t *gk_cacheCreate(uint32_t nway, uint32_t lnbits, size_t cnbits)
{
gk_cache_t *cache;
cache = (gk_cache_t *)gk_malloc(sizeof(gk_cache_t), "gk_cacheCreate: cache");
memset(cache, 0, sizeof(gk_cache_t));
cache->nway = nway;
cache->lnbits = lnbits;
cache->cnbits = cnbits;
cache->csize = 1<<cnbits;
cache->cmask = cache->csize-1;
cache->latimes = gk_ui64smalloc(cache->csize*nway, 0, "gk_cacheCreate: latimes");
cache->clines = gk_zusmalloc(cache->csize*nway, 0, "gk_cacheCreate: clines");
return cache;
}
/*************************************************************************/
/*! This function resets a cache
*/
/*************************************************************************/
void gk_cacheReset(gk_cache_t *cache)
{
cache->nhits = 0;
cache->nmisses = 0;
gk_ui64set(cache->csize*cache->nway, 0, cache->latimes);
gk_zuset(cache->csize*cache->nway, 0, cache->clines);
return;
}
/*************************************************************************/
/*! This function destroys a cache.
*/
/*************************************************************************/
void gk_cacheDestroy(gk_cache_t **r_cache)
{
gk_cache_t *cache = *r_cache;
if (cache == NULL)
return;
gk_free((void **)&cache->clines, &cache->latimes, &cache, LTERM);
*r_cache = NULL;
}
/*************************************************************************/
/*! This function simulates a load(ptr) operation.
*/
/*************************************************************************/
int gk_cacheLoad(gk_cache_t *cache, size_t addr)
{
uint32_t i, nway=cache->nway;
size_t lru=0;
//printf("%16"PRIx64" ", (uint64_t)addr);
addr = addr>>(cache->lnbits);
//printf("%16"PRIx64" %16"PRIx64" %16"PRIx64" ", (uint64_t)addr, (uint64_t)addr&(cache->cmask), (uint64_t)cache->cmask);
size_t *clines = cache->clines + (addr&(cache->cmask));
uint64_t *latimes = cache->latimes + (addr&(cache->cmask));
cache->clock++;
for (i=0; i<nway; i++) { /* look for hits */
if (clines[i] == addr) {
cache->nhits++;
latimes[i] = cache->clock;
goto DONE;
}
}
for (i=0; i<nway; i++) { /* look for empty spots or the lru spot */
if (clines[i] == 0) {
lru = i;
break;
}
else if (latimes[i] < latimes[lru]) {
lru = i;
}
}
/* initial fill or replace */
cache->nmisses++;
clines[lru] = addr;
latimes[lru] = cache->clock;
DONE:
//printf(" %"PRIu64" %"PRIu64"\n", cache->nhits, cache->clock);
return 1;
}
/*************************************************************************/
/*! This function returns the cache's hitrate
*/
/*************************************************************************/
double gk_cacheGetHitRate(gk_cache_t *cache)
{
return ((double)cache->nhits)/((double)(cache->clock+1));
}
@@ -0,0 +1,5 @@
extern __thread int x;
int main(int argc, char **argv) {
return 0;
}
File diff suppressed because it is too large. Load diff
+214
View File
@@ -0,0 +1,214 @@
/*!
\file error.c
\brief Various error-handling functions
This file contains functions dealing with error reporting and termination
\author George
\date 1/1/2007
\version\verbatim $Id: error.c 10711 2011-08-31 22:23:04Z karypis $ \endverbatim
*/
#define _GK_ERROR_C_ /* this is needed to properly declare the gk_jub* variables
as an extern function in GKlib.h */
#include <GKlib.h>
/* These are the jmp_buf for the graceful exit in case of severe errors.
Multiple buffers are defined to allow for recursive invokation. */
#define MAX_JBUFS 128
__thread int gk_cur_jbufs=-1;
__thread jmp_buf gk_jbufs[MAX_JBUFS];
__thread jmp_buf gk_jbuf;
typedef void (*gksighandler_t)(int);
/* These are the holders of the old singal handlers for the trapped signals */
static __thread gksighandler_t old_SIGMEM_handler; /* Custom signal */
static __thread gksighandler_t old_SIGERR_handler; /* Custom signal */
static __thread gksighandler_t old_SIGMEM_handlers[MAX_JBUFS]; /* Custom signal */
static __thread gksighandler_t old_SIGERR_handlers[MAX_JBUFS]; /* Custom signal */
/* The following is used to control if the gk_errexit() will actually abort or not.
There is always a single copy of this variable */
static int gk_exit_on_error = 1;
/*************************************************************************/
/*! This function sets the gk_exit_on_error variable
*/
/*************************************************************************/
void gk_set_exit_on_error(int value)
{
gk_exit_on_error = value;
}
/*************************************************************************/
/*! This function prints an error message and exits
*/
/*************************************************************************/
void errexit(char *f_str,...)
{
va_list argp;
va_start(argp, f_str);
vfprintf(stderr, f_str, argp);
va_end(argp);
if (strlen(f_str) == 0 || f_str[strlen(f_str)-1] != '\n')
fprintf(stderr,"\n");
fflush(stderr);
if (gk_exit_on_error)
exit(-2);
/* abort(); */
}
/*************************************************************************/
/*! This function prints an error message and raises a signum signal
*/
/*************************************************************************/
void gk_errexit(int signum, char *f_str,...)
{
va_list argp;
va_start(argp, f_str);
vfprintf(stderr, f_str, argp);
va_end(argp);
fprintf(stderr,"\n");
fflush(stderr);
if (gk_exit_on_error)
raise(signum);
}
/***************************************************************************/
/*! This function sets a number of signal handlers and sets the return point
of a longjmp
*/
/***************************************************************************/
int gk_sigtrap()
{
if (gk_cur_jbufs+1 >= MAX_JBUFS)
return 0;
gk_cur_jbufs++;
old_SIGMEM_handlers[gk_cur_jbufs] = signal(SIGMEM, gk_sigthrow);
old_SIGERR_handlers[gk_cur_jbufs] = signal(SIGERR, gk_sigthrow);
return 1;
}
/***************************************************************************/
/*! This function sets the handlers for the signals to their default handlers
*/
/***************************************************************************/
int gk_siguntrap()
{
if (gk_cur_jbufs == -1)
return 0;
signal(SIGMEM, old_SIGMEM_handlers[gk_cur_jbufs]);
signal(SIGERR, old_SIGERR_handlers[gk_cur_jbufs]);
gk_cur_jbufs--;
return 1;
}
/*************************************************************************/
/*! This function is the custome signal handler, which all it does is to
perform a longjump to the most recent saved environment
*/
/*************************************************************************/
void gk_sigthrow(int signum)
{
longjmp(gk_jbufs[gk_cur_jbufs], signum);
}
/***************************************************************************
* This function sets a number of signal handlers and sets the return point
* of a longjmp
****************************************************************************/
void gk_SetSignalHandlers()
{
old_SIGMEM_handler = signal(SIGMEM, gk_NonLocalExit_Handler);
old_SIGERR_handler = signal(SIGERR, gk_NonLocalExit_Handler);
}
/***************************************************************************
* This function sets the handlers for the signals to their default handlers
****************************************************************************/
void gk_UnsetSignalHandlers()
{
signal(SIGMEM, old_SIGMEM_handler);
signal(SIGERR, old_SIGERR_handler);
}
/*************************************************************************
* This function is the handler for SIGUSR1 that implements the cleaning up
* process prior to a non-local exit.
**************************************************************************/
void gk_NonLocalExit_Handler(int signum)
{
longjmp(gk_jbuf, signum);
}
/*************************************************************************/
/*! \brief Thread-safe implementation of strerror() */
/**************************************************************************/
char *gk_strerror(int errnum)
{
#if defined(WIN32) || defined(__MINGW32__)
return strerror(errnum);
#else
#ifndef SUNOS
static __thread char buf[1024];
strerror_r(errnum, buf, 1024);
buf[1023] = '\0';
return buf;
#else
return strerror(errnum);
#endif
#endif
}
/*************************************************************************
* This function prints a backtrace of calling functions
**************************************************************************/
void PrintBackTrace()
{
#ifdef HAVE_EXECINFO_H
void *array[10];
int i, size;
char **strings;
size = backtrace(array, 10);
strings = backtrace_symbols(array, size);
printf("Obtained %d stack frames.\n", size);
for (i=0; i<size; i++) {
printf("%s\n", strings[i]);
}
free(strings);
#endif
}
+132
View File
@@ -0,0 +1,132 @@
/*!
\file evaluate.c
\brief Various routines to evaluate classification performance
\author George
\date 9/23/2008
\version\verbatim $Id: evaluate.c 13328 2012-12-31 14:57:40Z karypis $ \endverbatim
*/
#include <GKlib.h>
/**********************************************************************
* This function computes the max accuracy score of a ranked list,
* given +1/-1 class list
**********************************************************************/
float ComputeAccuracy(int n, gk_fkv_t *list)
{
int i, P, N, TP, FN = 0;
float bAccuracy = 0.0;
float acc;
for (P=0, i=0;i<n;i++)
P += (list[i].val == 1? 1 : 0);
N = n - P;
TP = FN = 0;
for(i=0; i<n; i++){
if (list[i].val == 1)
TP++;
else
FN++;
acc = (TP + N - FN) * 100.0/ (P + N) ;
if (acc > bAccuracy)
bAccuracy = acc;
}
return bAccuracy;
}
/*****************************************************************************
* This function computes the ROC score of a ranked list, given a +1/-1 class
* list.
******************************************************************************/
float ComputeROCn(int n, int maxN, gk_fkv_t *list)
{
int i, P, TP, FP, TPprev, FPprev, AUC;
float prev;
FP = TP = FPprev = TPprev = AUC = 0;
prev = list[0].key -1;
for (P=0, i=0; i<n; i++)
P += (list[i].val == 1 ? 1 : 0);
for (i=0; i<n && FP < maxN; i++) {
if (list[i].key != prev) {
AUC += (TP+TPprev)*(FP-FPprev)/2;
prev = list[i].key;
FPprev = FP;
TPprev = TP;
}
if (list[i].val == 1)
TP++;
else {
FP++;
}
}
AUC += (TP+TPprev)*(FP-FPprev)/2;
return (TP*FP > 0 ? (float)(1.0*AUC/(P*FP)) : 0.0);
}
/*****************************************************************************
* This function computes the median rate of false positive for each positive
* instance.
******************************************************************************/
float ComputeMedianRFP(int n, gk_fkv_t *list)
{
int i, P, N, TP, FP;
P = N = 0;
for (i=0; i<n; i++) {
if (list[i].val == 1)
P++;
else
N++;
}
FP = TP = 0;
for (i=0; i<n && TP < (P+1)/2; i++) {
if (list[i].val == 1)
TP++;
else
FP++;
}
return 1.0*FP/N;
}
/*********************************************************
* Compute the mean
********************************************************/
float ComputeMean (int n, float *values)
{
int i;
float mean = 0.0;
for(i=0; i < n; i++)
mean += values[i];
return 1.0 * mean/ n;
}
/********************************************************
* Compute the standard deviation
********************************************************/
float ComputeStdDev(int n, float *values)
{
int i;
float mean = ComputeMean(n, values);
float stdDev = 0;
for(i=0;i<n;i++){
stdDev += (values[i] - mean)* (values[i] - mean);
}
return sqrt(1.0 * stdDev/n);
}
+142
View File
@@ -0,0 +1,142 @@
/*!
\file dfkvkselect.c
\brief Sorts only the largest k values
\date Started 7/14/00
\author George
\version\verbatim $Id: fkvkselect.c 10711 2011-08-31 22:23:04Z karypis $\endverbatim
*/
#include <GKlib.h>
/* Byte-wise swap two items of size SIZE. */
#define QSSWAP(a, b, stmp) do { stmp = (a); (a) = (b); (b) = stmp; } while (0)
/******************************************************************************/
/*! This function puts the 'topk' largest values in the beginning of the array */
/*******************************************************************************/
int gk_dfkvkselect(size_t n, int topk, gk_fkv_t *cand)
{
int i, j, lo, hi, mid;
gk_fkv_t stmp;
float pivot;
if (n <= topk)
return n; /* return if the array has fewer elements than we want */
for (lo=0, hi=n-1; lo < hi;) {
mid = lo + ((hi-lo) >> 1);
/* select the median */
if (cand[lo].key < cand[mid].key)
mid = lo;
if (cand[hi].key > cand[mid].key)
mid = hi;
else
goto jump_over;
if (cand[lo].key < cand[mid].key)
mid = lo;
jump_over:
QSSWAP(cand[mid], cand[hi], stmp);
pivot = cand[hi].key;
/* the partitioning algorithm */
for (i=lo-1, j=lo; j<hi; j++) {
if (cand[j].key >= pivot) {
i++;
QSSWAP(cand[i], cand[j], stmp);
}
}
i++;
QSSWAP(cand[i], cand[hi], stmp);
if (i > topk)
hi = i-1;
else if (i < topk)
lo = i+1;
else
break;
}
/*
if (cand[lo].key < cand[hi].key)
printf("Hmm Error: %d %d %d %f %f\n", i, lo, hi, cand[lo].key, cand[hi].key);
for (i=topk; i<n; i++) {
for (j=0; j<topk; j++)
if (cand[i].key > cand[j].key)
printf("Hmm Error: %d %d %f %f %d %d\n", i, j, cand[i].key, cand[j].key, lo, hi);
}
*/
return topk;
}
/******************************************************************************/
/*! This function puts the 'topk' smallest values in the beginning of the array */
/*******************************************************************************/
int gk_ifkvkselect(size_t n, int topk, gk_fkv_t *cand)
{
int i, j, lo, hi, mid;
gk_fkv_t stmp;
float pivot;
if (n <= topk)
return n; /* return if the array has fewer elements than we want */
for (lo=0, hi=n-1; lo < hi;) {
mid = lo + ((hi-lo) >> 1);
/* select the median */
if (cand[lo].key > cand[mid].key)
mid = lo;
if (cand[hi].key < cand[mid].key)
mid = hi;
else
goto jump_over;
if (cand[lo].key > cand[mid].key)
mid = lo;
jump_over:
QSSWAP(cand[mid], cand[hi], stmp);
pivot = cand[hi].key;
/* the partitioning algorithm */
for (i=lo-1, j=lo; j<hi; j++) {
if (cand[j].key <= pivot) {
i++;
QSSWAP(cand[i], cand[j], stmp);
}
}
i++;
QSSWAP(cand[i], cand[hi], stmp);
if (i > topk)
hi = i-1;
else if (i < topk)
lo = i+1;
else
break;
}
/*
if (cand[lo].key > cand[hi].key)
printf("Hmm Error: %d %d %d %f %f\n", i, lo, hi, cand[lo].key, cand[hi].key);
for (i=topk; i<n; i++) {
for (j=0; j<topk; j++)
if (cand[i].key < cand[j].key)
printf("Hmm Error: %d %d %f %f %d %d\n", i, j, cand[i].key, cand[j].key, lo, hi);
}
*/
return topk;
}
Loaded 100 of 261 files, more files were not shown because too many files have changed in this diff. Show more