Compare commits

..
35 Commits
Author SHA1 Message Date
shinyobjectz b90ee0728c #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 13:59:45 -08:00
shinyobjectz 5eb8b1e40e 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 13:43:27 -08:00
shinyobjectz bce27988ab windows-arm.yml: metis-sys alone on windows-latest's x64 MSVC too, which release.yml builds with 2026-11-26 11:42:54 -08:00
shinyobjectz c02a02d902 #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 11:42:35 -08:00
shinyobjectz b26da1cc95 #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 11:35:06 -08:00
shinyobjectz cf0282f550 #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 11:26:19 -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
179 changed files with 50979 additions and 129 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
+9 -2
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"
+5
View File
@@ -195,6 +195,7 @@ members = [
"runtime/endchecks",
"runtime/lod-plan",
"runtime/cut-plan",
"runtime/goal-plan",
"runtime/live",
"runtime/page",
"runtime/appscreen",
@@ -345,6 +346,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:")
+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()),
}
+5 -3
View File
@@ -143,7 +143,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,7 +183,7 @@ 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);
@@ -191,6 +191,7 @@ pub fn status(job: &Job) -> Value {
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))),
(_, make::Kind::Goal) => gates.extend(job.make.goal.iter().flat_map(|g| raea_runtime_goal_plan::gates(g, job.dir)).map(|g| gate(g.name, g.of.as_deref(), g.clear, g.says))),
_ => 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"
}
+24 -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());
}
+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
+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
+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"] }
+14 -7
View File
@@ -183,17 +183,24 @@ 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();
let (best, heard_share) = lines.iter().map(|l| (*l, share(l, &last))).fold(("", 0.0), |a, b| if b.1 > a.1 { b } else { a });
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"
+211
View File
@@ -0,0 +1,211 @@
//! 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: its name, the rule 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,
}
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")
+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 });
+76 -9
View File
@@ -7,7 +7,7 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::Ordering;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex};
@@ -34,7 +34,15 @@ 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 (its name), the block size it was asked for, and whether cpal said the stream broke
/// (the device unplugged, its AirPods put away): the stage follows the system's output (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)
device: String,
block: u32,
lost: Arc<AtomicBool>,
looked: std::time::Instant,
voices: NodeID,
master: NodeID,
score: Option<Score>,
@@ -85,7 +93,8 @@ 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 lost = Arc::new(AtomicBool::new(false));
let (stream, rate, device) = start(&mut cx, block, lost.clone())?;
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 +106,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), device, block, lost, looked: std::time::Instant::now(), 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 +218,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 +354,62 @@ 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) {
let lost = self.lost.load(Ordering::Relaxed);
if !lost && self.looked.elapsed() < std::time::Duration::from_secs(1) {
return;
}
self.looked = std::time::Instant::now();
let now = cpal::default_host().default_output_device().and_then(|d| d.name().ok()).unwrap_or_default();
if !lost && (now.is_empty() || now == self.device) {
return;
}
// the old stream and its callback go, and the processor in it: the context is free to start again
self._stream = None;
let t0 = std::time::Instant::now();
while self.cx.is_active() && t0.elapsed() < std::time::Duration::from_millis(500) {
let _ = self.cx.update();
std::thread::sleep(std::time::Duration::from_millis(1));
}
self.lost.store(false, Ordering::Relaxed);
match start(&mut self.cx, self.block, self.lost.clone()) {
Ok((stream, rate, device)) => {
eprintln!("raea mixer: sound now on {device} (was {})", if self.device.is_empty() { "nothing" } else { &self.device });
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.device = device;
self.resting = false;
self.origin = None;
self.settled = false;
self.opened = std::time::Instant::now();
let _ = self.cx.update();
}
// no device to play on (none plugged in): looked for again in a second
Err(e) => {
if !self.device.is_empty() {
eprintln!("raea mixer: no sound: {e}");
}
self.device.clear();
}
}
}
/// 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 +421,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));
@@ -407,9 +468,10 @@ 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> {
fn start(cx: &mut FirewheelContext, block: u32, lost: Arc<AtomicBool>) -> Result<(cpal::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 <= RATE && r.max_sample_rate().0 >= RATE)).unwrap_or(false);
@@ -451,9 +513,14 @@ fn start(cx: &mut FirewheelContext, block: u32) -> Result<(cpal::Stream, u32), S
// 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}"))?;
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))
Ok((stream, rate, name))
}
impl Drop for Live {
+3
View File
@@ -159,6 +159,9 @@ 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 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() },
+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"
+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"
+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);
}
}
+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;
}
+225
View File
@@ -0,0 +1,225 @@
/*!
\file fs.c
\brief Various file-system functions.
This file contains various functions that deal with interfacing with
the filesystem in a portable way.
\date Started 4/10/95
\author George
\version\verbatim $Id: fs.c 14332 2013-05-18 12:22:57Z karypis $ \endverbatim
*/
#include <GKlib.h>
/*************************************************************************
* This function checks if a file exists
**************************************************************************/
int gk_fexists(char *fname)
{
struct stat status;
if (stat(fname, &status) == -1)
return 0;
return S_ISREG(status.st_mode);
}
/*************************************************************************
* This function checks if a directory exists
**************************************************************************/
int gk_dexists(char *dirname)
{
struct stat status;
if (stat(dirname, &status) == -1)
return 0;
return S_ISDIR(status.st_mode);
}
/*************************************************************************/
/*! \brief Returns the size of the file in bytes
This function returns the size of a file as a 64 bit integer. If there
were any errors in stat'ing the file, -1 is returned.
\note That due to the -1 return code, the maximum file size is limited to
63 bits (which I guess is okay for now).
*/
/**************************************************************************/
ssize_t gk_getfsize(char *filename)
{
struct stat status;
if (stat(filename, &status) == -1)
return -1;
return (size_t)(status.st_size);
}
/*************************************************************************/
/*! This function gets some basic statistics about the file.
\param fname is the name of the file
\param r_nlines is the number of lines in the file. If it is NULL,
this information is not returned.
\param r_ntokens is the number of tokens in the file. If it is NULL,
this information is not returned.
\param r_max_nlntokens is the maximum number of tokens in any line
in the file. If it is NULL this information is not returned.
\param r_nbytes is the number of bytes in the file. If it is NULL,
this information is not returned.
*/
/*************************************************************************/
void gk_getfilestats(char *fname, size_t *r_nlines, size_t *r_ntokens,
size_t *r_max_nlntokens, size_t *r_nbytes)
{
size_t nlines=0, ntokens=0, max_nlntokens=0, nbytes=0, oldntokens=0, nread;
int intoken=0;
char buffer[4097], *cptr;
FILE *fpin;
fpin = gk_fopen(fname, "r", "gk_GetFileStats");
while (!feof(fpin)) {
nread = fread(buffer, sizeof(char), 4096, fpin);
nbytes += nread;
buffer[nread] = '\0'; /* There is space for this one */
for (cptr=buffer; *cptr!='\0'; cptr++) {
if (*cptr == '\n') {
nlines++;
ntokens += intoken;
intoken = 0;
if (max_nlntokens < ntokens-oldntokens)
max_nlntokens = ntokens-oldntokens;
oldntokens = ntokens;
}
else if (*cptr == ' ' || *cptr == '\t') {
ntokens += intoken;
intoken = 0;
}
else {
intoken = 1;
}
}
}
ntokens += intoken;
if (max_nlntokens < ntokens-oldntokens)
max_nlntokens = ntokens-oldntokens;
gk_fclose(fpin);
if (r_nlines != NULL)
*r_nlines = nlines;
if (r_ntokens != NULL)
*r_ntokens = ntokens;
if (r_max_nlntokens != NULL)
*r_max_nlntokens = max_nlntokens;
if (r_nbytes != NULL)
*r_nbytes = nbytes;
}
/*************************************************************************
* This function takes in a potentially full path specification of a file
* and just returns a string containing just the basename of the file.
* The basename is derived from the actual filename by stripping the last
* .ext part.
**************************************************************************/
char *gk_getbasename(char *path)
{
char *startptr, *endptr;
char *basename;
if ((startptr = strrchr(path, '/')) == NULL)
startptr = path;
else
startptr = startptr+1;
basename = gk_strdup(startptr);
if ((endptr = strrchr(basename, '.')) != NULL)
*endptr = '\0';
return basename;
}
/*************************************************************************
* This function takes in a potentially full path specification of a file
* and just returns a string corresponding to its file extension. The
* extension of a file is considered to be the string right after the
* last '.' character.
**************************************************************************/
char *gk_getextname(char *path)
{
char *startptr;
if ((startptr = strrchr(path, '.')) == NULL)
return gk_strdup(path);
else
return gk_strdup(startptr+1);
}
/*************************************************************************
* This function takes in a potentially full path specification of a file
* and just returns a string containing just the filename.
**************************************************************************/
char *gk_getfilename(char *path)
{
char *startptr;
if ((startptr = strrchr(path, '/')) == NULL)
return gk_strdup(path);
else
return gk_strdup(startptr+1);
}
/*************************************************************************
* This function takes in a potentially full path specification of a file
* and extracts the directory path component if it exists, otherwise it
* returns "./" as the path. The memory for it is dynamically allocated.
**************************************************************************/
char *getpathname(char *path)
{
char *endptr, *tmp;
if ((endptr = strrchr(path, '/')) == NULL) {
return gk_strdup(".");
}
else {
tmp = gk_strdup(path);
*(strrchr(tmp, '/')) = '\0';
return tmp;
}
}
/*************************************************************************
* This function creates a path
**************************************************************************/
int gk_mkpath(char *pathname)
{
char tmp[2048];
sprintf(tmp, "mkdir -p %s", pathname);
return system(tmp);
}
/*************************************************************************
* This function deletes a directory tree and all of its contents
**************************************************************************/
int gk_rmpath(char *pathname)
{
char tmp[2048];
sprintf(tmp, "rm -r %s", pathname);
return system(tmp);
}
+855
View File
@@ -0,0 +1,855 @@
/*************************************************************************/
/*! \file getopt.c
\brief Command line parsing
This file contains a implementation of GNU's Getopt facility. The purpose
for including it here is to ensure portability across different unix- and
windows-based systems.
\warning
The implementation provided here uses the \c gk_ prefix for all variables
used by the standard Getopt facility to communicate with the program.
So, do read the documentation here.
\verbatim
Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001
Free Software Foundation, Inc. This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
\endverbatim
*/
/*************************************************************************/
#include <GKlib.h>
/*************************************************************************/
/* Local function prototypes */
/*************************************************************************/
static void exchange (char **);
static char *gk_getopt_initialize (int, char **, char *);
static int gk_getopt_internal(int argc, char **argv, char *optstring,
struct gk_option *longopts, int *longind, int long_only);
/*************************************************************************/
/*! \brief For communication arguments to the caller.
This variable is set by getopt to point at the value of the option argument,
for those options that accept arguments.
*/
/*************************************************************************/
char *gk_optarg;
/*************************************************************************/
/*! \brief Index in ARGV of the next element to be scanned.
This variable is set by getopt to the index of the next element of the argv
array to be processed. Once getopt has found all of the option arguments,
you can use this variable to determine where the remaining non-option arguments
begin.
*/
/*************************************************************************/
int gk_optind = 1;
/*************************************************************************/
/*! \brief Controls error reporting for unrecognized options.
If the value of this variable is nonzero, then getopt prints an error
message to the standard error stream if it encounters an unknown option
character or an option with a missing required argument. This is the default
behavior. If you set this variable to zero, getopt does not print any messages,
but it still returns the character ? to indicate an error.
*/
/*************************************************************************/
int gk_opterr = 1;
/*************************************************************************/
/*! \brief Stores unknown option characters
When getopt encounters an unknown option character or an option with a
missing required argument, it stores that option character in this
variable. You can use this for providing your own diagnostic messages.
*/
/*************************************************************************/
int gk_optopt = '?';
/*************************************************************************/
/*
Records that the getopt facility has been initialized.
*/
/*************************************************************************/
int gk_getopt_initialized;
/*************************************************************************/
/*
The next char to be scanned in the option-element in which the last option
character we returned was found. This allows us to pick up the scan where
we left off.
If this is zero, or a null string, it means resume the scan by advancing
to the next ARGV-element.
*/
/*************************************************************************/
static char *nextchar;
/*************************************************************************/
/*
Value of POSIXLY_CORRECT environment variable.
*/
/*************************************************************************/
static char *posixly_correct;
/*************************************************************************/
/*
Describe how to deal with options that follow non-option ARGV-elements.
If the caller did not specify anything, the default is REQUIRE_ORDER if
the environment variable POSIXLY_CORRECT is defined, PERMUTE otherwise.
REQUIRE_ORDER means don't recognize them as options; stop option processing
when the first non-option is seen. This is what Unix does. This mode of
operation is selected by either setting the environment variable
POSIXLY_CORRECT, or using `+' as the first character of the list of
option characters.
PERMUTE is the default. We permute the contents of ARGV as we scan, so
that eventually all the non-options are at the end. This allows options
to be given in any order, even with programs that were not written to
expect this.
RETURN_IN_ORDER is an option available to programs that were written
to expect options and other ARGV-elements in any order and that care
about the ordering of the two. We describe each non-option ARGV-element
as if it were the argument of an option with character code 1.
Using `-' as the first character of the list of option characters
selects this mode of operation.
The special argument `--' forces an end of option-scanning regardless
of the value of `ordering'. In the case of RETURN_IN_ORDER, only
`--' can cause `getopt' to return -1 with `gk_optind' != ARGC.
*/
/*************************************************************************/
static enum
{
REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
} ordering;
/*************************************************************************/
/*
Describe the part of ARGV that contains non-options that have
been skipped. `first_nonopt' is the index in ARGV of the first of them;
`last_nonopt' is the index after the last of them.
*/
/*************************************************************************/
static int first_nonopt;
static int last_nonopt;
/*************************************************************************/
/*
Handle permutation of arguments.
Exchange two adjacent subsequences of ARGV.
One subsequence is elements [first_nonopt,last_nonopt)
which contains all the non-options that have been skipped so far.
The other is elements [last_nonopt,gk_optind), which contains all
the options processed since those non-options were skipped.
`first_nonopt' and `last_nonopt' are relocated so that they describe
the new indices of the non-options in ARGV after they are moved.
*/
/*************************************************************************/
static void exchange (char **argv)
{
int bottom = first_nonopt;
int middle = last_nonopt;
int top = gk_optind;
char *tem;
/* Exchange the shorter segment with the far end of the longer segment.
That puts the shorter segment into the right place.
It leaves the longer segment in the right place overall,
but it consists of two parts that need to be swapped next. */
while (top > middle && middle > bottom) {
if (top - middle > middle - bottom) {
/* Bottom segment is the short one. */
int len = middle - bottom;
register int i;
/* Swap it with the top part of the top segment. */
for (i = 0; i < len; i++) {
tem = argv[bottom + i];
argv[bottom + i] = argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
}
/* Exclude the moved bottom segment from further swapping. */
top -= len;
}
else {
/* Top segment is the short one. */
int len = top - middle;
register int i;
/* Swap it with the bottom part of the bottom segment. */
for (i = 0; i < len; i++) {
tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
}
/* Exclude the moved top segment from further swapping. */
bottom += len;
}
}
/* Update records for the slots the non-options now occupy. */
first_nonopt += (gk_optind - last_nonopt);
last_nonopt = gk_optind;
}
/*************************************************************************/
/*
Initialize the internal data when the first call is made.
*/
/*************************************************************************/
static char *gk_getopt_initialize (int argc, char **argv, char *optstring)
{
/* Start processing options with ARGV-element 1 (since ARGV-element 0
is the program name); the sequence of previously skipped
non-option ARGV-elements is empty. */
first_nonopt = last_nonopt = gk_optind;
nextchar = NULL;
posixly_correct = getenv("POSIXLY_CORRECT");
/* Determine how to handle the ordering of options and nonoptions. */
if (optstring[0] == '-') {
ordering = RETURN_IN_ORDER;
++optstring;
}
else if (optstring[0] == '+') {
ordering = REQUIRE_ORDER;
++optstring;
}
else if (posixly_correct != NULL)
ordering = REQUIRE_ORDER;
else
ordering = PERMUTE;
return optstring;
}
/*************************************************************************/
/*
Scan elements of ARGV (whose length is ARGC) for option characters
given in OPTSTRING.
If an element of ARGV starts with '-', and is not exactly "-" or "--",
then it is an option element. The characters of this element
(aside from the initial '-') are option characters. If `getopt'
is called repeatedly, it returns successively each of the option characters
from each of the option elements.
If `getopt' finds another option character, it returns that character,
updating `gk_optind' and `nextchar' so that the next call to `getopt' can
resume the scan with the following option character or ARGV-element.
If there are no more option characters, `getopt' returns -1.
Then `gk_optind' is the index in ARGV of the first ARGV-element
that is not an option. (The ARGV-elements have been permuted
so that those that are not options now come last.)
OPTSTRING is a string containing the legitimate option characters.
If an option character is seen that is not listed in OPTSTRING,
return '?' after printing an error message. If you set `gk_opterr' to
zero, the error message is suppressed but we still return '?'.
If a char in OPTSTRING is followed by a colon, that means it wants an arg,
so the following text in the same ARGV-element, or the text of the following
ARGV-element, is returned in `gk_optarg'. Two colons mean an option that
wants an optional arg; if there is text in the current ARGV-element,
it is returned in `gk_optarg', otherwise `gk_optarg' is set to zero.
If OPTSTRING starts with `-' or `+', it requests different methods of
handling the non-option ARGV-elements.
See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
Long-named options begin with `--' instead of `-'.
Their names may be abbreviated as long as the abbreviation is unique
or is an exact match for some defined option. If they have an
argument, it follows the option name in the same ARGV-element, separated
from the option name by a `=', or else the in next ARGV-element.
When `getopt' finds a long-named option, it returns 0 if that option's
`flag' field is nonzero, the value of the option's `val' field
if the `flag' field is zero.
LONGOPTS is a vector of `struct gk_option' terminated by an
element containing a name which is zero.
LONGIND returns the index in LONGOPT of the long-named option found.
It is only valid when a long-named option has been found by the most
recent call.
If LONG_ONLY is nonzero, '-' as well as '--' can introduce
long-named options.
*/
/*************************************************************************/
static int gk_getopt_internal(int argc, char **argv, char *optstring,
struct gk_option *longopts, int *longind, int long_only)
{
int print_errors = gk_opterr;
if (optstring[0] == ':')
print_errors = 0;
if (argc < 1)
return -1;
gk_optarg = NULL;
if (gk_optind == 0 || !gk_getopt_initialized) {
if (gk_optind == 0)
gk_optind = 1; /* Don't scan ARGV[0], the program name. */
optstring = gk_getopt_initialize (argc, argv, optstring);
gk_getopt_initialized = 1;
}
/* Test whether ARGV[gk_optind] points to a non-option argument.
Either it does not have option syntax, or there is an environment flag
from the shell indicating it is not an option. The later information
is only used when the used in the GNU libc. */
# define NONOPTION_P (argv[gk_optind][0] != '-' || argv[gk_optind][1] == '\0')
if (nextchar == NULL || *nextchar == '\0') {
/* Advance to the next ARGV-element. */
/* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
moved back by the user (who may also have changed the arguments). */
if (last_nonopt > gk_optind)
last_nonopt = gk_optind;
if (first_nonopt > gk_optind)
first_nonopt = gk_optind;
if (ordering == PERMUTE) {
/* If we have just processed some options following some non-options,
exchange them so that the options come first. */
if (first_nonopt != last_nonopt && last_nonopt != gk_optind)
exchange ((char **) argv);
else if (last_nonopt != gk_optind)
first_nonopt = gk_optind;
/* Skip any additional non-options
and extend the range of non-options previously skipped. */
while (gk_optind < argc && NONOPTION_P)
gk_optind++;
last_nonopt = gk_optind;
}
/* The special ARGV-element `--' means premature end of options.
Skip it like a null option,
then exchange with previous non-options as if it were an option,
then skip everything else like a non-option. */
if (gk_optind != argc && !strcmp (argv[gk_optind], "--")) {
gk_optind++;
if (first_nonopt != last_nonopt && last_nonopt != gk_optind)
exchange ((char **) argv);
else if (first_nonopt == last_nonopt)
first_nonopt = gk_optind;
last_nonopt = argc;
gk_optind = argc;
}
/* If we have done all the ARGV-elements, stop the scan
and back over any non-options that we skipped and permuted. */
if (gk_optind == argc) {
/* Set the next-arg-index to point at the non-options
that we previously skipped, so the caller will digest them. */
if (first_nonopt != last_nonopt)
gk_optind = first_nonopt;
return -1;
}
/* If we have come to a non-option and did not permute it,
either stop the scan or describe it to the caller and pass it by. */
if (NONOPTION_P) {
if (ordering == REQUIRE_ORDER)
return -1;
gk_optarg = argv[gk_optind++];
return 1;
}
/* We have found another option-ARGV-element.
Skip the initial punctuation. */
nextchar = (argv[gk_optind] + 1 + (longopts != NULL && argv[gk_optind][1] == '-'));
}
/* Decode the current option-ARGV-element. */
/* Check whether the ARGV-element is a long option.
If long_only and the ARGV-element has the form "-f", where f is
a valid short option, don't consider it an abbreviated form of
a long option that starts with f. Otherwise there would be no
way to give the -f short option.
On the other hand, if there's a long option "fubar" and
the ARGV-element is "-fu", do consider that an abbreviation of
the long option, just like "--fu", and not "-f" with arg "u".
This distinction seems to be the most useful approach. */
if (longopts != NULL && (argv[gk_optind][1] == '-' || (long_only && (argv[gk_optind][2] || !strchr(optstring, argv[gk_optind][1]))))) {
char *nameend;
struct gk_option *p;
struct gk_option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = -1;
int option_index;
for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++) {
if (!strncmp (p->name, nextchar, nameend - nextchar)) {
if ((unsigned int) (nameend - nextchar) == (unsigned int) strlen (p->name)) {
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL) {
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else if (long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val)
/* Second or later nonexact match found. */
ambig = 1;
}
}
if (ambig && !exact) {
if (print_errors)
fprintf(stderr, "%s: option `%s' is ambiguous\n", argv[0], argv[gk_optind]);
nextchar += strlen (nextchar);
gk_optind++;
gk_optopt = 0;
return '?';
}
if (pfound != NULL) {
option_index = indfound;
gk_optind++;
if (*nameend) {
/* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */
if (pfound->has_arg)
gk_optarg = nameend + 1;
else {
if (print_errors) {
if (argv[gk_optind - 1][1] == '-')
/* --option */
fprintf(stderr, "%s: option `--%s' doesn't allow an argument\n", argv[0], pfound->name);
else
/* +option or -option */
fprintf(stderr, "%s: option `%c%s' doesn't allow an argument\n", argv[0], argv[gk_optind - 1][0], pfound->name);
}
nextchar += strlen (nextchar);
gk_optopt = pfound->val;
return '?';
}
}
else if (pfound->has_arg == 1) {
if (gk_optind < argc)
gk_optarg = argv[gk_optind++];
else {
if (print_errors)
fprintf(stderr, "%s: option `%s' requires an argument\n", argv[0], argv[gk_optind - 1]);
nextchar += strlen (nextchar);
gk_optopt = pfound->val;
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen (nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag) {
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
/* Can't find it as a long option. If this is not getopt_long_only,
or the option starts with '--' or is not a valid short
option, then it's an error. Otherwise interpret it as a short option. */
if (!long_only || argv[gk_optind][1] == '-' || strchr(optstring, *nextchar) == NULL) {
if (print_errors) {
if (argv[gk_optind][1] == '-')
/* --option */
fprintf(stderr, "%s: unrecognized option `--%s'\n", argv[0], nextchar);
else
/* +option or -option */
fprintf(stderr, "%s: unrecognized option `%c%s'\n", argv[0], argv[gk_optind][0], nextchar);
}
nextchar = (char *) "";
gk_optind++;
gk_optopt = 0;
return '?';
}
}
/* Look at and handle the next short option-character. */
{
char c = *nextchar++;
char *temp = strchr(optstring, c);
/* Increment `gk_optind' when we start to process its last character. */
if (*nextchar == '\0')
++gk_optind;
if (temp == NULL || c == ':') {
if (print_errors) {
if (posixly_correct)
/* 1003.2 specifies the format of this message. */
fprintf(stderr, "%s: illegal option -- %c\n", argv[0], c);
else
fprintf(stderr, "%s: invalid option -- %c\n", argv[0], c);
}
gk_optopt = c;
return '?';
}
/* Convenience. Treat POSIX -W foo same as long option --foo */
if (temp[0] == 'W' && temp[1] == ';') {
char *nameend;
struct gk_option *p;
struct gk_option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = 0;
int option_index;
/* This is an option that requires an argument. */
if (*nextchar != '\0') {
gk_optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
gk_optind++;
}
else if (gk_optind == argc) {
if (print_errors) {
/* 1003.2 specifies the format of this message. */
fprintf(stderr, "%s: option requires an argument -- %c\n", argv[0], c);
}
gk_optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
return c;
}
else
/* We already incremented `gk_optind' once; increment it again when taking next ARGV-elt as argument. */
gk_optarg = argv[gk_optind++];
/* gk_optarg is now the argument, see if it's in the table of longopts. */
for (nextchar = nameend = gk_optarg; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++) {
if (!strncmp (p->name, nextchar, nameend - nextchar)) {
if ((unsigned int) (nameend - nextchar) == strlen (p->name)) {
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL) {
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else
/* Second or later nonexact match found. */
ambig = 1;
}
}
if (ambig && !exact) {
if (print_errors)
fprintf(stderr, "%s: option `-W %s' is ambiguous\n", argv[0], argv[gk_optind]);
nextchar += strlen (nextchar);
gk_optind++;
return '?';
}
if (pfound != NULL) {
option_index = indfound;
if (*nameend) {
/* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */
if (pfound->has_arg)
gk_optarg = nameend + 1;
else {
if (print_errors)
fprintf(stderr, "%s: option `-W %s' doesn't allow an argument\n", argv[0], pfound->name);
nextchar += strlen (nextchar);
return '?';
}
}
else if (pfound->has_arg == 1) {
if (gk_optind < argc)
gk_optarg = argv[gk_optind++];
else {
if (print_errors)
fprintf(stderr, "%s: option `%s' requires an argument\n", argv[0], argv[gk_optind - 1]);
nextchar += strlen (nextchar);
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen (nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag) {
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
nextchar = NULL;
return 'W'; /* Let the application handle it. */
}
if (temp[1] == ':') {
if (temp[2] == ':') {
/* This is an option that accepts an argument optionally. */
if (*nextchar != '\0') {
gk_optarg = nextchar;
gk_optind++;
}
else
gk_optarg = NULL;
nextchar = NULL;
}
else {
/* This is an option that requires an argument. */
if (*nextchar != '\0') {
gk_optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */
gk_optind++;
}
else if (gk_optind == argc) {
if (print_errors) {
/* 1003.2 specifies the format of this message. */
fprintf(stderr, "%s: option requires an argument -- %c\n", argv[0], c);
}
gk_optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
}
else
/* We already incremented `gk_optind' once; increment it again when taking next ARGV-elt as argument. */
gk_optarg = argv[gk_optind++];
nextchar = NULL;
}
}
return c;
}
}
/*************************************************************************/
/*! \brief Parse command-line arguments
The gk_getopt() function gets the next option argument from the argument
list specified by the \c argv and \c argc arguments. Normally these values
come directly from the arguments received by main().
\param argc is the number of command line arguments passed to main().
\param argv is an array of strings storing the above command line
arguments.
\param options is a string that specifies the option characters that
are valid for this program. An option character in this string
can be followed by a colon (`:') to indicate that it takes a
required argument. If an option character is followed by two
colons (`::'), its argument is optional; this is a GNU extension.
\return
It returns the option character for the next command line option. When no
more option arguments are available, it returns -1. There may still be
more non-option arguments; you must compare the external variable
#gk_optind against the \c argc parameter to check this.
\return
If the option has an argument, gk_getopt() returns the argument by storing
it in the variable #gk_optarg. You don't ordinarily need to copy the
#gk_optarg string, since it is a pointer into the original \c argv array,
not into a static area that might be overwritten.
\return
If gk_getopt() finds an option character in \c argv that was not included
in options, or a missing option argument, it returns `?' and sets the
external variable #gk_optopt to the actual option character.
If the first character of options is a colon (`:'), then gk_getopt()
returns `:' instead of `?' to indicate a missing option argument.
In addition, if the external variable #gk_opterr is nonzero (which is
the default), gk_getopt() prints an error message. This variable is
set by gk_getopt() to point at the value of the option argument,
for those options that accept arguments.
gk_getopt() has three ways to deal with options that follow non-options
\c argv elements. The special argument <tt>`--'</tt> forces in all cases
the end of option scanning.
- The default is to permute the contents of \c argv while scanning it
so that eventually all the non-options are at the end. This allows
options to be given in any order, even with programs that were not
written to expect this.
- If the options argument string begins with a hyphen (`-'), this is
treated specially. It permits arguments that are not options to be
returned as if they were associated with option character `\\1'.
- POSIX demands the following behavior: The first non-option stops
option processing. This mode is selected by either setting the
environment variable POSIXLY_CORRECT or beginning the options
argument string with a plus sign (`+').
*/
/*************************************************************************/
int gk_getopt(int argc, char **argv, char *options)
{
return gk_getopt_internal(argc, argv, options, NULL, NULL, 0);
}
/*************************************************************************/
/*! \brief Parse command-line arguments with long options
This function accepts GNU-style long options as well as single-character
options.
\param argc is the number of command line arguments passed to main().
\param argv is an array of strings storing the above command line
arguments.
\param options describes the short options to accept, just as it does
in gk_getopt().
\param long_options describes the long options to accept. See the
defintion of ::gk_option for more information.
\param opt_index this is a returned variable. For any long option,
gk_getopt_long() tells you the index in the array \c long_options
of the options definition, by storing it into <tt>*opt_index</tt>.
You can get the name of the option with <tt>longopts[*opt_index].name</tt>.
So you can distinguish among long options either by the values
in their val fields or by their indices. You can also distinguish
in this way among long options that set flags.
\return
When gk_getopt_long() encounters a short option, it does the same thing
that gk_getopt() would do: it returns the character code for the option,
and stores the options argument (if it has one) in #gk_optarg.
\return
When gk_getopt_long() encounters a long option, it takes actions based
on the flag and val fields of the definition of that option.
\return
If flag is a null pointer, then gk_getopt_long() returns the contents
of val to indicate which option it found. You should arrange distinct
values in the val field for options with different meanings, so you
can decode these values after gk_getopt_long() returns. If the long
option is equivalent to a short option, you can use the short option's
character code in val.
\return
If flag is not a null pointer, that means this option should just set
a flag in the program. The flag is a variable of type int that you
define. Put the address of the flag in the flag field. Put in the
val field the value you would like this option to store in the flag.
In this case, gk_getopt_long() returns 0.
\return
When a long option has an argument, gk_getopt_long() puts the argument
value in the variable #gk_optarg before returning. When the option has
no argument, the value in #gk_optarg is a null pointer. This is
how you can tell whether an optional argument was supplied.
\return
When gk_getopt_long() has no more options to handle, it returns -1,
and leaves in the variable #gk_optind the index in argv of the next
remaining argument.
*/
/*************************************************************************/
int gk_getopt_long( int argc, char **argv, char *options,
struct gk_option *long_options, int *opt_index)
{
return gk_getopt_internal (argc, argv, options, long_options, opt_index, 0);
}
/*************************************************************************/
/*! \brief Parse command-line arguments with only long options
Like gk_getopt_long(), but '-' as well as '--' can indicate a long option.
If an option that starts with '-' (not '--') doesn't match a long option,
but does match a short option, it is parsed as a short option instead.
*/
/*************************************************************************/
int gk_getopt_long_only(int argc, char **argv, char *options,
struct gk_option *long_options, int *opt_index)
{
return gk_getopt_internal(argc, argv, options, long_options, opt_index, 1);
}
+77
View File
@@ -0,0 +1,77 @@
/*!
\file gk_arch.h
\brief This file contains various architecture-specific declerations
\date Started 3/27/2007
\author George
\version\verbatim $Id: gk_arch.h 21637 2018-01-03 22:37:24Z karypis $ \endverbatim
*/
#ifndef _GK_ARCH_H_
#define _GK_ARCH_H_
/*************************************************************************
* Architecture-specific differences in header files
**************************************************************************/
#ifdef LINUX
#if !defined(__USE_XOPEN)
#define __USE_XOPEN
#endif
#if !defined(_XOPEN_SOURCE)
#define _XOPEN_SOURCE 600
#endif
#if !defined(__USE_XOPEN2K)
#define __USE_XOPEN2K
#endif
#endif
#ifdef HAVE_EXECINFO_H
#include <execinfo.h>
#endif
#ifdef __MSC__
#if _MSC_VER >= 1800
/* raea: Visual Studio 2013 and later have both headers, and Visual Studio 18's stdint.h types int_fast16_t
differently from the stand-in's, so it stopped compiling (raea#82, the windows-11-arm runner) */
#include <stdint.h>
#include <inttypes.h>
#else
#include "gk_ms_stdint.h"
#include "gk_ms_inttypes.h"
#endif
#include "gk_ms_stat.h"
#include "win32/adapt.h"
#else
#ifndef SUNOS
#include <stdint.h>
#endif
#include <inttypes.h>
#include <sys/types.h>
#ifndef __MINGW32__
#include <sys/resource.h>
#endif
#include <sys/time.h>
#include <unistd.h>
#endif
/*************************************************************************
* Architecture-specific modifications
**************************************************************************/
#ifdef WIN32
typedef ptrdiff_t ssize_t;
#endif
#ifdef SUNOS
#define PTRDIFF_MAX INT64_MAX
#endif
/* MSC does not have INFINITY defined */
#ifndef INFINITY
#define INFINITY FLT_MAX
#endif
#endif
+87
View File
@@ -0,0 +1,87 @@
/*!
\file gk_defs.h
\brief This file contains various constants definitions
\date Started 3/27/2007
\author George
\version\verbatim $Id: gk_defs.h 22039 2018-05-26 16:34:48Z karypis $ \endverbatim
*/
#ifndef _GK_DEFS_H_
#define _GK_DEFS_H_
#define LTERM (void **) 0 /* List terminator for GKfree() */
/* mopt_t types */
#define GK_MOPT_MARK 1
#define GK_MOPT_CORE 2
#define GK_MOPT_HEAP 3
#define HTABLE_EMPTY -1
#define HTABLE_DELETED -2
#define HTABLE_FIRST 1
#define HTABLE_NEXT 2
/* pdb corruption bit switches */
#define CRP_ALTLOCS 1
#define CRP_MISSINGCA 2
#define CRP_MISSINGBB 4
#define CRP_MULTICHAIN 8
#define CRP_MULTICA 16
#define CRP_MULTIBB 32
#define MAXLINELEN 300000
/* GKlib signals to standard signal mapping */
#define SIGMEM SIGABRT
#define SIGERR SIGTERM
/* CSR-related defines */
#define GK_CSR_ROW 1
#define GK_CSR_COL 2
#define GK_CSR_ROWCOL 3
#define GK_CSR_MAXTF 1
#define GK_CSR_SQRT 2
#define GK_CSR_POW25 3
#define GK_CSR_POW65 4
#define GK_CSR_POW75 5
#define GK_CSR_POW85 6
#define GK_CSR_LOG 7
#define GK_CSR_IDF 8
#define GK_CSR_IDF2 9
#define GK_CSR_MAXTF2 10
#define GK_CSR_DOTP 1
#define GK_CSR_COS 2
#define GK_CSR_JAC 3
#define GK_CSR_MIN 4
#define GK_CSR_AMIN 5
#define GK_CSR_FMT_AUTO 2
#define GK_CSR_FMT_CLUTO 1
#define GK_CSR_FMT_CSR 2
#define GK_CSR_FMT_METIS 3
#define GK_CSR_FMT_BINROW 4
#define GK_CSR_FMT_BINCOL 5
#define GK_CSR_FMT_IJV 6
#define GK_CSR_FMT_BIJV 7
#define GK_CSR_SYM_SUM 1
#define GK_CSR_SYM_MIN 2
#define GK_CSR_SYM_MAX 3
#define GK_CSR_SYM_AVG 4
#define GK_GRAPH_FMT_METIS 1
#define GK_GRAPH_FMT_IJV 2
#define GK_GRAPH_FMT_HIJV 3
#define GK_GRAPH_SYM_SUM 1
#define GK_GRAPH_SYM_MIN 2
#define GK_GRAPH_SYM_MAX 3
#define GK_GRAPH_SYM_AVG 4
#endif
+25
View File
@@ -0,0 +1,25 @@
/*!
\file gk_externs.h
\brief This file contains definitions of external variables created by GKlib
\date Started 3/27/2007
\author George
\version\verbatim $Id: gk_externs.h 10711 2011-08-31 22:23:04Z karypis $ \endverbatim
*/
#ifndef _GK_EXTERNS_H_
#define _GK_EXTERNS_H_
/*************************************************************************
* Extern variable definition. Hopefully, the __thread makes them thread-safe.
**************************************************************************/
#ifndef _GK_ERROR_C_
/* declared in error.c */
extern __thread int gk_cur_jbufs;
extern __thread jmp_buf gk_jbufs[];
extern __thread jmp_buf gk_jbuf;
#endif
#endif
+64
View File
@@ -0,0 +1,64 @@
/*!
\file gk_getopt.h
\brief This file contains GNU's externs/structs/prototypes
\date Started 3/27/2007
\author George
\version\verbatim $Id: gk_getopt.h 10711 2011-08-31 22:23:04Z karypis $ \endverbatim
*/
#ifndef _GK_GETOPT_H_
#define _GK_GETOPT_H_
/* Externals from getopt.c */
extern char *gk_optarg;
extern int gk_optind;
extern int gk_opterr;
extern int gk_optopt;
/*! \brief The structure that stores the information about the command-line options
This structure describes a single long option name for the sake of
gk_getopt_long(). The argument <tt>long_options</tt> must be an array
of these structures, one for each long option. Terminate the array with
an element containing all zeros.
*/
struct gk_option {
char *name; /*!< This field is the name of the option. */
int has_arg; /*!< This field says whether the option takes an argument.
It is an integer, and there are three legitimate values:
no_argument, required_argument and optional_argument.
*/
int *flag; /*!< See the discussion on ::gk_option#val */
int val; /*!< These fields control how to report or act on the option
when it occurs.
If flag is a null pointer, then the val is a value which
identifies this option. Often these values are chosen
to uniquely identify particular long options.
If flag is not a null pointer, it should be the address
of an int variable which is the flag for this option.
The value in val is the value to store in the flag to
indicate that the option was seen. */
};
/* Names for the values of the `has_arg' field of `struct gk_option'. */
#define no_argument 0
#define required_argument 1
#define optional_argument 2
/* Function prototypes */
extern int gk_getopt(int argc, char **argv, char *shortopts);
extern int gk_getopt_long(int argc, char **argv, char *shortopts,
struct gk_option *longopts, int *longind);
extern int gk_getopt_long_only (int argc, char **argv,
char *shortopts, struct gk_option *longopts, int *longind);
#endif
+169
View File
@@ -0,0 +1,169 @@
/*!
\file gk_macros.h
\brief This file contains various macros
\date Started 3/27/2007
\author George
\version\verbatim $Id: gk_macros.h 15048 2013-08-31 19:38:14Z karypis $ \endverbatim
*/
#ifndef _GK_MACROS_H_
#define _GK_MACROS_H_
/*-------------------------------------------------------------
* Usefull commands
*-------------------------------------------------------------*/
#define gk_max(a, b) ((a) >= (b) ? (a) : (b))
#define gk_min(a, b) ((a) >= (b) ? (b) : (a))
#define gk_max3(a, b, c) ((a) >= (b) && (a) >= (c) ? (a) : ((b) >= (a) && (b) >= (c) ? (b) : (c)))
#define gk_SWAP(a, b, tmp) do {(tmp) = (a); (a) = (b); (b) = (tmp);} while(0)
#define INC_DEC(a, b, val) do {(a) += (val); (b) -= (val);} while(0)
#define sign(a, b) ((a >= 0 ? b : -b))
#define ONEOVERRANDMAX (1.0/(RAND_MAX+1.0))
#define RandomInRange(u) ((int) (ONEOVERRANDMAX*(u)*rand()))
#define RandomInRange_r(s, u) ((int) (ONEOVERRANDMAX*(u)*rand_r(s)))
#define gk_abs(x) ((x) >= 0 ? (x) : -(x))
/*-------------------------------------------------------------
* Timing macros
*-------------------------------------------------------------*/
#define gk_clearcputimer(tmr) (tmr = 0.0)
#define gk_startcputimer(tmr) (tmr -= gk_CPUSeconds())
#define gk_stopcputimer(tmr) (tmr += gk_CPUSeconds())
#define gk_getcputimer(tmr) (tmr)
#define gk_clearwctimer(tmr) (tmr = 0.0)
#define gk_startwctimer(tmr) (tmr -= gk_WClockSeconds())
#define gk_stopwctimer(tmr) (tmr += gk_WClockSeconds())
#define gk_getwctimer(tmr) (tmr)
/*-------------------------------------------------------------
* dbglvl handling macros
*-------------------------------------------------------------*/
#define IFSET(a, flag, cmd) if ((a)&(flag)) (cmd);
/*-------------------------------------------------------------
* gracefull library exit macro
*-------------------------------------------------------------*/
#define GKSETJMP() (setjmp(gk_return_to_entry))
#define gk_sigcatch() (setjmp(gk_jbufs[gk_cur_jbufs]))
/*-------------------------------------------------------------
* Debuging memory leaks
*-------------------------------------------------------------*/
#ifdef DMALLOC
# define MALLOC_CHECK(ptr) \
if (malloc_verify((ptr)) == DMALLOC_VERIFY_ERROR) { \
printf("***MALLOC_CHECK failed on line %d of file %s: " #ptr "\n", \
__LINE__, __FILE__); \
abort(); \
}
#else
# define MALLOC_CHECK(ptr) ;
#endif
/*-------------------------------------------------------------
* CSR conversion macros
*-------------------------------------------------------------*/
#define MAKECSR(i, n, a) \
do { \
for (i=1; i<n; i++) a[i] += a[i-1]; \
for (i=n; i>0; i--) a[i] = a[i-1]; \
a[0] = 0; \
} while(0)
#define SHIFTCSR(i, n, a) \
do { \
for (i=n; i>0; i--) a[i] = a[i-1]; \
a[0] = 0; \
} while(0)
/*-------------------------------------------------------------
* ASSERTS that cannot be turned off!
*-------------------------------------------------------------*/
#define GKASSERT(expr) \
if (!(expr)) { \
printf("***ASSERTION failed on line %d of file %s: " #expr "\n", \
__LINE__, __FILE__); \
abort(); \
}
#define GKASSERTP(expr,msg) \
if (!(expr)) { \
printf("***ASSERTION failed on line %d of file %s: " #expr "\n", \
__LINE__, __FILE__); \
printf msg ; \
printf("\n"); \
abort(); \
}
#define GKCUASSERT(expr) \
if (!(expr)) { \
printf("***ASSERTION failed on line %d of file %s: " #expr "\n", \
__LINE__, __FILE__); \
}
#define GKWARN(expr) \
if (!(expr)) { \
printf("***ASSERTION failed on line %d of file %s: " #expr "\n", \
__LINE__, __FILE__); \
}
#define GKCUASSERTP(expr,msg) \
if (!(expr)) { \
printf("***ASSERTION failed on line %d of file %s: " #expr "\n", \
__LINE__, __FILE__); \
printf msg ; \
printf("\n"); \
}
#define GKWARNP(expr,msg) \
if (!(expr)) { \
printf("***ASSERTION failed on line %d of file %s: " #expr "\n", \
__LINE__, __FILE__); \
printf msg ; \
printf("\n"); \
}
/*-------------------------------------------------------------
* Program Assertions
*-------------------------------------------------------------*/
#ifndef NDEBUG
# define ASSERT(expr) \
if (!(expr)) { \
printf("***ASSERTION failed on line %d of file %s: " #expr "\n", \
__LINE__, __FILE__); \
assert(expr); \
}
# define ASSERTP(expr,msg) \
if (!(expr)) { \
printf("***ASSERTION failed on line %d of file %s: " #expr "\n", \
__LINE__, __FILE__); \
printf msg ; \
printf("\n"); \
assert(expr); \
}
#else
# define ASSERT(expr) ;
# define ASSERTP(expr,msg) ;
#endif
#ifndef NDEBUG2
# define ASSERT2 ASSERT
# define ASSERTP2 ASSERTP
#else
# define ASSERT2(expr) ;
# define ASSERTP2(expr,msg) ;
#endif
#endif
+203
View File
@@ -0,0 +1,203 @@
/*!
\file gk_mkblas.h
\brief Templates for BLAS-like routines
\date Started 3/28/07
\author George
\version\verbatim $Id: gk_mkblas.h 16304 2014-02-25 14:27:19Z karypis $ \endverbatim
*/
#ifndef _GK_MKBLAS_H_
#define _GK_MKBLAS_H_
#define GK_MKBLAS(PRFX, TYPE, OUTTYPE) \
/*************************************************************************/\
/*! The macro for gk_?incset()-class of routines */\
/*************************************************************************/\
TYPE *PRFX ## incset(size_t n, TYPE baseval, TYPE *x)\
{\
size_t i;\
\
for (i=0; i<n; i++)\
x[i] = baseval+i;\
\
return x;\
}\
\
/*************************************************************************/\
/*! The macro for gk_?max()-class of routines */\
/*************************************************************************/\
TYPE PRFX ## max(size_t n, TYPE *x, size_t incx)\
{\
size_t i;\
TYPE max;\
\
if (n <= 0) return (TYPE) 0;\
\
for (max=(*x), x+=incx, i=1; i<n; i++, x+=incx)\
max = ((*x) > max ? (*x) : max);\
\
return max;\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?min()-class of routines */\
/*************************************************************************/\
TYPE PRFX ## min(size_t n, TYPE *x, size_t incx)\
{\
size_t i;\
TYPE min;\
\
if (n <= 0) return (TYPE) 0;\
\
for (min=(*x), x+=incx, i=1; i<n; i++, x+=incx)\
min = ((*x) < min ? (*x) : min);\
\
return min;\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?argmax()-class of routines */\
/*************************************************************************/\
size_t PRFX ## argmax(size_t n, TYPE *x, size_t incx)\
{\
size_t i, j, max=0;\
\
for (i=1, j=incx; i<n; i++, j+=incx)\
max = (x[j] > x[max] ? j : max);\
\
return (size_t)(max/incx);\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?argmin()-class of routines */\
/*************************************************************************/\
size_t PRFX ## argmin(size_t n, TYPE *x, size_t incx)\
{\
size_t i, j, min=0;\
\
for (i=1, j=incx; i<n; i++, j+=incx)\
min = (x[j] < x[min] ? j : min);\
\
return (size_t)(min/incx);\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?argmax_n()-class of routines */\
/*************************************************************************/\
size_t PRFX ## argmax_n(size_t n, TYPE *x, size_t incx, size_t k)\
{\
size_t i, j, max_n;\
PRFX ## kv_t *cand;\
\
cand = PRFX ## kvmalloc(n, "GK_ARGMAX_N: cand");\
\
for (i=0, j=0; i<n; i++, j+=incx) {\
cand[i].val = i;\
cand[i].key = x[j];\
}\
PRFX ## kvsortd(n, cand);\
\
max_n = cand[k-1].val;\
\
gk_free((void *)&cand, LTERM);\
\
return max_n;\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?sum()-class of routines */\
/**************************************************************************/\
OUTTYPE PRFX ## sum(size_t n, TYPE *x, size_t incx)\
{\
size_t i;\
OUTTYPE sum = 0;\
\
for (i=0; i<n; i++, x+=incx)\
sum += (*x);\
\
return sum;\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?scale()-class of routines */\
/**************************************************************************/\
TYPE *PRFX ## scale(size_t n, TYPE alpha, TYPE *x, size_t incx)\
{\
size_t i;\
\
for (i=0; i<n; i++, x+=incx)\
(*x) *= alpha;\
\
return x;\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?norm2()-class of routines */\
/**************************************************************************/\
OUTTYPE PRFX ## norm2(size_t n, TYPE *x, size_t incx)\
{\
size_t i;\
OUTTYPE partial = 0;\
\
for (i=0; i<n; i++, x+=incx)\
partial += (*x) * (*x);\
\
return (partial > 0 ? (OUTTYPE)sqrt((double)partial) : (OUTTYPE)0);\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?dot()-class of routines */\
/**************************************************************************/\
OUTTYPE PRFX ## dot(size_t n, TYPE *x, size_t incx, TYPE *y, size_t incy)\
{\
size_t i;\
OUTTYPE partial = 0.0;\
\
for (i=0; i<n; i++, x+=incx, y+=incy)\
partial += (*x) * (*y);\
\
return partial;\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?axpy()-class of routines */\
/**************************************************************************/\
TYPE *PRFX ## axpy(size_t n, TYPE alpha, TYPE *x, size_t incx, TYPE *y, size_t incy)\
{\
size_t i;\
TYPE *y_in = y;\
\
for (i=0; i<n; i++, x+=incx, y+=incy)\
*y += alpha*(*x);\
\
return y_in;\
}\
#define GK_MKBLAS_PROTO(PRFX, TYPE, OUTTYPE) \
TYPE *PRFX ## incset(size_t n, TYPE baseval, TYPE *x);\
TYPE PRFX ## max(size_t n, TYPE *x, size_t incx);\
TYPE PRFX ## min(size_t n, TYPE *x, size_t incx);\
size_t PRFX ## argmax(size_t n, TYPE *x, size_t incx);\
size_t PRFX ## argmin(size_t n, TYPE *x, size_t incx);\
size_t PRFX ## argmax_n(size_t n, TYPE *x, size_t incx, size_t k);\
OUTTYPE PRFX ## sum(size_t n, TYPE *x, size_t incx);\
TYPE *PRFX ## scale(size_t n, TYPE alpha, TYPE *x, size_t incx);\
OUTTYPE PRFX ## norm2(size_t n, TYPE *x, size_t incx);\
OUTTYPE PRFX ## dot(size_t n, TYPE *x, size_t incx, TYPE *y, size_t incy);\
TYPE *PRFX ## axpy(size_t n, TYPE alpha, TYPE *x, size_t incx, TYPE *y, size_t incy);\
#endif
+142
View File
@@ -0,0 +1,142 @@
/*!
\file gk_mkmemory.h
\brief Templates for memory allocation routines
\date Started 3/29/07
\author George
\version\verbatim $Id: gk_mkmemory.h 10711 2011-08-31 22:23:04Z karypis $ \endverbatim
*/
#ifndef _GK_MKMEMORY_H_
#define _GK_MKMEMORY_H_
#define GK_MKALLOC(PRFX, TYPE)\
/*************************************************************************/\
/*! The macro for gk_?malloc()-class of routines */\
/**************************************************************************/\
TYPE *PRFX ## malloc(size_t n, char *msg)\
{\
return (TYPE *)gk_malloc(sizeof(TYPE)*n, msg);\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?realloc()-class of routines */\
/**************************************************************************/\
TYPE *PRFX ## realloc(TYPE *ptr, size_t n, char *msg)\
{\
return (TYPE *)gk_realloc((void *)ptr, sizeof(TYPE)*n, msg);\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?smalloc()-class of routines */\
/**************************************************************************/\
TYPE *PRFX ## smalloc(size_t n, TYPE ival, char *msg)\
{\
TYPE *ptr;\
\
ptr = (TYPE *)gk_malloc(sizeof(TYPE)*n, msg);\
if (ptr == NULL) \
return NULL; \
\
return PRFX ## set(n, ival, ptr); \
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?set()-class of routines */\
/*************************************************************************/\
TYPE *PRFX ## set(size_t n, TYPE val, TYPE *x)\
{\
size_t i;\
\
for (i=0; i<n; i++)\
x[i] = val;\
\
return x;\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?set()-class of routines */\
/*************************************************************************/\
TYPE *PRFX ## copy(size_t n, TYPE *a, TYPE *b)\
{\
return (TYPE *)memmove((void *)b, (void *)a, sizeof(TYPE)*n);\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?AllocMatrix()-class of routines */\
/**************************************************************************/\
TYPE **PRFX ## AllocMatrix(size_t ndim1, size_t ndim2, TYPE value, char *errmsg)\
{\
gk_idx_t i, j;\
TYPE **matrix;\
\
matrix = (TYPE **)gk_malloc(ndim1*sizeof(TYPE *), errmsg);\
if (matrix == NULL) \
return NULL;\
\
for (i=0; i<ndim1; i++) { \
matrix[i] = PRFX ## smalloc(ndim2, value, errmsg);\
if (matrix[i] == NULL) { \
for (j=0; j<i; j++) \
gk_free((void **)&matrix[j], LTERM); \
return NULL; \
} \
}\
\
return matrix;\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?AllocMatrix()-class of routines */\
/**************************************************************************/\
void PRFX ## FreeMatrix(TYPE ***r_matrix, size_t ndim1, size_t ndim2)\
{\
gk_idx_t i;\
TYPE **matrix;\
\
if (*r_matrix == NULL) \
return; \
\
matrix = *r_matrix;\
\
for (i=0; i<ndim1; i++) \
gk_free((void **)&(matrix[i]), LTERM);\
\
gk_free((void **)r_matrix, LTERM);\
}\
\
\
/*************************************************************************/\
/*! The macro for gk_?SetMatrix()-class of routines */\
/**************************************************************************/\
void PRFX ## SetMatrix(TYPE **matrix, size_t ndim1, size_t ndim2, TYPE value)\
{\
gk_idx_t i, j;\
\
for (i=0; i<ndim1; i++) {\
for (j=0; j<ndim2; j++)\
matrix[i][j] = value;\
}\
}\
#define GK_MKALLOC_PROTO(PRFX, TYPE)\
TYPE *PRFX ## malloc(size_t n, char *msg);\
TYPE *PRFX ## realloc(TYPE *ptr, size_t n, char *msg);\
TYPE *PRFX ## smalloc(size_t n, TYPE ival, char *msg);\
TYPE *PRFX ## set(size_t n, TYPE val, TYPE *x);\
TYPE *PRFX ## copy(size_t n, TYPE *a, TYPE *b);\
TYPE **PRFX ## AllocMatrix(size_t ndim1, size_t ndim2, TYPE value, char *errmsg);\
void PRFX ## FreeMatrix(TYPE ***r_matrix, size_t ndim1, size_t ndim2);\
void PRFX ## SetMatrix(TYPE **matrix, size_t ndim1, size_t ndim2, TYPE value);\
#endif
+440
View File
@@ -0,0 +1,440 @@
/*!
\file gk_mkpqueue.h
\brief Templates for priority queues
\date Started 4/09/07
\author George
\version\verbatim $Id: gk_mkpqueue.h 21742 2018-01-26 16:59:15Z karypis $ \endverbatim
*/
#ifndef _GK_MKPQUEUE_H
#define _GK_MKPQUEUE_H
#define GK_MKPQUEUE(FPRFX, PQT, KVT, KT, VT, KVMALLOC, KMAX, KEY_LT)\
/*************************************************************************/\
/*! This function creates and initializes a priority queue */\
/**************************************************************************/\
PQT *FPRFX ## Create(size_t maxnodes)\
{\
PQT *queue; \
\
queue = (PQT *)gk_malloc(sizeof(PQT), "gk_pqCreate: queue");\
FPRFX ## Init(queue, maxnodes);\
\
return queue;\
}\
\
\
/*************************************************************************/\
/*! This function initializes the data structures of the priority queue */\
/**************************************************************************/\
void FPRFX ## Init(PQT *queue, size_t maxnodes)\
{\
queue->nnodes = 0;\
queue->maxnodes = maxnodes;\
\
queue->heap = KVMALLOC(maxnodes, "gk_PQInit: heap");\
queue->locator = gk_idxsmalloc(maxnodes, -1, "gk_PQInit: locator");\
}\
\
\
/*************************************************************************/\
/*! This function resets the priority queue */\
/**************************************************************************/\
void FPRFX ## Reset(PQT *queue)\
{\
ssize_t i;\
ssize_t *locator=queue->locator;\
KVT *heap=queue->heap;\
\
for (i=queue->nnodes-1; i>=0; i--)\
locator[heap[i].val] = -1;\
queue->nnodes = 0;\
}\
\
\
/*************************************************************************/\
/*! This function frees the internal datastructures of the priority queue */\
/**************************************************************************/\
void FPRFX ## Free(PQT *queue)\
{\
if (queue == NULL) return;\
gk_free((void **)&queue->heap, &queue->locator, LTERM);\
queue->maxnodes = 0;\
}\
\
\
/*************************************************************************/\
/*! This function frees the internal datastructures of the priority queue \
and the queue itself */\
/**************************************************************************/\
void FPRFX ## Destroy(PQT *queue)\
{\
if (queue == NULL) return;\
FPRFX ## Free(queue);\
gk_free((void **)&queue, LTERM);\
}\
\
\
/*************************************************************************/\
/*! This function returns the length of the queue */\
/**************************************************************************/\
size_t FPRFX ## Length(PQT *queue)\
{\
return queue->nnodes;\
}\
\
\
/*************************************************************************/\
/*! This function adds an item in the priority queue */\
/**************************************************************************/\
int FPRFX ## Insert(PQT *queue, VT node, KT key)\
{\
ssize_t i, j;\
ssize_t *locator=queue->locator;\
KVT *heap=queue->heap;\
\
ASSERT2(FPRFX ## CheckHeap(queue));\
\
ASSERT(locator[node] == -1);\
\
i = queue->nnodes++;\
while (i > 0) {\
j = (i-1)>>1;\
if (KEY_LT(key, heap[j].key)) {\
heap[i] = heap[j];\
locator[heap[i].val] = i;\
i = j;\
}\
else\
break;\
}\
ASSERT(i >= 0);\
heap[i].key = key;\
heap[i].val = node;\
locator[node] = i;\
\
ASSERT2(FPRFX ## CheckHeap(queue));\
\
return 0;\
}\
\
\
/*************************************************************************/\
/*! This function deletes an item from the priority queue */\
/**************************************************************************/\
int FPRFX ## Delete(PQT *queue, VT node)\
{\
ssize_t i, j;\
size_t nnodes;\
KT newkey, oldkey;\
ssize_t *locator=queue->locator;\
KVT *heap=queue->heap;\
\
ASSERT(locator[node] != -1);\
ASSERT(heap[locator[node]].val == node);\
\
ASSERT2(FPRFX ## CheckHeap(queue));\
\
i = locator[node];\
locator[node] = -1;\
\
if (--queue->nnodes > 0 && heap[queue->nnodes].val != node) {\
node = heap[queue->nnodes].val;\
newkey = heap[queue->nnodes].key;\
oldkey = heap[i].key;\
\
if (KEY_LT(newkey, oldkey)) { /* Filter-up */\
while (i > 0) {\
j = (i-1)>>1;\
if (KEY_LT(newkey, heap[j].key)) {\
heap[i] = heap[j];\
locator[heap[i].val] = i;\
i = j;\
}\
else\
break;\
}\
}\
else { /* Filter down */\
nnodes = queue->nnodes;\
while ((j=(i<<1)+1) < nnodes) {\
if (KEY_LT(heap[j].key, newkey)) {\
if (j+1 < nnodes && KEY_LT(heap[j+1].key, heap[j].key))\
j++;\
heap[i] = heap[j];\
locator[heap[i].val] = i;\
i = j;\
}\
else if (j+1 < nnodes && KEY_LT(heap[j+1].key, newkey)) {\
j++;\
heap[i] = heap[j];\
locator[heap[i].val] = i;\
i = j;\
}\
else\
break;\
}\
}\
\
heap[i].key = newkey;\
heap[i].val = node;\
locator[node] = i;\
}\
\
ASSERT2(FPRFX ## CheckHeap(queue));\
\
return 0;\
}\
\
\
/*************************************************************************/\
/*! This function updates the key values associated for a particular item */ \
/**************************************************************************/\
void FPRFX ## Update(PQT *queue, VT node, KT newkey)\
{\
ssize_t i, j;\
size_t nnodes;\
KT oldkey;\
ssize_t *locator=queue->locator;\
KVT *heap=queue->heap;\
\
oldkey = heap[locator[node]].key;\
if (!KEY_LT(newkey, oldkey) && !KEY_LT(oldkey, newkey)) return;\
\
ASSERT(locator[node] != -1);\
ASSERT(heap[locator[node]].val == node);\
ASSERT2(FPRFX ## CheckHeap(queue));\
\
i = locator[node];\
\
if (KEY_LT(newkey, oldkey)) { /* Filter-up */\
while (i > 0) {\
j = (i-1)>>1;\
if (KEY_LT(newkey, heap[j].key)) {\
heap[i] = heap[j];\
locator[heap[i].val] = i;\
i = j;\
}\
else\
break;\
}\
}\
else { /* Filter down */\
nnodes = queue->nnodes;\
while ((j=(i<<1)+1) < nnodes) {\
if (KEY_LT(heap[j].key, newkey)) {\
if (j+1 < nnodes && KEY_LT(heap[j+1].key, heap[j].key))\
j++;\
heap[i] = heap[j];\
locator[heap[i].val] = i;\
i = j;\
}\
else if (j+1 < nnodes && KEY_LT(heap[j+1].key, newkey)) {\
j++;\
heap[i] = heap[j];\
locator[heap[i].val] = i;\
i = j;\
}\
else\
break;\
}\
}\
\
heap[i].key = newkey;\
heap[i].val = node;\
locator[node] = i;\
\
ASSERT2(FPRFX ## CheckHeap(queue));\
\
return;\
}\
\
\
/*************************************************************************/\
/*! This function returns the item at the top of the queue and removes\
it from the priority queue */\
/**************************************************************************/\
VT FPRFX ## GetTop(PQT *queue)\
{\
ssize_t i, j;\
ssize_t *locator;\
KVT *heap;\
VT vtx, node;\
KT key;\
\
ASSERT2(FPRFX ## CheckHeap(queue));\
\
if (queue->nnodes == 0)\
return -1;\
\
queue->nnodes--;\
\
heap = queue->heap;\
locator = queue->locator;\
\
vtx = heap[0].val;\
locator[vtx] = -1;\
\
if ((i = queue->nnodes) > 0) {\
key = heap[i].key;\
node = heap[i].val;\
i = 0;\
while ((j=2*i+1) < queue->nnodes) {\
if (KEY_LT(heap[j].key, key)) {\
if (j+1 < queue->nnodes && KEY_LT(heap[j+1].key, heap[j].key))\
j = j+1;\
heap[i] = heap[j];\
locator[heap[i].val] = i;\
i = j;\
}\
else if (j+1 < queue->nnodes && KEY_LT(heap[j+1].key, key)) {\
j = j+1;\
heap[i] = heap[j];\
locator[heap[i].val] = i;\
i = j;\
}\
else\
break;\
}\
\
heap[i].key = key;\
heap[i].val = node;\
locator[node] = i;\
}\
\
ASSERT2(FPRFX ## CheckHeap(queue));\
return vtx;\
}\
\
\
/*************************************************************************/\
/*! This function returns the item at the top of the queue. The item is not\
deleted from the queue. */\
/**************************************************************************/\
VT FPRFX ## SeeTopVal(PQT *queue)\
{\
return (queue->nnodes == 0 ? -1 : queue->heap[0].val);\
}\
\
\
/*************************************************************************/\
/*! This function returns the key of the top item. The item is not\
deleted from the queue. */\
/**************************************************************************/\
KT FPRFX ## SeeTopKey(PQT *queue)\
{\
return (queue->nnodes == 0 ? KMAX : queue->heap[0].key);\
}\
\
\
/*************************************************************************/\
/*! This function returns the key of a specific item */\
/**************************************************************************/\
KT FPRFX ## SeeKey(PQT *queue, VT node)\
{\
ssize_t *locator;\
KVT *heap;\
\
heap = queue->heap;\
locator = queue->locator;\
\
return heap[locator[node]].key;\
}\
\
\
/*************************************************************************/\
/*! This function returns the first item in a breadth-first traversal of\
the heap whose key is less than maxwgt. This function is here due to\
hMETIS and is not general!*/\
/**************************************************************************/\
/*\
VT FPRFX ## SeeConstraintTop(PQT *queue, KT maxwgt, KT *wgts)\
{\
ssize_t i;\
\
if (queue->nnodes == 0)\
return -1;\
\
if (maxwgt <= 1000)\
return FPRFX ## SeeTopVal(queue);\
\
for (i=0; i<queue->nnodes; i++) {\
if (queue->heap[i].key > 0) {\
if (wgts[queue->heap[i].val] <= maxwgt)\
return queue->heap[i].val;\
}\
else {\
if (queue->heap[i/2].key <= 0)\
break;\
}\
}\
\
return queue->heap[0].val;\
\
}\
*/\
\
\
/*************************************************************************/\
/*! This functions checks the consistency of the heap */\
/**************************************************************************/\
int FPRFX ## CheckHeap(PQT *queue)\
{\
ssize_t i, j;\
size_t nnodes;\
ssize_t *locator;\
KVT *heap;\
\
heap = queue->heap;\
locator = queue->locator;\
nnodes = queue->nnodes;\
\
if (nnodes == 0)\
return 1;\
\
ASSERT(locator[heap[0].val] == 0);\
for (i=1; i<nnodes; i++) {\
ASSERT(locator[heap[i].val] == i);\
ASSERT(!KEY_LT(heap[i].key, heap[(i-1)/2].key));\
}\
for (i=1; i<nnodes; i++)\
ASSERT(!KEY_LT(heap[i].key, heap[0].key));\
\
for (j=i=0; i<queue->maxnodes; i++) {\
if (locator[i] != -1)\
j++;\
}\
ASSERTP(j == nnodes, ("%jd %jd\n", (intmax_t)j, (intmax_t)nnodes));\
\
return 1;\
}\
#define GK_MKPQUEUE_PROTO(FPRFX, PQT, KT, VT)\
PQT * FPRFX ## Create(size_t maxnodes);\
void FPRFX ## Init(PQT *queue, size_t maxnodes);\
void FPRFX ## Reset(PQT *queue);\
void FPRFX ## Free(PQT *queue);\
void FPRFX ## Destroy(PQT *queue);\
size_t FPRFX ## Length(PQT *queue);\
int FPRFX ## Insert(PQT *queue, VT node, KT key);\
int FPRFX ## Delete(PQT *queue, VT node);\
void FPRFX ## Update(PQT *queue, VT node, KT newkey);\
VT FPRFX ## GetTop(PQT *queue);\
VT FPRFX ## SeeTopVal(PQT *queue);\
KT FPRFX ## SeeTopKey(PQT *queue);\
KT FPRFX ## SeeKey(PQT *queue, VT node);\
VT FPRFX ## SeeConstraintTop(PQT *queue, KT maxwgt, KT *wgts);\
int FPRFX ## CheckHeap(PQT *queue);\
/* This is how these macros are used
GK_MKPQUEUE(gk_dkvPQ, gk_dkvPQ_t, double, gk_idx_t, gk_dkvmalloc, DBL_MAX)
GK_MKPQUEUE_PROTO(gk_dkvPQ, gk_dkvPQ_t, double, gk_idx_t)
*/
#endif
+215
View File
@@ -0,0 +1,215 @@
/*!
\file gk_mkpqueue2.h
\brief Templates for priority queues that do not utilize locators and as such
they can use different types of values.
\date Started 4/09/07
\author George
\version\verbatim $Id: gk_mkpqueue2.h 13005 2012-10-23 22:34:36Z karypis $ \endverbatim
*/
#ifndef _GK_MKPQUEUE2_H
#define _GK_MKPQUEUE2_H
#define GK_MKPQUEUE2(FPRFX, PQT, KT, VT, KMALLOC, VMALLOC, KMAX, KEY_LT)\
/*************************************************************************/\
/*! This function creates and initializes a priority queue */\
/**************************************************************************/\
PQT *FPRFX ## Create2(ssize_t maxnodes)\
{\
PQT *queue; \
\
if ((queue = (PQT *)gk_malloc(sizeof(PQT), "gk_pqCreate2: queue")) != NULL) {\
memset(queue, 0, sizeof(PQT));\
queue->nnodes = 0;\
queue->maxnodes = maxnodes;\
queue->keys = KMALLOC(maxnodes, "gk_pqCreate2: keys");\
queue->vals = VMALLOC(maxnodes, "gk_pqCreate2: vals");\
\
if (queue->keys == NULL || queue->vals == NULL)\
gk_free((void **)&queue->keys, &queue->vals, &queue, LTERM);\
}\
\
return queue;\
}\
\
\
/*************************************************************************/\
/*! This function resets the priority queue */\
/**************************************************************************/\
void FPRFX ## Reset2(PQT *queue)\
{\
queue->nnodes = 0;\
}\
\
\
/*************************************************************************/\
/*! This function frees the internal datastructures of the priority queue */\
/**************************************************************************/\
void FPRFX ## Destroy2(PQT **r_queue)\
{\
PQT *queue = *r_queue; \
if (queue == NULL) return;\
gk_free((void **)&queue->keys, &queue->vals, &queue, LTERM);\
*r_queue = NULL;\
}\
\
\
/*************************************************************************/\
/*! This function returns the length of the queue */\
/**************************************************************************/\
size_t FPRFX ## Length2(PQT *queue)\
{\
return queue->nnodes;\
}\
\
\
/*************************************************************************/\
/*! This function adds an item in the priority queue. */\
/**************************************************************************/\
int FPRFX ## Insert2(PQT *queue, VT val, KT key)\
{\
ssize_t i, j;\
KT *keys=queue->keys;\
VT *vals=queue->vals;\
\
ASSERT2(FPRFX ## CheckHeap2(queue));\
\
if (queue->nnodes == queue->maxnodes) \
return 0;\
\
ASSERT2(FPRFX ## CheckHeap2(queue));\
\
i = queue->nnodes++;\
while (i > 0) {\
j = (i-1)>>1;\
if (KEY_LT(key, keys[j])) {\
keys[i] = keys[j];\
vals[i] = vals[j];\
i = j;\
}\
else\
break;\
}\
ASSERT(i >= 0);\
keys[i] = key;\
vals[i] = val;\
\
ASSERT2(FPRFX ## CheckHeap2(queue));\
\
return 1;\
}\
\
\
/*************************************************************************/\
/*! This function returns the item at the top of the queue and removes\
it from the priority queue */\
/**************************************************************************/\
int FPRFX ## GetTop2(PQT *queue, VT *r_val)\
{\
ssize_t i, j;\
KT key, *keys=queue->keys;\
VT val, *vals=queue->vals;\
\
ASSERT2(FPRFX ## CheckHeap2(queue));\
\
if (queue->nnodes == 0)\
return 0;\
\
queue->nnodes--;\
\
*r_val = vals[0];\
\
if ((i = queue->nnodes) > 0) {\
key = keys[i];\
val = vals[i];\
i = 0;\
while ((j=2*i+1) < queue->nnodes) {\
if (KEY_LT(keys[j], key)) {\
if (j+1 < queue->nnodes && KEY_LT(keys[j+1], keys[j]))\
j = j+1;\
keys[i] = keys[j];\
vals[i] = vals[j];\
i = j;\
}\
else if (j+1 < queue->nnodes && KEY_LT(keys[j+1], key)) {\
j = j+1;\
keys[i] = keys[j];\
vals[i] = vals[j];\
i = j;\
}\
else\
break;\
}\
\
keys[i] = key;\
vals[i] = val;\
}\
\
ASSERT2(FPRFX ## CheckHeap2(queue));\
\
return 1;\
}\
\
\
/*************************************************************************/\
/*! This function returns the item at the top of the queue. The item is not\
deleted from the queue. */\
/**************************************************************************/\
int FPRFX ## SeeTopVal2(PQT *queue, VT *r_val)\
{\
if (queue->nnodes == 0) \
return 0;\
\
*r_val = queue->vals[0];\
\
return 1;\
}\
\
\
/*************************************************************************/\
/*! This function returns the key of the top item. The item is not\
deleted from the queue. */\
/**************************************************************************/\
KT FPRFX ## SeeTopKey2(PQT *queue)\
{\
return (queue->nnodes == 0 ? KMAX : queue->keys[0]);\
}\
\
\
/*************************************************************************/\
/*! This functions checks the consistency of the heap */\
/**************************************************************************/\
int FPRFX ## CheckHeap2(PQT *queue)\
{\
ssize_t i;\
KT *keys=queue->keys;\
\
if (queue->nnodes == 0)\
return 1;\
\
for (i=1; i<queue->nnodes; i++) {\
ASSERT(!KEY_LT(keys[i], keys[(i-1)/2]));\
}\
for (i=1; i<queue->nnodes; i++)\
ASSERT(!KEY_LT(keys[i], keys[0]));\
\
return 1;\
}\
#define GK_MKPQUEUE2_PROTO(FPRFX, PQT, KT, VT)\
PQT * FPRFX ## Create2(ssize_t maxnodes);\
void FPRFX ## Reset2(PQT *queue);\
void FPRFX ## Destroy2(PQT **r_queue);\
size_t FPRFX ## Length2(PQT *queue);\
int FPRFX ## Insert2(PQT *queue, VT node, KT key);\
int FPRFX ## GetTop2(PQT *queue, VT *r_val);\
int FPRFX ## SeeTopVal2(PQT *queue, VT *r_val);\
KT FPRFX ## SeeTopKey2(PQT *queue);\
int FPRFX ## CheckHeap2(PQT *queue);\
#endif
+123
View File
@@ -0,0 +1,123 @@
/*!
\file
\brief Templates for portable random number generation
\date Started 5/17/07
\author George
\version\verbatim $Id: gk_mkrandom.h 10711 2011-08-31 22:23:04Z karypis $ \endverbatim
*/
#ifndef _GK_MKRANDOM_H
#define _GK_MKRANDOM_H
/*************************************************************************/\
/*! The generator for the rand() related routines. \
\params RNGT the datatype that defines the range of values over which\
random numbers will be generated\
\params VALT the datatype that defines the contents of the array to \
be permuted by randArrayPermute() \
\params FPRFX the function prefix \
*/\
/**************************************************************************/\
#define GK_MKRANDOM(FPRFX, RNGT, VALT)\
/*************************************************************************/\
/*! Initializes the generator */ \
/**************************************************************************/\
void FPRFX ## srand(RNGT seed) \
{\
gk_randinit((uint64_t) seed);\
}\
\
\
/*************************************************************************/\
/*! Returns a random number */ \
/**************************************************************************/\
RNGT FPRFX ## rand() \
{\
if (sizeof(RNGT) <= sizeof(int32_t)) \
return (RNGT)gk_randint32(); \
else \
return (RNGT)gk_randint64(); \
}\
\
\
/*************************************************************************/\
/*! Returns a random number between [0, max) */ \
/**************************************************************************/\
RNGT FPRFX ## randInRange(RNGT max) \
{\
return (RNGT)((FPRFX ## rand())%max); \
}\
\
\
/*************************************************************************/\
/*! Randomly permutes the elements of an array p[]. \
flag == 1, p[i] = i prior to permutation, \
flag == 0, p[] is not initialized. */\
/**************************************************************************/\
void FPRFX ## randArrayPermute(RNGT n, VALT *p, RNGT nshuffles, int flag)\
{\
RNGT i, u, v;\
VALT tmp;\
\
if (flag == 1) {\
for (i=0; i<n; i++)\
p[i] = (VALT)i;\
}\
\
if (n < 10) {\
for (i=0; i<n; i++) {\
v = FPRFX ## randInRange(n);\
u = FPRFX ## randInRange(n);\
gk_SWAP(p[v], p[u], tmp);\
}\
}\
else {\
for (i=0; i<nshuffles; i++) {\
v = FPRFX ## randInRange(n-3);\
u = FPRFX ## randInRange(n-3);\
/*gk_SWAP(p[v+0], p[u+0], tmp);*/\
/*gk_SWAP(p[v+1], p[u+1], tmp);*/\
/*gk_SWAP(p[v+2], p[u+2], tmp);*/\
/*gk_SWAP(p[v+3], p[u+3], tmp);*/\
gk_SWAP(p[v+0], p[u+2], tmp);\
gk_SWAP(p[v+1], p[u+3], tmp);\
gk_SWAP(p[v+2], p[u+0], tmp);\
gk_SWAP(p[v+3], p[u+1], tmp);\
}\
}\
}\
\
\
/*************************************************************************/\
/*! Randomly permutes the elements of an array p[]. \
flag == 1, p[i] = i prior to permutation, \
flag == 0, p[] is not initialized. */\
/**************************************************************************/\
void FPRFX ## randArrayPermuteFine(RNGT n, VALT *p, int flag)\
{\
RNGT i, v;\
VALT tmp;\
\
if (flag == 1) {\
for (i=0; i<n; i++)\
p[i] = (VALT)i;\
}\
\
for (i=0; i<n; i++) {\
v = FPRFX ## randInRange(n);\
gk_SWAP(p[i], p[v], tmp);\
}\
}\
#define GK_MKRANDOM_PROTO(FPRFX, RNGT, VALT)\
void FPRFX ## srand(RNGT seed); \
RNGT FPRFX ## rand(); \
RNGT FPRFX ## randInRange(RNGT max); \
void FPRFX ## randArrayPermute(RNGT n, VALT *p, RNGT nshuffles, int flag);\
void FPRFX ## randArrayPermuteFine(RNGT n, VALT *p, int flag);\
#endif
+271
View File
@@ -0,0 +1,271 @@
/*!
\file gk_mksort.h
\brief Templates for the qsort routine
\date Started 3/28/07
\author George
\version\verbatim $Id: gk_mksort.h 21051 2017-05-25 04:36:14Z karypis $ \endverbatim
*/
#ifndef _GK_MKSORT_H_
#define _GK_MKSORT_H_
/* Adopted from GNU glibc by Mjt.
* See stdlib/qsort.c in glibc */
/* Copyright (C) 1991, 1992, 1996, 1997, 1999 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Written by Douglas C. Schmidt (schmidt@ics.uci.edu).
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
/* in-line qsort implementation. Differs from traditional qsort() routine
* in that it is a macro, not a function, and instead of passing an address
* of a comparision routine to the function, it is possible to inline
* comparision routine, thus speed up sorting alot.
*
* Usage:
* #include "iqsort.h"
* #define islt(a,b) (strcmp((*a),(*b))<0)
* char *arr[];
* int n;
* GKQSORT(char*, arr, n, islt);
*
* The "prototype" and 4 arguments are:
* GKQSORT(TYPE,BASE,NELT,ISLT)
* 1) type of each element, TYPE,
* 2) address of the beginning of the array, of type TYPE*,
* 3) number of elements in the array, and
* 4) comparision routine.
* Array pointer and number of elements are referenced only once.
* This is similar to a call
* qsort(BASE,NELT,sizeof(TYPE),ISLT)
* with the difference in last parameter.
* Note the islt macro/routine (it receives pointers to two elements):
* the only condition of interest is whenever one element is less than
* another, no other conditions (greather than, equal to etc) are tested.
* So, for example, to define integer sort, use:
* #define islt(a,b) ((*a)<(*b))
* GKQSORT(int, arr, n, islt)
*
* The macro could be used to implement a sorting function (see examples
* below), or to implement the sorting algorithm inline. That is, either
* create a sorting function and use it whenever you want to sort something,
* or use GKQSORT() macro directly instead a call to such routine. Note that
* the macro expands to quite some code (compiled size of int qsort on x86
* is about 700..800 bytes).
*
* Using this macro directly it isn't possible to implement traditional
* qsort() routine, because the macro assumes sizeof(element) == sizeof(TYPE),
* while qsort() allows element size to be different.
*
* Several ready-to-use examples:
*
* Sorting array of integers:
* void int_qsort(int *arr, unsigned n) {
* #define int_lt(a,b) ((*a)<(*b))
* GKQSORT(int, arr, n, int_lt);
* }
*
* Sorting array of string pointers:
* void str_qsort(char *arr[], unsigned n) {
* #define str_lt(a,b) (strcmp((*a),(*b)) < 0)
* GKQSORT(char*, arr, n, str_lt);
* }
*
* Sorting array of structures:
*
* struct elt {
* int key;
* ...
* };
* void elt_qsort(struct elt *arr, unsigned n) {
* #define elt_lt(a,b) ((a)->key < (b)->key)
* GKQSORT(struct elt, arr, n, elt_lt);
* }
*
* And so on.
*/
/* Swap two items pointed to by A and B using temporary buffer t. */
#define _GKQSORT_SWAP(a, b, t) ((void)((t = *a), (*a = *b), (*b = t)))
/* Discontinue quicksort algorithm when partition gets below this size. */
#define _GKQSORT_MAX_THRESH 8
/* The next 4 #defines implement a very fast in-line stack abstraction. */
#define _GKQSORT_STACK_SIZE (8 * sizeof(size_t))
#define _GKQSORT_PUSH(top, low, high) (((top->_lo = (low)), (top->_hi = (high)), ++top))
#define _GKQSORT_POP(low, high, top) ((--top, (low = top->_lo), (high = top->_hi)))
#define _GKQSORT_STACK_NOT_EMPTY (_stack < _top)
/* The main code starts here... */
#define GK_MKQSORT(GKQSORT_TYPE,GKQSORT_BASE,GKQSORT_NELT,GKQSORT_LT) \
{ \
GKQSORT_TYPE *const _base = (GKQSORT_BASE); \
const size_t _elems = (GKQSORT_NELT); \
GKQSORT_TYPE _hold; \
\
if (_elems < 1) \
return; \
\
/* Don't declare two variables of type GKQSORT_TYPE in a single \
* statement: eg `TYPE a, b;', in case if TYPE is a pointer, \
* expands to `type* a, b;' wich isn't what we want. \
*/ \
\
if (_elems > _GKQSORT_MAX_THRESH) { \
GKQSORT_TYPE *_lo = _base; \
GKQSORT_TYPE *_hi = _lo + _elems - 1; \
struct { \
GKQSORT_TYPE *_hi; GKQSORT_TYPE *_lo; \
} _stack[_GKQSORT_STACK_SIZE], *_top = _stack + 1; \
\
while (_GKQSORT_STACK_NOT_EMPTY) { \
GKQSORT_TYPE *_left_ptr; GKQSORT_TYPE *_right_ptr; \
\
/* Select median value from among LO, MID, and HI. Rearrange \
LO and HI so the three values are sorted. This lowers the \
probability of picking a pathological pivot value and \
skips a comparison for both the LEFT_PTR and RIGHT_PTR in \
the while loops. */ \
\
GKQSORT_TYPE *_mid = _lo + ((_hi - _lo) >> 1); \
\
if (GKQSORT_LT (_mid, _lo)) \
_GKQSORT_SWAP (_mid, _lo, _hold); \
if (GKQSORT_LT (_hi, _mid)) \
_GKQSORT_SWAP (_mid, _hi, _hold); \
else \
goto _jump_over; \
if (GKQSORT_LT (_mid, _lo)) \
_GKQSORT_SWAP (_mid, _lo, _hold); \
_jump_over:; \
\
_left_ptr = _lo + 1; \
_right_ptr = _hi - 1; \
\
/* Here's the famous ``collapse the walls'' section of quicksort. \
Gotta like those tight inner loops! They are the main reason \
that this algorithm runs much faster than others. */ \
do { \
while (GKQSORT_LT (_left_ptr, _mid)) \
++_left_ptr; \
\
while (GKQSORT_LT (_mid, _right_ptr)) \
--_right_ptr; \
\
if (_left_ptr < _right_ptr) { \
_GKQSORT_SWAP (_left_ptr, _right_ptr, _hold); \
if (_mid == _left_ptr) \
_mid = _right_ptr; \
else if (_mid == _right_ptr) \
_mid = _left_ptr; \
++_left_ptr; \
--_right_ptr; \
} \
else if (_left_ptr == _right_ptr) { \
++_left_ptr; \
--_right_ptr; \
break; \
} \
} while (_left_ptr <= _right_ptr); \
\
/* Set up pointers for next iteration. First determine whether \
left and right partitions are below the threshold size. If so, \
ignore one or both. Otherwise, push the larger partition's \
bounds on the stack and continue sorting the smaller one. */ \
\
if (_right_ptr - _lo <= _GKQSORT_MAX_THRESH) { \
if (_hi - _left_ptr <= _GKQSORT_MAX_THRESH) \
/* Ignore both small partitions. */ \
_GKQSORT_POP (_lo, _hi, _top); \
else \
/* Ignore small left partition. */ \
_lo = _left_ptr; \
} \
else if (_hi - _left_ptr <= _GKQSORT_MAX_THRESH) \
/* Ignore small right partition. */ \
_hi = _right_ptr; \
else if (_right_ptr - _lo > _hi - _left_ptr) { \
/* Push larger left partition indices. */ \
_GKQSORT_PUSH (_top, _lo, _right_ptr); \
_lo = _left_ptr; \
} \
else { \
/* Push larger right partition indices. */ \
_GKQSORT_PUSH (_top, _left_ptr, _hi); \
_hi = _right_ptr; \
} \
} \
} \
\
/* Once the BASE array is partially sorted by quicksort the rest \
is completely sorted using insertion sort, since this is efficient \
for partitions below MAX_THRESH size. BASE points to the \
beginning of the array to sort, and END_PTR points at the very \
last element in the array (*not* one beyond it!). */ \
\
{ \
GKQSORT_TYPE *const _end_ptr = _base + _elems - 1; \
GKQSORT_TYPE *_tmp_ptr = _base; \
register GKQSORT_TYPE *_run_ptr; \
GKQSORT_TYPE *_thresh; \
\
_thresh = _base + _GKQSORT_MAX_THRESH; \
if (_thresh > _end_ptr) \
_thresh = _end_ptr; \
\
/* Find smallest element in first threshold and place it at the \
array's beginning. This is the smallest array element, \
and the operation speeds up insertion sort's inner loop. */ \
\
for (_run_ptr = _tmp_ptr + 1; _run_ptr <= _thresh; ++_run_ptr) \
if (GKQSORT_LT (_run_ptr, _tmp_ptr)) \
_tmp_ptr = _run_ptr; \
\
if (_tmp_ptr != _base) \
_GKQSORT_SWAP (_tmp_ptr, _base, _hold); \
\
/* Insertion sort, running from left-hand-side \
* up to right-hand-side. */ \
\
_run_ptr = _base + 1; \
while (++_run_ptr <= _end_ptr) { \
_tmp_ptr = _run_ptr - 1; \
while (GKQSORT_LT (_run_ptr, _tmp_ptr)) \
--_tmp_ptr; \
\
++_tmp_ptr; \
if (_tmp_ptr != _run_ptr) { \
GKQSORT_TYPE *_trav = _run_ptr + 1; \
while (--_trav >= _run_ptr) { \
GKQSORT_TYPE *_hi; GKQSORT_TYPE *_lo; \
_hold = *_trav; \
\
for (_hi = _lo = _trav; --_lo >= _tmp_ptr; _hi = _lo) \
*_hi = *_lo; \
*_hi = _hold; \
} \
} \
} \
} \
\
}
#endif
+40
View File
@@ -0,0 +1,40 @@
/*!
\file
\brief Templates for various utility routines
\date Started 5/28/07
\author George
\version\verbatim $Id: gk_mkutils.h 10711 2011-08-31 22:23:04Z karypis $ \endverbatim
*/
#ifndef _GK_MKUTILS_H_
#define _GK_MKUTILS_H_
#define GK_MKARRAY2CSR(PRFX, TYPE)\
/*************************************************************************/\
/*! The macro for gk_?array2csr() routine */\
/**************************************************************************/\
void PRFX ## array2csr(TYPE n, TYPE range, TYPE *array, TYPE *ptr, TYPE *ind)\
{\
TYPE i;\
\
for (i=0; i<=range; i++)\
ptr[i] = 0;\
\
for (i=0; i<n; i++)\
ptr[array[i]]++;\
\
/* Compute the ptr, ind structure */\
MAKECSR(i, range, ptr);\
for (i=0; i<n; i++)\
ind[ptr[array[i]]++] = i;\
SHIFTCSR(i, range, ptr);\
}
#define GK_MKARRAY2CSR_PROTO(PRFX, TYPE)\
void PRFX ## array2csr(TYPE n, TYPE range, TYPE *array, TYPE *ptr, TYPE *ind);\
#endif
+301
View File
@@ -0,0 +1,301 @@
// ISO C9x compliant inttypes.h for Microsoft Visual Studio
// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
//
// Copyright (c) 2006 Alexander Chemeris
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. The name of the author may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef _MSC_VER // [
#error "Use this header only with Microsoft Visual C++ compilers!"
#endif // _MSC_VER ]
#ifndef _MSC_INTTYPES_H_ // [
#define _MSC_INTTYPES_H_
#if _MSC_VER > 1000
#pragma once
#endif
#include "gk_ms_stdint.h"
// 7.8 Format conversion of integer types
typedef struct {
intmax_t quot;
intmax_t rem;
} imaxdiv_t;
// 7.8.1 Macros for format specifiers
// The fprintf macros for signed integers are:
#define PRId8 "d"
#define PRIi8 "i"
#define PRIdLEAST8 "d"
#define PRIiLEAST8 "i"
#define PRIdFAST8 "d"
#define PRIiFAST8 "i"
#define PRId16 "hd"
#define PRIi16 "hi"
#define PRIdLEAST16 "hd"
#define PRIiLEAST16 "hi"
#define PRIdFAST16 "hd"
#define PRIiFAST16 "hi"
#define PRId32 "I32d"
#define PRIi32 "I32i"
#define PRIdLEAST32 "I32d"
#define PRIiLEAST32 "I32i"
#define PRIdFAST32 "I32d"
#define PRIiFAST32 "I32i"
#define PRId64 "I64d"
#define PRIi64 "I64i"
#define PRIdLEAST64 "I64d"
#define PRIiLEAST64 "I64i"
#define PRIdFAST64 "I64d"
#define PRIiFAST64 "I64i"
#define PRIdMAX "I64d"
#define PRIiMAX "I64i"
#define PRIdPTR "Id"
#define PRIiPTR "Ii"
// The fprintf macros for unsigned integers are:
#define PRIo8 "o"
#define PRIu8 "u"
#define PRIx8 "x"
#define PRIX8 "X"
#define PRIoLEAST8 "o"
#define PRIuLEAST8 "u"
#define PRIxLEAST8 "x"
#define PRIXLEAST8 "X"
#define PRIoFAST8 "o"
#define PRIuFAST8 "u"
#define PRIxFAST8 "x"
#define PRIXFAST8 "X"
#define PRIo16 "ho"
#define PRIu16 "hu"
#define PRIx16 "hx"
#define PRIX16 "hX"
#define PRIoLEAST16 "ho"
#define PRIuLEAST16 "hu"
#define PRIxLEAST16 "hx"
#define PRIXLEAST16 "hX"
#define PRIoFAST16 "ho"
#define PRIuFAST16 "hu"
#define PRIxFAST16 "hx"
#define PRIXFAST16 "hX"
#define PRIo32 "I32o"
#define PRIu32 "I32u"
#define PRIx32 "I32x"
#define PRIX32 "I32X"
#define PRIoLEAST32 "I32o"
#define PRIuLEAST32 "I32u"
#define PRIxLEAST32 "I32x"
#define PRIXLEAST32 "I32X"
#define PRIoFAST32 "I32o"
#define PRIuFAST32 "I32u"
#define PRIxFAST32 "I32x"
#define PRIXFAST32 "I32X"
#define PRIo64 "I64o"
#define PRIu64 "I64u"
#define PRIx64 "I64x"
#define PRIX64 "I64X"
#define PRIoLEAST64 "I64o"
#define PRIuLEAST64 "I64u"
#define PRIxLEAST64 "I64x"
#define PRIXLEAST64 "I64X"
#define PRIoFAST64 "I64o"
#define PRIuFAST64 "I64u"
#define PRIxFAST64 "I64x"
#define PRIXFAST64 "I64X"
#define PRIoMAX "I64o"
#define PRIuMAX "I64u"
#define PRIxMAX "I64x"
#define PRIXMAX "I64X"
#define PRIoPTR "Io"
#define PRIuPTR "Iu"
#define PRIxPTR "Ix"
#define PRIXPTR "IX"
// The fscanf macros for signed integers are:
#define SCNd8 "d"
#define SCNi8 "i"
#define SCNdLEAST8 "d"
#define SCNiLEAST8 "i"
#define SCNdFAST8 "d"
#define SCNiFAST8 "i"
#define SCNd16 "hd"
#define SCNi16 "hi"
#define SCNdLEAST16 "hd"
#define SCNiLEAST16 "hi"
#define SCNdFAST16 "hd"
#define SCNiFAST16 "hi"
#define SCNd32 "ld"
#define SCNi32 "li"
#define SCNdLEAST32 "ld"
#define SCNiLEAST32 "li"
#define SCNdFAST32 "ld"
#define SCNiFAST32 "li"
#define SCNd64 "I64d"
#define SCNi64 "I64i"
#define SCNdLEAST64 "I64d"
#define SCNiLEAST64 "I64i"
#define SCNdFAST64 "I64d"
#define SCNiFAST64 "I64i"
#define SCNdMAX "I64d"
#define SCNiMAX "I64i"
#ifdef _WIN64 // [
# define SCNdPTR "I64d"
# define SCNiPTR "I64i"
#else // _WIN64 ][
# define SCNdPTR "ld"
# define SCNiPTR "li"
#endif // _WIN64 ]
// The fscanf macros for unsigned integers are:
#define SCNo8 "o"
#define SCNu8 "u"
#define SCNx8 "x"
#define SCNX8 "X"
#define SCNoLEAST8 "o"
#define SCNuLEAST8 "u"
#define SCNxLEAST8 "x"
#define SCNXLEAST8 "X"
#define SCNoFAST8 "o"
#define SCNuFAST8 "u"
#define SCNxFAST8 "x"
#define SCNXFAST8 "X"
#define SCNo16 "ho"
#define SCNu16 "hu"
#define SCNx16 "hx"
#define SCNX16 "hX"
#define SCNoLEAST16 "ho"
#define SCNuLEAST16 "hu"
#define SCNxLEAST16 "hx"
#define SCNXLEAST16 "hX"
#define SCNoFAST16 "ho"
#define SCNuFAST16 "hu"
#define SCNxFAST16 "hx"
#define SCNXFAST16 "hX"
#define SCNo32 "lo"
#define SCNu32 "lu"
#define SCNx32 "lx"
#define SCNX32 "lX"
#define SCNoLEAST32 "lo"
#define SCNuLEAST32 "lu"
#define SCNxLEAST32 "lx"
#define SCNXLEAST32 "lX"
#define SCNoFAST32 "lo"
#define SCNuFAST32 "lu"
#define SCNxFAST32 "lx"
#define SCNXFAST32 "lX"
#define SCNo64 "I64o"
#define SCNu64 "I64u"
#define SCNx64 "I64x"
#define SCNX64 "I64X"
#define SCNoLEAST64 "I64o"
#define SCNuLEAST64 "I64u"
#define SCNxLEAST64 "I64x"
#define SCNXLEAST64 "I64X"
#define SCNoFAST64 "I64o"
#define SCNuFAST64 "I64u"
#define SCNxFAST64 "I64x"
#define SCNXFAST64 "I64X"
#define SCNoMAX "I64o"
#define SCNuMAX "I64u"
#define SCNxMAX "I64x"
#define SCNXMAX "I64X"
#ifdef _WIN64 // [
# define SCNoPTR "I64o"
# define SCNuPTR "I64u"
# define SCNxPTR "I64x"
# define SCNXPTR "I64X"
#else // _WIN64 ][
# define SCNoPTR "lo"
# define SCNuPTR "lu"
# define SCNxPTR "lx"
# define SCNXPTR "lX"
#endif // _WIN64 ]
// 7.8.2 Functions for greatest-width integer types
// 7.8.2.1 The imaxabs function
#define imaxabs _abs64
// 7.8.2.2 The imaxdiv function
// This is modified version of div() function from Microsoft's div.c found
// in %MSVC.NET%\crt\src\div.c
#ifdef STATIC_IMAXDIV // [
static
#else // STATIC_IMAXDIV ][
_inline
#endif // STATIC_IMAXDIV ]
imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom)
{
imaxdiv_t result;
result.quot = numer / denom;
result.rem = numer % denom;
if (numer < 0 && result.rem > 0) {
// did division wrong; must fix up
++result.quot;
result.rem -= denom;
}
return result;
}
// 7.8.2.3 The strtoimax and strtoumax functions
#define strtoimax _strtoi64
#define strtoumax _strtoui64
// 7.8.2.4 The wcstoimax and wcstoumax functions
#define wcstoimax _wcstoi64
#define wcstoumax _wcstoui64
#endif // _MSC_INTTYPES_H_ ]
+22
View File
@@ -0,0 +1,22 @@
#ifndef _MSC_VER // [
#error "Use this header only with Microsoft Visual C++ compilers!"
#endif // _MSC_VER ]
#ifndef _MS_STAT_H_
#define _MS_STAT_H_
#if _MSC_VER > 1000
#pragma once
#endif
#include <sys/stat.h>
/* Test macros for file types. */
#define __S_ISTYPE(mode, mask) (((mode) & S_IFMT) == (mask))
#define S_ISDIR(mode) __S_ISTYPE((mode), S_IFDIR)
#define S_ISCHR(mode) __S_ISTYPE((mode), S_IFCHR)
#define S_ISBLK(mode) __S_ISTYPE((mode), S_IFBLK)
#define S_ISREG(mode) __S_ISTYPE((mode), S_IFREG)
#endif
+222
View File
@@ -0,0 +1,222 @@
// ISO C9x compliant stdint.h for Microsoft Visual Studio
// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
//
// Copyright (c) 2006 Alexander Chemeris
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. The name of the author may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef _MSC_VER // [
#error "Use this header only with Microsoft Visual C++ compilers!"
#endif // _MSC_VER ]
#ifndef _MSC_STDINT_H_ // [
#define _MSC_STDINT_H_
#if _MSC_VER > 1000
#pragma once
#endif
#include <limits.h>
// For Visual Studio 6 in C++ mode wrap <wchar.h> include with 'extern "C++" {}'
// or compiler give many errors like this:
// error C2733: second C linkage of overloaded function 'wmemchr' not allowed
#if (_MSC_VER < 1300) && defined(__cplusplus)
extern "C++" {
#endif
# include <wchar.h>
#if (_MSC_VER < 1300) && defined(__cplusplus)
}
#endif
// 7.18.1 Integer types
// 7.18.1.1 Exact-width integer types
typedef __int8 int8_t;
typedef __int16 int16_t;
typedef __int32 int32_t;
typedef __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
// 7.18.1.2 Minimum-width integer types
typedef int8_t int_least8_t;
typedef int16_t int_least16_t;
typedef int32_t int_least32_t;
typedef int64_t int_least64_t;
typedef uint8_t uint_least8_t;
typedef uint16_t uint_least16_t;
typedef uint32_t uint_least32_t;
typedef uint64_t uint_least64_t;
// 7.18.1.3 Fastest minimum-width integer types
typedef int8_t int_fast8_t;
typedef int16_t int_fast16_t;
typedef int32_t int_fast32_t;
typedef int64_t int_fast64_t;
typedef uint8_t uint_fast8_t;
typedef uint16_t uint_fast16_t;
typedef uint32_t uint_fast32_t;
typedef uint64_t uint_fast64_t;
// 7.18.1.4 Integer types capable of holding object pointers
#ifdef _WIN64 // [
typedef __int64 intptr_t;
typedef unsigned __int64 uintptr_t;
#else // _WIN64 ][
typedef int intptr_t;
typedef unsigned int uintptr_t;
#endif // _WIN64 ]
// 7.18.1.5 Greatest-width integer types
typedef int64_t intmax_t;
typedef uint64_t uintmax_t;
// 7.18.2 Limits of specified-width integer types
#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259
// 7.18.2.1 Limits of exact-width integer types
#define INT8_MIN ((int8_t)_I8_MIN)
#define INT8_MAX _I8_MAX
#define INT16_MIN ((int16_t)_I16_MIN)
#define INT16_MAX _I16_MAX
#define INT32_MIN ((int32_t)_I32_MIN)
#define INT32_MAX _I32_MAX
#define INT64_MIN ((int64_t)_I64_MIN)
#define INT64_MAX _I64_MAX
#define UINT8_MAX _UI8_MAX
#define UINT16_MAX _UI16_MAX
#define UINT32_MAX _UI32_MAX
#define UINT64_MAX _UI64_MAX
// 7.18.2.2 Limits of minimum-width integer types
#define INT_LEAST8_MIN INT8_MIN
#define INT_LEAST8_MAX INT8_MAX
#define INT_LEAST16_MIN INT16_MIN
#define INT_LEAST16_MAX INT16_MAX
#define INT_LEAST32_MIN INT32_MIN
#define INT_LEAST32_MAX INT32_MAX
#define INT_LEAST64_MIN INT64_MIN
#define INT_LEAST64_MAX INT64_MAX
#define UINT_LEAST8_MAX UINT8_MAX
#define UINT_LEAST16_MAX UINT16_MAX
#define UINT_LEAST32_MAX UINT32_MAX
#define UINT_LEAST64_MAX UINT64_MAX
// 7.18.2.3 Limits of fastest minimum-width integer types
#define INT_FAST8_MIN INT8_MIN
#define INT_FAST8_MAX INT8_MAX
#define INT_FAST16_MIN INT16_MIN
#define INT_FAST16_MAX INT16_MAX
#define INT_FAST32_MIN INT32_MIN
#define INT_FAST32_MAX INT32_MAX
#define INT_FAST64_MIN INT64_MIN
#define INT_FAST64_MAX INT64_MAX
#define UINT_FAST8_MAX UINT8_MAX
#define UINT_FAST16_MAX UINT16_MAX
#define UINT_FAST32_MAX UINT32_MAX
#define UINT_FAST64_MAX UINT64_MAX
// 7.18.2.4 Limits of integer types capable of holding object pointers
#ifdef _WIN64 // [
# define INTPTR_MIN INT64_MIN
# define INTPTR_MAX INT64_MAX
# define UINTPTR_MAX UINT64_MAX
#else // _WIN64 ][
# define INTPTR_MIN INT32_MIN
# define INTPTR_MAX INT32_MAX
# define UINTPTR_MAX UINT32_MAX
#endif // _WIN64 ]
// 7.18.2.5 Limits of greatest-width integer types
#define INTMAX_MIN INT64_MIN
#define INTMAX_MAX INT64_MAX
#define UINTMAX_MAX UINT64_MAX
// 7.18.3 Limits of other integer types
#ifdef _WIN64 // [
# define PTRDIFF_MIN _I64_MIN
# define PTRDIFF_MAX _I64_MAX
#else // _WIN64 ][
# define PTRDIFF_MIN _I32_MIN
# define PTRDIFF_MAX _I32_MAX
#endif // _WIN64 ]
#define SIG_ATOMIC_MIN INT_MIN
#define SIG_ATOMIC_MAX INT_MAX
#ifndef SIZE_MAX // [
# ifdef _WIN64 // [
# define SIZE_MAX _UI64_MAX
# else // _WIN64 ][
# define SIZE_MAX _UI32_MAX
# endif // _WIN64 ]
#endif // SIZE_MAX ]
// WCHAR_MIN and WCHAR_MAX are also defined in <wchar.h>
#ifndef WCHAR_MIN // [
# define WCHAR_MIN 0
#endif // WCHAR_MIN ]
#ifndef WCHAR_MAX // [
# define WCHAR_MAX _UI16_MAX
#endif // WCHAR_MAX ]
#define WINT_MIN 0
#define WINT_MAX _UI16_MAX
#endif // __STDC_LIMIT_MACROS ]
// 7.18.4 Limits of other integer types
#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260
// 7.18.4.1 Macros for minimum-width integer constants
#define INT8_C(val) val##i8
#define INT16_C(val) val##i16
#define INT32_C(val) val##i32
#define INT64_C(val) val##i64
#define UINT8_C(val) val##ui8
#define UINT16_C(val) val##ui16
#define UINT32_C(val) val##ui32
#define UINT64_C(val) val##ui64
// 7.18.4.2 Macros for greatest-width integer constants
#define INTMAX_C INT64_C
#define UINTMAX_C UINT64_C
#endif // __STDC_CONSTANT_MACROS ]
#endif // _MSC_STDINT_H_ ]
+426
View File
@@ -0,0 +1,426 @@
/*!
\file gk_proto.h
\brief This file contains function prototypes
\date Started 3/27/2007
\author George
\version\verbatim $Id: gk_proto.h 22010 2018-05-14 20:20:26Z karypis $ \endverbatim
*/
#ifndef _GK_PROTO_H_
#define _GK_PROTO_H_
#ifdef __cplusplus
extern "C" {
#endif
/*-------------------------------------------------------------
* blas.c
*-------------------------------------------------------------*/
GK_MKBLAS_PROTO(gk_c, char, int)
GK_MKBLAS_PROTO(gk_i, int, int)
GK_MKBLAS_PROTO(gk_i8, int8_t, int8_t)
GK_MKBLAS_PROTO(gk_i16, int16_t, int16_t)
GK_MKBLAS_PROTO(gk_i32, int32_t, int32_t)
GK_MKBLAS_PROTO(gk_i64, int64_t, int64_t)
GK_MKBLAS_PROTO(gk_z, ssize_t, ssize_t)
GK_MKBLAS_PROTO(gk_zu, size_t, size_t)
GK_MKBLAS_PROTO(gk_f, float, float)
GK_MKBLAS_PROTO(gk_d, double, double)
GK_MKBLAS_PROTO(gk_idx, gk_idx_t, gk_idx_t)
/*-------------------------------------------------------------
* io.c
*-------------------------------------------------------------*/
FILE *gk_fopen(char *, char *, const char *);
void gk_fclose(FILE *);
ssize_t gk_read(int fd, void *vbuf, size_t count);
ssize_t gk_write(int fd, void *vbuf, size_t count);
ssize_t gk_getline(char **lineptr, size_t *n, FILE *stream);
char **gk_readfile(char *fname, size_t *r_nlines);
int32_t *gk_i32readfile(char *fname, size_t *r_nlines);
int64_t *gk_i64readfile(char *fname, size_t *r_nlines);
ssize_t *gk_zreadfile(char *fname, size_t *r_nlines);
char *gk_creadfilebin(char *fname, size_t *r_nelmnts);
size_t gk_cwritefilebin(char *fname, size_t n, char *a);
int32_t *gk_i32readfilebin(char *fname, size_t *r_nelmnts);
size_t gk_i32writefilebin(char *fname, size_t n, int32_t *a);
int64_t *gk_i64readfilebin(char *fname, size_t *r_nelmnts);
size_t gk_i64writefilebin(char *fname, size_t n, int64_t *a);
ssize_t *gk_zreadfilebin(char *fname, size_t *r_nelmnts);
size_t gk_zwritefilebin(char *fname, size_t n, ssize_t *a);
float *gk_freadfilebin(char *fname, size_t *r_nelmnts);
size_t gk_fwritefilebin(char *fname, size_t n, float *a);
double *gk_dreadfilebin(char *fname, size_t *r_nelmnts);
size_t gk_dwritefilebin(char *fname, size_t n, double *a);
/*-------------------------------------------------------------
* fs.c
*-------------------------------------------------------------*/
int gk_fexists(char *);
int gk_dexists(char *);
ssize_t gk_getfsize(char *);
void gk_getfilestats(char *fname, size_t *r_nlines, size_t *r_ntokens,
size_t *r_max_nlntokens, size_t *r_nbytes);
char *gk_getbasename(char *path);
char *gk_getextname(char *path);
char *gk_getfilename(char *path);
char *gk_getpathname(char *path);
int gk_mkpath(char *);
int gk_rmpath(char *);
/*-------------------------------------------------------------
* memory.c
*-------------------------------------------------------------*/
GK_MKALLOC_PROTO(gk_c, char)
GK_MKALLOC_PROTO(gk_i, int)
GK_MKALLOC_PROTO(gk_i8, int8_t)
GK_MKALLOC_PROTO(gk_i16, int16_t)
GK_MKALLOC_PROTO(gk_i32, int32_t)
GK_MKALLOC_PROTO(gk_i64, int64_t)
GK_MKALLOC_PROTO(gk_ui8, uint8_t)
GK_MKALLOC_PROTO(gk_ui16, uint16_t)
GK_MKALLOC_PROTO(gk_ui32, uint32_t)
GK_MKALLOC_PROTO(gk_ui64, uint64_t)
GK_MKALLOC_PROTO(gk_z, ssize_t)
GK_MKALLOC_PROTO(gk_zu, size_t)
GK_MKALLOC_PROTO(gk_f, float)
GK_MKALLOC_PROTO(gk_d, double)
GK_MKALLOC_PROTO(gk_idx, gk_idx_t)
GK_MKALLOC_PROTO(gk_ckv, gk_ckv_t)
GK_MKALLOC_PROTO(gk_ikv, gk_ikv_t)
GK_MKALLOC_PROTO(gk_i8kv, gk_i8kv_t)
GK_MKALLOC_PROTO(gk_i16kv, gk_i16kv_t)
GK_MKALLOC_PROTO(gk_i32kv, gk_i32kv_t)
GK_MKALLOC_PROTO(gk_i64kv, gk_i64kv_t)
GK_MKALLOC_PROTO(gk_zkv, gk_zkv_t)
GK_MKALLOC_PROTO(gk_zukv, gk_zukv_t)
GK_MKALLOC_PROTO(gk_fkv, gk_fkv_t)
GK_MKALLOC_PROTO(gk_dkv, gk_dkv_t)
GK_MKALLOC_PROTO(gk_skv, gk_skv_t)
GK_MKALLOC_PROTO(gk_idxkv, gk_idxkv_t)
void gk_AllocMatrix(void ***, size_t, size_t , size_t);
void gk_FreeMatrix(void ***, size_t, size_t);
int gk_malloc_init();
void gk_malloc_cleanup(int showstats);
void *gk_malloc(size_t nbytes, char *msg);
void *gk_realloc(void *oldptr, size_t nbytes, char *msg);
void gk_free(void **ptr1,...);
size_t gk_GetCurMemoryUsed();
size_t gk_GetMaxMemoryUsed();
void gk_GetVMInfo(size_t *vmsize, size_t *vmrss);
size_t gk_GetProcVmPeak();
/*-------------------------------------------------------------
* seq.c
*-------------------------------------------------------------*/
gk_seq_t *gk_seq_ReadGKMODPSSM(char *file_name);
gk_i2cc2i_t *gk_i2cc2i_create_common(char *alphabet);
void gk_seq_init(gk_seq_t *seq);
/*-------------------------------------------------------------
* error.c
*-------------------------------------------------------------*/
void gk_set_exit_on_error(int value);
void errexit(char *,...);
void gk_errexit(int signum, char *,...);
int gk_sigtrap();
int gk_siguntrap();
void gk_sigthrow(int signum);
void gk_SetSignalHandlers();
void gk_UnsetSignalHandlers();
void gk_NonLocalExit_Handler(int signum);
char *gk_strerror(int errnum);
void PrintBackTrace();
/*-------------------------------------------------------------
* util.c
*-------------------------------------------------------------*/
void gk_RandomPermute(size_t, int *, int);
void gk_array2csr(size_t n, size_t range, int *array, int *ptr, int *ind);
int gk_log2(int);
int gk_ispow2(int);
float gk_flog2(float);
/*-------------------------------------------------------------
* time.c
*-------------------------------------------------------------*/
gk_wclock_t gk_WClockSeconds(void);
double gk_CPUSeconds(void);
/*-------------------------------------------------------------
* string.c
*-------------------------------------------------------------*/
char *gk_strchr_replace(char *str, char *fromlist, char *tolist);
int gk_strstr_replace(char *str, char *pattern, char *replacement, char *options, char **new_str);
char *gk_strtprune(char *, char *);
char *gk_strhprune(char *, char *);
char *gk_strtoupper(char *);
char *gk_strtolower(char *);
char *gk_strdup(char *orgstr);
int gk_strcasecmp(char *s1, char *s2);
int gk_strrcmp(char *s1, char *s2);
char *gk_time2str(time_t time);
time_t gk_str2time(char *str);
int gk_GetStringID(gk_StringMap_t *strmap, char *key);
/*-------------------------------------------------------------
* sort.c
*-------------------------------------------------------------*/
void gk_csorti(size_t, char *);
void gk_csortd(size_t, char *);
void gk_isorti(size_t, int *);
void gk_isortd(size_t, int *);
void gk_i32sorti(size_t, int32_t *);
void gk_i32sortd(size_t, int32_t *);
void gk_i64sorti(size_t, int64_t *);
void gk_i64sortd(size_t, int64_t *);
void gk_ui32sorti(size_t, uint32_t *);
void gk_ui32sortd(size_t, uint32_t *);
void gk_ui64sorti(size_t, uint64_t *);
void gk_ui64sortd(size_t, uint64_t *);
void gk_fsorti(size_t, float *);
void gk_fsortd(size_t, float *);
void gk_dsorti(size_t, double *);
void gk_dsortd(size_t, double *);
void gk_idxsorti(size_t, gk_idx_t *);
void gk_idxsortd(size_t, gk_idx_t *);
void gk_ckvsorti(size_t, gk_ckv_t *);
void gk_ckvsortd(size_t, gk_ckv_t *);
void gk_ikvsorti(size_t, gk_ikv_t *);
void gk_ikvsortd(size_t, gk_ikv_t *);
void gk_i32kvsorti(size_t, gk_i32kv_t *);
void gk_i32kvsortd(size_t, gk_i32kv_t *);
void gk_i64kvsorti(size_t, gk_i64kv_t *);
void gk_i64kvsortd(size_t, gk_i64kv_t *);
void gk_zkvsorti(size_t, gk_zkv_t *);
void gk_zkvsortd(size_t, gk_zkv_t *);
void gk_zukvsorti(size_t, gk_zukv_t *);
void gk_zukvsortd(size_t, gk_zukv_t *);
void gk_fkvsorti(size_t, gk_fkv_t *);
void gk_fkvsortd(size_t, gk_fkv_t *);
void gk_dkvsorti(size_t, gk_dkv_t *);
void gk_dkvsortd(size_t, gk_dkv_t *);
void gk_skvsorti(size_t, gk_skv_t *);
void gk_skvsortd(size_t, gk_skv_t *);
void gk_idxkvsorti(size_t, gk_idxkv_t *);
void gk_idxkvsortd(size_t, gk_idxkv_t *);
/*-------------------------------------------------------------
* Selection routines
*-------------------------------------------------------------*/
int gk_dfkvkselect(size_t, int, gk_fkv_t *);
int gk_ifkvkselect(size_t, int, gk_fkv_t *);
/*-------------------------------------------------------------
* Priority queue
*-------------------------------------------------------------*/
GK_MKPQUEUE_PROTO(gk_ipq, gk_ipq_t, int, gk_idx_t)
GK_MKPQUEUE_PROTO(gk_i32pq, gk_i32pq_t, int32_t, gk_idx_t)
GK_MKPQUEUE_PROTO(gk_i64pq, gk_i64pq_t, int64_t, gk_idx_t)
GK_MKPQUEUE_PROTO(gk_fpq, gk_fpq_t, float, gk_idx_t)
GK_MKPQUEUE_PROTO(gk_dpq, gk_dpq_t, double, gk_idx_t)
GK_MKPQUEUE_PROTO(gk_idxpq, gk_idxpq_t, gk_idx_t, gk_idx_t)
/*-------------------------------------------------------------
* HTable routines
*-------------------------------------------------------------*/
gk_HTable_t *HTable_Create(int nelements);
void HTable_Reset(gk_HTable_t *htable);
void HTable_Resize(gk_HTable_t *htable, int nelements);
void HTable_Insert(gk_HTable_t *htable, int key, int val);
void HTable_Delete(gk_HTable_t *htable, int key);
int HTable_Search(gk_HTable_t *htable, int key);
int HTable_GetNext(gk_HTable_t *htable, int key, int *val, int type);
int HTable_SearchAndDelete(gk_HTable_t *htable, int key);
void HTable_Destroy(gk_HTable_t *htable);
int HTable_HFunction(int nelements, int key);
/*-------------------------------------------------------------
* Tokenizer routines
*-------------------------------------------------------------*/
void gk_strtokenize(char *line, char *delim, gk_Tokens_t *tokens);
void gk_freetokenslist(gk_Tokens_t *tokens);
/*-------------------------------------------------------------
* Encoder/Decoder
*-------------------------------------------------------------*/
void encodeblock(unsigned char *in, unsigned char *out);
void decodeblock(unsigned char *in, unsigned char *out);
void GKEncodeBase64(int nbytes, unsigned char *inbuffer, unsigned char *outbuffer);
void GKDecodeBase64(int nbytes, unsigned char *inbuffer, unsigned char *outbuffer);
/*-------------------------------------------------------------
* random.c
*-------------------------------------------------------------*/
GK_MKRANDOM_PROTO(gk_c, size_t, char)
GK_MKRANDOM_PROTO(gk_i, size_t, int)
GK_MKRANDOM_PROTO(gk_i32, size_t, int32_t)
GK_MKRANDOM_PROTO(gk_f, size_t, float)
GK_MKRANDOM_PROTO(gk_d, size_t, double)
GK_MKRANDOM_PROTO(gk_idx, size_t, gk_idx_t)
GK_MKRANDOM_PROTO(gk_z, size_t, ssize_t)
GK_MKRANDOM_PROTO(gk_zu, size_t, size_t)
void gk_randinit(uint64_t);
uint64_t gk_randint64(void);
uint32_t gk_randint32(void);
/*-------------------------------------------------------------
* OpenMP fake functions
*-------------------------------------------------------------*/
#if !defined(__OPENMP__)
void omp_set_num_threads(int num_threads);
int omp_get_num_threads(void);
int omp_get_max_threads(void);
int omp_get_thread_num(void);
int omp_get_num_procs(void);
int omp_in_parallel(void);
void omp_set_dynamic(int num_threads);
int omp_get_dynamic(void);
void omp_set_nested(int nested);
int omp_get_nested(void);
#endif /* __OPENMP__ */
/*-------------------------------------------------------------
* CSR-related functions
*-------------------------------------------------------------*/
gk_csr_t *gk_csr_Create();
void gk_csr_Init(gk_csr_t *mat);
void gk_csr_Free(gk_csr_t **mat);
void gk_csr_FreeContents(gk_csr_t *mat);
gk_csr_t *gk_csr_Dup(gk_csr_t *mat);
gk_csr_t *gk_csr_ExtractSubmatrix(gk_csr_t *mat, int rstart, int nrows);
gk_csr_t *gk_csr_ExtractRows(gk_csr_t *mat, int nrows, int *rind);
gk_csr_t *gk_csr_ExtractPartition(gk_csr_t *mat, int *part, int pid);
gk_csr_t **gk_csr_Split(gk_csr_t *mat, int *color);
int gk_csr_DetermineFormat(char *filename, int format);
gk_csr_t *gk_csr_Read(char *filename, int format, int readvals, int numbering);
void gk_csr_Write(gk_csr_t *mat, char *filename, int format, int writevals, int numbering);
gk_csr_t *gk_csr_Prune(gk_csr_t *mat, int what, int minf, int maxf);
gk_csr_t *gk_csr_LowFilter(gk_csr_t *mat, int what, int norm, float fraction);
gk_csr_t *gk_csr_TopKPlusFilter(gk_csr_t *mat, int what, int topk, float keepval);
gk_csr_t *gk_csr_ZScoreFilter(gk_csr_t *mat, int what, float zscore);
void gk_csr_CompactColumns(gk_csr_t *mat);
void gk_csr_SortIndices(gk_csr_t *mat, int what);
void gk_csr_CreateIndex(gk_csr_t *mat, int what);
void gk_csr_Normalize(gk_csr_t *mat, int what, int norm);
void gk_csr_Scale(gk_csr_t *mat, int type);
void gk_csr_ComputeSums(gk_csr_t *mat, int what);
void gk_csr_ComputeNorms(gk_csr_t *mat, int what);
void gk_csr_ComputeSquaredNorms(gk_csr_t *mat, int what);
gk_csr_t *gk_csr_Shuffle(gk_csr_t *mat, int what, int summetric);
gk_csr_t *gk_csr_Transpose(gk_csr_t *mat);
float gk_csr_ComputeSimilarity(gk_csr_t *mat, int i1, int i2, int what, int simtype);
float gk_csr_ComputePairSimilarity(gk_csr_t *mat_a, gk_csr_t *mat_b, int i1, int i2, int what, int simtype);
int gk_csr_GetSimilarRows(gk_csr_t *mat, int nqterms, int *qind, float *qval,
int simtype, int nsim, float minsim, gk_fkv_t *hits, int *_imarker,
gk_fkv_t *i_cand);
int gk_csr_FindConnectedComponents(gk_csr_t *mat, int32_t *cptr, int32_t *cind,
int32_t *cids);
gk_csr_t *gk_csr_MakeSymmetric(gk_csr_t *mat, int op);
gk_csr_t *gk_csr_ReorderSymmetric(gk_csr_t *mat, int32_t *perm, int32_t *iperm);
void gk_csr_ComputeBFSOrderingSymmetric(gk_csr_t *mat, int maxdegree, int v,
int32_t **r_perm, int32_t **r_iperm);
void gk_csr_ComputeBestFOrderingSymmetric(gk_csr_t *mat, int v, int type,
int32_t **r_perm, int32_t **r_iperm);
/* itemsets.c */
void gk_find_frequent_itemsets(int ntrans, ssize_t *tranptr, int *tranind,
int minfreq, int maxfreq, int minlen, int maxlen,
void (*process_itemset)(void *stateptr, int nitems, int *itemind,
int ntrans, int *tranind),
void *stateptr);
/* evaluate.c */
float ComputeAccuracy(int n, gk_fkv_t *list);
float ComputeROCn(int n, int maxN, gk_fkv_t *list);
float ComputeMedianRFP(int n, gk_fkv_t *list);
float ComputeMean (int n, float *values);
float ComputeStdDev(int n, float *values);
/* mcore.c */
gk_mcore_t *gk_mcoreCreate(size_t coresize);
gk_mcore_t *gk_gkmcoreCreate();
void gk_mcoreDestroy(gk_mcore_t **r_mcore, int showstats);
void gk_gkmcoreDestroy(gk_mcore_t **r_mcore, int showstats);
void *gk_mcoreMalloc(gk_mcore_t *mcore, size_t nbytes);
void gk_mcorePush(gk_mcore_t *mcore);
void gk_gkmcorePush(gk_mcore_t *mcore);
void gk_mcorePop(gk_mcore_t *mcore);
void gk_gkmcorePop(gk_mcore_t *mcore);
void gk_mcoreAdd(gk_mcore_t *mcore, int type, size_t nbytes, void *ptr);
void gk_gkmcoreAdd(gk_mcore_t *mcore, int type, size_t nbytes, void *ptr);
void gk_mcoreDel(gk_mcore_t *mcore, void *ptr);
void gk_gkmcoreDel(gk_mcore_t *mcore, void *ptr);
/* rw.c */
int gk_rw_PageRank(gk_csr_t *mat, float lamda, float eps, int max_niter, float *pr);
/* graph.c */
gk_graph_t *gk_graph_Create();
void gk_graph_Init(gk_graph_t *graph);
void gk_graph_Free(gk_graph_t **graph);
void gk_graph_FreeContents(gk_graph_t *graph);
gk_graph_t *gk_graph_Read(char *filename, int format, int hasvals,
int numbering, int isfewgts, int isfvwgts, int isfvsizes);
void gk_graph_Write(gk_graph_t *graph, char *filename, int format, int numbering);
gk_graph_t *gk_graph_Dup(gk_graph_t *graph);
gk_graph_t *gk_graph_Transpose(gk_graph_t *graph);
gk_graph_t *gk_graph_ExtractSubgraph(gk_graph_t *graph, int vstart, int nvtxs);
gk_graph_t *gk_graph_Reorder(gk_graph_t *graph, int32_t *perm, int32_t *iperm);
int gk_graph_FindComponents(gk_graph_t *graph, int32_t *cptr, int32_t *cind);
void gk_graph_ComputeBFSOrdering(gk_graph_t *graph, int v, int32_t **r_perm,
int32_t **r_iperm);
void gk_graph_ComputeBestFOrdering0(gk_graph_t *graph, int v, int type,
int32_t **r_perm, int32_t **r_iperm);
void gk_graph_ComputeBestFOrdering(gk_graph_t *graph, int v, int type,
int32_t **r_perm, int32_t **r_iperm);
void gk_graph_SingleSourceShortestPaths(gk_graph_t *graph, int v, void **r_sps);
void gk_graph_SortAdjacencies(gk_graph_t *graph);
gk_graph_t *gk_graph_MakeSymmetric(gk_graph_t *graph, int op);
/* cache.c */
gk_cache_t *gk_cacheCreate(uint32_t nway, uint32_t lnbits, size_t cnbits);
void gk_cacheReset(gk_cache_t *cache);
void gk_cacheDestroy(gk_cache_t **r_cache);
int gk_cacheLoad(gk_cache_t *cache, size_t addr);
double gk_cacheGetHitRate(gk_cache_t *cache);
#ifdef __cplusplus
}
#endif
#endif
+296
View File
@@ -0,0 +1,296 @@
/*!
\file gk_struct.h
\brief This file contains various datastructures used/provided by GKlib
\date Started 3/27/2007
\author George
\version\verbatim $Id: gk_struct.h 21988 2018-04-16 00:11:19Z karypis $ \endverbatim
*/
#ifndef _GK_STRUCT_H_
#define _GK_STRUCT_H_
/********************************************************************/
/*! Generator for gk_??KeyVal_t data structure */
/********************************************************************/
#define GK_MKKEYVALUE_T(NAME, KEYTYPE, VALTYPE) \
typedef struct {\
KEYTYPE key;\
VALTYPE val;\
} NAME;\
/* The actual KeyVal data structures */
GK_MKKEYVALUE_T(gk_ckv_t, char, ssize_t)
GK_MKKEYVALUE_T(gk_ikv_t, int, ssize_t)
GK_MKKEYVALUE_T(gk_i8kv_t, int8_t, ssize_t)
GK_MKKEYVALUE_T(gk_i16kv_t, int16_t, ssize_t)
GK_MKKEYVALUE_T(gk_i32kv_t, int32_t, ssize_t)
GK_MKKEYVALUE_T(gk_i64kv_t, int64_t, ssize_t)
GK_MKKEYVALUE_T(gk_zkv_t, ssize_t, ssize_t)
GK_MKKEYVALUE_T(gk_zukv_t, size_t, ssize_t)
GK_MKKEYVALUE_T(gk_fkv_t, float, ssize_t)
GK_MKKEYVALUE_T(gk_dkv_t, double, ssize_t)
GK_MKKEYVALUE_T(gk_skv_t, char *, ssize_t)
GK_MKKEYVALUE_T(gk_idxkv_t, gk_idx_t, gk_idx_t)
/********************************************************************/
/*! Generator for gk_?pq_t data structure */
/********************************************************************/
#define GK_MKPQUEUE_T(NAME, KVTYPE)\
typedef struct {\
size_t nnodes;\
size_t maxnodes;\
\
/* Heap version of the data structure */ \
KVTYPE *heap;\
ssize_t *locator;\
} NAME;\
GK_MKPQUEUE_T(gk_ipq_t, gk_ikv_t)
GK_MKPQUEUE_T(gk_i32pq_t, gk_i32kv_t)
GK_MKPQUEUE_T(gk_i64pq_t, gk_i64kv_t)
GK_MKPQUEUE_T(gk_fpq_t, gk_fkv_t)
GK_MKPQUEUE_T(gk_dpq_t, gk_dkv_t)
GK_MKPQUEUE_T(gk_idxpq_t, gk_idxkv_t)
#define GK_MKPQUEUE2_T(NAME, KTYPE, VTYPE)\
typedef struct {\
ssize_t nnodes;\
ssize_t maxnodes;\
\
/* Heap version of the data structure */ \
KTYPE *keys;\
VTYPE *vals;\
} NAME;\
/*-------------------------------------------------------------
* The following data structure stores a sparse CSR format
*-------------------------------------------------------------*/
typedef struct gk_csr_t {
int32_t nrows, ncols;
ssize_t *rowptr, *colptr;
int32_t *rowind, *colind;
int32_t *rowids, *colids;
int32_t *rlabels, *clabels;
int32_t *rmap, *cmap;
float *rowval, *colval;
float *rnorms, *cnorms;
float *rsums, *csums;
float *rsizes, *csizes;
float *rvols, *cvols;
float *rwgts, *cwgts;
} gk_csr_t;
/*-------------------------------------------------------------
* The following data structure stores a sparse graph
*-------------------------------------------------------------*/
typedef struct gk_graph_t {
int32_t nvtxs; /*!< The number of vertices in the graph */
ssize_t *xadj; /*!< The ptr-structure of the adjncy list */
int32_t *adjncy; /*!< The adjacency list of the graph */
int32_t *iadjwgt; /*!< The integer edge weights */
float *fadjwgt; /*!< The floating point edge weights */
int32_t *ivwgts; /*!< The integer vertex weights */
float *fvwgts; /*!< The floating point vertex weights */
int32_t *ivsizes; /*!< The integer vertex sizes */
float *fvsizes; /*!< The floating point vertex sizes */
int32_t *vlabels; /*!< The labels of the vertices */
} gk_graph_t;
/*-------------------------------------------------------------
* The following data structure stores stores a string as a
* pair of its allocated buffer and the buffer itself.
*-------------------------------------------------------------*/
typedef struct gk_str_t {
size_t len;
char *buf;
} gk_str_t;
/*-------------------------------------------------------------
* The following data structure implements a string-2-int mapping
* table used for parsing command-line options
*-------------------------------------------------------------*/
typedef struct gk_StringMap_t {
char *name;
int id;
} gk_StringMap_t;
/*------------------------------------------------------------
* This structure implements a simple hash table
*------------------------------------------------------------*/
typedef struct gk_HTable_t {
int nelements; /* The overall size of the hash-table */
int htsize; /* The current size of the hash-table */
gk_ikv_t *harray; /* The actual hash-table */
} gk_HTable_t;
/*------------------------------------------------------------
* This structure implements a gk_Tokens_t list returned by the
* string tokenizer
*------------------------------------------------------------*/
typedef struct gk_Tokens_t {
int ntoks; /* The number of tokens in the input string */
char *strbuf; /* The memory that stores all the entries */
char **list; /* Pointers to the strbuf for each element */
} gk_Tokens_t;
/*------------------------------------------------------------
* This structure implements storage for an atom in a pdb file
*------------------------------------------------------------*/
typedef struct atom {
int serial;
char *name;
char altLoc;
char *resname;
char chainid;
int rserial;
char icode;
char element;
double x;
double y;
double z;
double opcy;
double tmpt;
} atom;
/*------------------------------------------------------------
* This structure implements storage for a center of mass for
* a single residue.
*------------------------------------------------------------*/
typedef struct center_of_mass {
char name;
double x;
double y;
double z;
} center_of_mass;
/*------------------------------------------------------------
* This structure implements storage for a pdb protein
*------------------------------------------------------------*/
typedef struct pdbf {
int natoms; /* Number of atoms */
int nresidues; /* Number of residues based on coordinates */
int ncas;
int nbbs;
int corruption;
char *resSeq; /* Residue sequence based on coordinates */
char **threeresSeq; /* three-letter residue sequence */
atom *atoms;
atom **bbs;
atom **cas;
center_of_mass *cm;
} pdbf;
/*************************************************************
* Localization Structures for converting characters to integers
**************************************************************/
typedef struct gk_i2cc2i_t {
int n;
char *i2c;
int *c2i;
} gk_i2cc2i_t;
/*******************************************************************
*This structure implements storage of a protein sequence
* *****************************************************************/
typedef struct gk_seq_t {
int len; /*Number of Residues */
int *sequence; /* Stores the sequence*/
int **pssm; /* Stores the pssm matrix */
int **psfm; /* Stores the psfm matrix */
char *name; /* Stores the name of the sequence */
int nsymbols;
} gk_seq_t;
/*************************************************************************/
/*! The following data structure stores information about a memory
allocation operation that can either be served from gk_mcore_t or by
a gk_malloc if not sufficient workspace memory is available. */
/*************************************************************************/
typedef struct gk_mop_t {
int type;
ssize_t nbytes;
void *ptr;
} gk_mop_t;
/*************************************************************************/
/*! The following structure defines the mcore for GKlib's customized
memory allocations. */
/*************************************************************************/
typedef struct gk_mcore_t {
/* Workspace information */
size_t coresize; /*!< The amount of core memory that has been allocated */
size_t corecpos; /*!< Index of the first free location in core */
void *core; /*!< Pointer to the core itself */
/* These are for implementing a stack-based allocation scheme using both
core and also dynamically allocated memory */
size_t nmops; /*!< The number of maop_t entries that have been allocated */
size_t cmop; /*!< Index of the first free location in maops */
gk_mop_t *mops; /*!< The array recording the maop_t operations */
/* These are for keeping various statistics for wspacemalloc */
size_t num_callocs; /*!< The number of core mallocs */
size_t num_hallocs; /*!< The number of heap mallocs */
size_t size_callocs; /*!< The total # of bytes in core mallocs */
size_t size_hallocs; /*!< The total # of bytes in heap mallocs */
size_t cur_callocs; /*!< The current # of bytes in core mallocs */
size_t cur_hallocs; /*!< The current # of bytes in heap mallocs */
size_t max_callocs; /*!< The maximum # of bytes in core mallocs at any given time */
size_t max_hallocs; /*!< The maximum # of bytes in heap mallocs at any given time */
} gk_mcore_t;
/*************************************************************************/
/*! The following structure is used for cache simulation for performance
modeling and analysis. */
/*************************************************************************/
typedef struct gk_cache_t {
/*! The total cache is nway*(2^(cnbits+lnbits)) bytes */
uint32_t nway; /*!< the associativity of the cache */
uint32_t lnbits; /*!< the number of address bits indexing the cache line */
uint32_t cnbits; /*!< the number of address bits indexing the cache */
size_t csize; /*!< 2^cnbits */
size_t cmask; /*!< csize-1 */
uint64_t clock; /*!< a clock in terms of accesses */
uint64_t *latimes; /*!< a cacheline-level last access time */
size_t *clines; /*!< the cache in terms of cachelines */
uint64_t nhits; /*!< counts the number of hits */
uint64_t nmisses; /*!< counts the number of misses */
} gk_cache_t;
#endif
+38
View File
@@ -0,0 +1,38 @@
/*!
\file gk_types.h
\brief This file contains basic scalar datatype used in GKlib
\date Started 3/27/2007
\author George
\version\verbatim $Id: gk_types.h 10711 2011-08-31 22:23:04Z karypis $ \endverbatim
*/
#ifndef _GK_TYPES_H_
#define _GK_TYPES_H_
/*************************************************************************
* Basic data type definitions. These definitions allow GKlib to separate
* the following elemental types:
* - loop iterator variables, which are set to size_t
* - signed and unsigned int variables that can be set to any # of bits
* - signed and unsigned long variables that can be set to any # of bits
* - real variables, which can be set to single or double precision.
**************************************************************************/
/*typedef ptrdiff_t gk_idx_t; */ /* index variable */
typedef ssize_t gk_idx_t; /* index variable */
typedef int32_t gk_int_t; /* integer values */
typedef uint32_t gk_uint_t; /* unsigned integer values */
typedef int64_t gk_long_t; /* long integer values */
typedef uint64_t gk_ulong_t; /* unsigned long integer values */
typedef float gk_real_t; /* real type */
typedef double gk_dreal_t; /* double precission real type */
typedef double gk_wclock_t; /* wall-clock time */
/*#define GK_IDX_MAX PTRDIFF_MAX*/
#define GK_IDX_MAX ((SIZE_MAX>>1)-2)
#define PRIGKIDX "zd"
#define SCNGKIDX "zd"
#endif
+107
View File
@@ -0,0 +1,107 @@
/*!
\file util.c
\brief Various utility routines
\date Started 4/12/2007
\author George
\version\verbatim $Id: gk_util.c 16223 2014-02-15 21:34:09Z karypis $ \endverbatim
*/
#include <GKlib.h>
/*************************************************************************
* This file randomly permutes the contents of an array.
* flag == 0, don't initialize perm
* flag == 1, set p[i] = i
**************************************************************************/
void gk_RandomPermute(size_t n, int *p, int flag)
{
size_t i, u, v;
int tmp;
if (flag == 1) {
for (i=0; i<n; i++)
p[i] = i;
}
for (i=0; i<n/2; i++) {
v = RandomInRange(n);
u = RandomInRange(n);
gk_SWAP(p[v], p[u], tmp);
}
}
/************************************************************************/
/*!
\brief Converts an element-based set membership into a CSR-format set-based
membership.
For example, it takes an array such as part[] that stores where each
element belongs to and returns a pair of arrays (pptr[], pind[]) that
store in CSF format the list of elements belonging in each partition.
\param n
the number of elements in the array (e.g., # of vertices)
\param range
the cardinality of the set (e.g., # of partitions)
\param array
the array that stores the per-element set membership
\param ptr
the array that will store the starting indices in ind for
the elements of each set. This is filled by the routine and
its size should be at least range+1.
\param ind
the array that stores consecutively which elements belong to
each set. The size of this array should be n.
*/
/************************************************************************/
void gk_array2csr(size_t n, size_t range, int *array, int *ptr, int *ind)
{
size_t i;
gk_iset(range+1, 0, ptr);
for (i=0; i<n; i++)
ptr[array[i]]++;
/* Compute the ptr, ind structure */
MAKECSR(i, range, ptr);
for (i=0; i<n; i++)
ind[ptr[array[i]]++] = i;
SHIFTCSR(i, range, ptr);
}
/*************************************************************************
* This function returns the log2(x)
**************************************************************************/
int gk_log2(int a)
{
size_t i;
for (i=1; a > 1; i++, a = a>>1);
return i-1;
}
/*************************************************************************
* This function checks if the argument is a power of 2
**************************************************************************/
int gk_ispow2(int a)
{
return (a == (1<<gk_log2(a)));
}
/*************************************************************************
* This function returns the log2(x)
**************************************************************************/
float gk_flog2(float a)
{
return log(a)/log(2.0);
}
File diff suppressed because it is too large. Load diff
+556
View File
@@ -0,0 +1,556 @@
/* Definitions for data structures and routines for the regular
expression library.
Copyright (C) 1985,1989-93,1995-98,2000,2001,2002,2003,2005,2006
Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#ifndef _REGEX_H
#define _REGEX_H 1
#include <sys/types.h>
/* Allow the use in C++ code. */
#ifdef __cplusplus
extern "C" {
#endif
/* The following two types have to be signed and unsigned integer type
wide enough to hold a value of a pointer. For most ANSI compilers
ptrdiff_t and size_t should be likely OK. Still size of these two
types is 2 for Microsoft C. Ugh... */
typedef long int s_reg_t;
typedef unsigned long int active_reg_t;
/* The following bits are used to determine the regexp syntax we
recognize. The set/not-set meanings are chosen so that Emacs syntax
remains the value 0. The bits are given in alphabetical order, and
the definitions shifted by one from the previous bit; thus, when we
add or remove a bit, only one other definition need change. */
typedef unsigned long int reg_syntax_t;
/* If this bit is not set, then \ inside a bracket expression is literal.
If set, then such a \ quotes the following character. */
#define RE_BACKSLASH_ESCAPE_IN_LISTS ((unsigned long int) 1)
/* If this bit is not set, then + and ? are operators, and \+ and \? are
literals.
If set, then \+ and \? are operators and + and ? are literals. */
#define RE_BK_PLUS_QM (RE_BACKSLASH_ESCAPE_IN_LISTS << 1)
/* If this bit is set, then character classes are supported. They are:
[:alpha:], [:upper:], [:lower:], [:digit:], [:alnum:], [:xdigit:],
[:space:], [:print:], [:punct:], [:graph:], and [:cntrl:].
If not set, then character classes are not supported. */
#define RE_CHAR_CLASSES (RE_BK_PLUS_QM << 1)
/* If this bit is set, then ^ and $ are always anchors (outside bracket
expressions, of course).
If this bit is not set, then it depends:
^ is an anchor if it is at the beginning of a regular
expression or after an open-group or an alternation operator;
$ is an anchor if it is at the end of a regular expression, or
before a close-group or an alternation operator.
This bit could be (re)combined with RE_CONTEXT_INDEP_OPS, because
POSIX draft 11.2 says that * etc. in leading positions is undefined.
We already implemented a previous draft which made those constructs
invalid, though, so we haven't changed the code back. */
#define RE_CONTEXT_INDEP_ANCHORS (RE_CHAR_CLASSES << 1)
/* If this bit is set, then special characters are always special
regardless of where they are in the pattern.
If this bit is not set, then special characters are special only in
some contexts; otherwise they are ordinary. Specifically,
* + ? and intervals are only special when not after the beginning,
open-group, or alternation operator. */
#define RE_CONTEXT_INDEP_OPS (RE_CONTEXT_INDEP_ANCHORS << 1)
/* If this bit is set, then *, +, ?, and { cannot be first in an re or
immediately after an alternation or begin-group operator. */
#define RE_CONTEXT_INVALID_OPS (RE_CONTEXT_INDEP_OPS << 1)
/* If this bit is set, then . matches newline.
If not set, then it doesn't. */
#define RE_DOT_NEWLINE (RE_CONTEXT_INVALID_OPS << 1)
/* If this bit is set, then . doesn't match NUL.
If not set, then it does. */
#define RE_DOT_NOT_NULL (RE_DOT_NEWLINE << 1)
/* If this bit is set, nonmatching lists [^...] do not match newline.
If not set, they do. */
#define RE_HAT_LISTS_NOT_NEWLINE (RE_DOT_NOT_NULL << 1)
/* If this bit is set, either \{...\} or {...} defines an
interval, depending on RE_NO_BK_BRACES.
If not set, \{, \}, {, and } are literals. */
#define RE_INTERVALS (RE_HAT_LISTS_NOT_NEWLINE << 1)
/* If this bit is set, +, ? and | aren't recognized as operators.
If not set, they are. */
#define RE_LIMITED_OPS (RE_INTERVALS << 1)
/* If this bit is set, newline is an alternation operator.
If not set, newline is literal. */
#define RE_NEWLINE_ALT (RE_LIMITED_OPS << 1)
/* If this bit is set, then `{...}' defines an interval, and \{ and \}
are literals.
If not set, then `\{...\}' defines an interval. */
#define RE_NO_BK_BRACES (RE_NEWLINE_ALT << 1)
/* If this bit is set, (...) defines a group, and \( and \) are literals.
If not set, \(...\) defines a group, and ( and ) are literals. */
#define RE_NO_BK_PARENS (RE_NO_BK_BRACES << 1)
/* If this bit is set, then \<digit> matches <digit>.
If not set, then \<digit> is a back-reference. */
#define RE_NO_BK_REFS (RE_NO_BK_PARENS << 1)
/* If this bit is set, then | is an alternation operator, and \| is literal.
If not set, then \| is an alternation operator, and | is literal. */
#define RE_NO_BK_VBAR (RE_NO_BK_REFS << 1)
/* If this bit is set, then an ending range point collating higher
than the starting range point, as in [z-a], is invalid.
If not set, then when ending range point collates higher than the
starting range point, the range is ignored. */
#define RE_NO_EMPTY_RANGES (RE_NO_BK_VBAR << 1)
/* If this bit is set, then an unmatched ) is ordinary.
If not set, then an unmatched ) is invalid. */
#define RE_UNMATCHED_RIGHT_PAREN_ORD (RE_NO_EMPTY_RANGES << 1)
/* If this bit is set, succeed as soon as we match the whole pattern,
without further backtracking. */
#define RE_NO_POSIX_BACKTRACKING (RE_UNMATCHED_RIGHT_PAREN_ORD << 1)
/* If this bit is set, do not process the GNU regex operators.
If not set, then the GNU regex operators are recognized. */
#define RE_NO_GNU_OPS (RE_NO_POSIX_BACKTRACKING << 1)
/* If this bit is set, turn on internal regex debugging.
If not set, and debugging was on, turn it off.
This only works if regex.c is compiled -DDEBUG.
We define this bit always, so that all that's needed to turn on
debugging is to recompile regex.c; the calling code can always have
this bit set, and it won't affect anything in the normal case. */
#define RE_DEBUG (RE_NO_GNU_OPS << 1)
/* If this bit is set, a syntactically invalid interval is treated as
a string of ordinary characters. For example, the ERE 'a{1' is
treated as 'a\{1'. */
#define RE_INVALID_INTERVAL_ORD (RE_DEBUG << 1)
/* If this bit is set, then ignore case when matching.
If not set, then case is significant. */
#define RE_ICASE (RE_INVALID_INTERVAL_ORD << 1)
/* This bit is used internally like RE_CONTEXT_INDEP_ANCHORS but only
for ^, because it is difficult to scan the regex backwards to find
whether ^ should be special. */
#define RE_CARET_ANCHORS_HERE (RE_ICASE << 1)
/* If this bit is set, then \{ cannot be first in an bre or
immediately after an alternation or begin-group operator. */
#define RE_CONTEXT_INVALID_DUP (RE_CARET_ANCHORS_HERE << 1)
/* If this bit is set, then no_sub will be set to 1 during
re_compile_pattern. */
#define RE_NO_SUB (RE_CONTEXT_INVALID_DUP << 1)
/* This global variable defines the particular regexp syntax to use (for
some interfaces). When a regexp is compiled, the syntax used is
stored in the pattern buffer, so changing this does not affect
already-compiled regexps. */
extern reg_syntax_t re_syntax_options;
/* Define combinations of the above bits for the standard possibilities.
(The [[[ comments delimit what gets put into the Texinfo file, so
don't delete them!) */
/* [[[begin syntaxes]]] */
#define RE_SYNTAX_EMACS 0
#define RE_SYNTAX_AWK \
(RE_BACKSLASH_ESCAPE_IN_LISTS | RE_DOT_NOT_NULL \
| RE_NO_BK_PARENS | RE_NO_BK_REFS \
| RE_NO_BK_VBAR | RE_NO_EMPTY_RANGES \
| RE_DOT_NEWLINE | RE_CONTEXT_INDEP_ANCHORS \
| RE_UNMATCHED_RIGHT_PAREN_ORD | RE_NO_GNU_OPS)
#define RE_SYNTAX_GNU_AWK \
((RE_SYNTAX_POSIX_EXTENDED | RE_BACKSLASH_ESCAPE_IN_LISTS | RE_DEBUG) \
& ~(RE_DOT_NOT_NULL | RE_INTERVALS | RE_CONTEXT_INDEP_OPS \
| RE_CONTEXT_INVALID_OPS ))
#define RE_SYNTAX_POSIX_AWK \
(RE_SYNTAX_POSIX_EXTENDED | RE_BACKSLASH_ESCAPE_IN_LISTS \
| RE_INTERVALS | RE_NO_GNU_OPS)
#define RE_SYNTAX_GREP \
(RE_BK_PLUS_QM | RE_CHAR_CLASSES \
| RE_HAT_LISTS_NOT_NEWLINE | RE_INTERVALS \
| RE_NEWLINE_ALT)
#define RE_SYNTAX_EGREP \
(RE_CHAR_CLASSES | RE_CONTEXT_INDEP_ANCHORS \
| RE_CONTEXT_INDEP_OPS | RE_HAT_LISTS_NOT_NEWLINE \
| RE_NEWLINE_ALT | RE_NO_BK_PARENS \
| RE_NO_BK_VBAR)
#define RE_SYNTAX_POSIX_EGREP \
(RE_SYNTAX_EGREP | RE_INTERVALS | RE_NO_BK_BRACES \
| RE_INVALID_INTERVAL_ORD)
/* P1003.2/D11.2, section 4.20.7.1, lines 5078ff. */
#define RE_SYNTAX_ED RE_SYNTAX_POSIX_BASIC
#define RE_SYNTAX_SED RE_SYNTAX_POSIX_BASIC
/* Syntax bits common to both basic and extended POSIX regex syntax. */
#define _RE_SYNTAX_POSIX_COMMON \
(RE_CHAR_CLASSES | RE_DOT_NEWLINE | RE_DOT_NOT_NULL \
| RE_INTERVALS | RE_NO_EMPTY_RANGES)
#define RE_SYNTAX_POSIX_BASIC \
(_RE_SYNTAX_POSIX_COMMON | RE_BK_PLUS_QM | RE_CONTEXT_INVALID_DUP)
/* Differs from ..._POSIX_BASIC only in that RE_BK_PLUS_QM becomes
RE_LIMITED_OPS, i.e., \? \+ \| are not recognized. Actually, this
isn't minimal, since other operators, such as \`, aren't disabled. */
#define RE_SYNTAX_POSIX_MINIMAL_BASIC \
(_RE_SYNTAX_POSIX_COMMON | RE_LIMITED_OPS)
#define RE_SYNTAX_POSIX_EXTENDED \
(_RE_SYNTAX_POSIX_COMMON | RE_CONTEXT_INDEP_ANCHORS \
| RE_CONTEXT_INDEP_OPS | RE_NO_BK_BRACES \
| RE_NO_BK_PARENS | RE_NO_BK_VBAR \
| RE_CONTEXT_INVALID_OPS | RE_UNMATCHED_RIGHT_PAREN_ORD)
/* Differs from ..._POSIX_EXTENDED in that RE_CONTEXT_INDEP_OPS is
removed and RE_NO_BK_REFS is added. */
#define RE_SYNTAX_POSIX_MINIMAL_EXTENDED \
(_RE_SYNTAX_POSIX_COMMON | RE_CONTEXT_INDEP_ANCHORS \
| RE_CONTEXT_INVALID_OPS | RE_NO_BK_BRACES \
| RE_NO_BK_PARENS | RE_NO_BK_REFS \
| RE_NO_BK_VBAR | RE_UNMATCHED_RIGHT_PAREN_ORD)
/* [[[end syntaxes]]] */
/* Maximum number of duplicates an interval can allow. Some systems
(erroneously) define this in other header files, but we want our
value, so remove any previous define. */
#ifdef RE_DUP_MAX
# undef RE_DUP_MAX
#endif
/* If sizeof(int) == 2, then ((1 << 15) - 1) overflows. */
#define RE_DUP_MAX (0x7fff)
/* POSIX `cflags' bits (i.e., information for `regcomp'). */
/* If this bit is set, then use extended regular expression syntax.
If not set, then use basic regular expression syntax. */
#define REG_EXTENDED 1
/* If this bit is set, then ignore case when matching.
If not set, then case is significant. */
#define REG_ICASE (REG_EXTENDED << 1)
/* If this bit is set, then anchors do not match at newline
characters in the string.
If not set, then anchors do match at newlines. */
#define REG_NEWLINE (REG_ICASE << 1)
/* If this bit is set, then report only success or fail in regexec.
If not set, then returns differ between not matching and errors. */
#define REG_NOSUB (REG_NEWLINE << 1)
/* POSIX `eflags' bits (i.e., information for regexec). */
/* If this bit is set, then the beginning-of-line operator doesn't match
the beginning of the string (presumably because it's not the
beginning of a line).
If not set, then the beginning-of-line operator does match the
beginning of the string. */
#define REG_NOTBOL 1
/* Like REG_NOTBOL, except for the end-of-line. */
#define REG_NOTEOL (1 << 1)
/* Use PMATCH[0] to delimit the start and end of the search in the
buffer. */
#define REG_STARTEND (1 << 2)
/* If any error codes are removed, changed, or added, update the
`re_error_msg' table in regex.c. */
typedef enum
{
#ifdef _XOPEN_SOURCE
REG_ENOSYS = -1, /* This will never happen for this implementation. */
#endif
REG_NOERROR = 0, /* Success. */
REG_NOMATCH, /* Didn't find a match (for regexec). */
/* POSIX regcomp return error codes. (In the order listed in the
standard.) */
REG_BADPAT, /* Invalid pattern. */
REG_ECOLLATE, /* Inalid collating element. */
REG_ECTYPE, /* Invalid character class name. */
REG_EESCAPE, /* Trailing backslash. */
REG_ESUBREG, /* Invalid back reference. */
REG_EBRACK, /* Unmatched left bracket. */
REG_EPAREN, /* Parenthesis imbalance. */
REG_EBRACE, /* Unmatched \{. */
REG_BADBR, /* Invalid contents of \{\}. */
REG_ERANGE, /* Invalid range end. */
REG_ESPACE, /* Ran out of memory. */
REG_BADRPT, /* No preceding re for repetition op. */
/* Error codes we've added. */
REG_EEND, /* Premature end. */
REG_ESIZE, /* Compiled pattern bigger than 2^16 bytes. */
REG_ERPAREN /* Unmatched ) or \); not returned from regcomp. */
} reg_errcode_t;
/* This data structure represents a compiled pattern. Before calling
the pattern compiler, the fields `buffer', `allocated', `fastmap',
`translate', and `no_sub' can be set. After the pattern has been
compiled, the `re_nsub' field is available. All other fields are
private to the regex routines. */
#ifndef RE_TRANSLATE_TYPE
# define RE_TRANSLATE_TYPE unsigned char *
#endif
struct re_pattern_buffer
{
/* Space that holds the compiled pattern. It is declared as
`unsigned char *' because its elements are sometimes used as
array indexes. */
unsigned char *buffer;
/* Number of bytes to which `buffer' points. */
unsigned long int allocated;
/* Number of bytes actually used in `buffer'. */
unsigned long int used;
/* Syntax setting with which the pattern was compiled. */
reg_syntax_t syntax;
/* Pointer to a fastmap, if any, otherwise zero. re_search uses the
fastmap, if there is one, to skip over impossible starting points
for matches. */
char *fastmap;
/* Either a translate table to apply to all characters before
comparing them, or zero for no translation. The translation is
applied to a pattern when it is compiled and to a string when it
is matched. */
RE_TRANSLATE_TYPE translate;
/* Number of subexpressions found by the compiler. */
size_t re_nsub;
/* Zero if this pattern cannot match the empty string, one else.
Well, in truth it's used only in `re_search_2', to see whether or
not we should use the fastmap, so we don't set this absolutely
perfectly; see `re_compile_fastmap' (the `duplicate' case). */
unsigned can_be_null : 1;
/* If REGS_UNALLOCATED, allocate space in the `regs' structure
for `max (RE_NREGS, re_nsub + 1)' groups.
If REGS_REALLOCATE, reallocate space if necessary.
If REGS_FIXED, use what's there. */
#define REGS_UNALLOCATED 0
#define REGS_REALLOCATE 1
#define REGS_FIXED 2
unsigned regs_allocated : 2;
/* Set to zero when `regex_compile' compiles a pattern; set to one
by `re_compile_fastmap' if it updates the fastmap. */
unsigned fastmap_accurate : 1;
/* If set, `re_match_2' does not return information about
subexpressions. */
unsigned no_sub : 1;
/* If set, a beginning-of-line anchor doesn't match at the beginning
of the string. */
unsigned not_bol : 1;
/* Similarly for an end-of-line anchor. */
unsigned not_eol : 1;
/* If true, an anchor at a newline matches. */
unsigned newline_anchor : 1;
};
typedef struct re_pattern_buffer regex_t;
/* Type for byte offsets within the string. POSIX mandates this. */
typedef int regoff_t;
/* This is the structure we store register match data in. See
regex.texinfo for a full description of what registers match. */
struct re_registers
{
unsigned num_regs;
regoff_t *start;
regoff_t *end;
};
/* If `regs_allocated' is REGS_UNALLOCATED in the pattern buffer,
`re_match_2' returns information about at least this many registers
the first time a `regs' structure is passed. */
#ifndef RE_NREGS
# define RE_NREGS 30
#endif
/* POSIX specification for registers. Aside from the different names than
`re_registers', POSIX uses an array of structures, instead of a
structure of arrays. */
typedef struct
{
regoff_t rm_so; /* Byte offset from string's start to substring's start. */
regoff_t rm_eo; /* Byte offset from string's start to substring's end. */
} regmatch_t;
/* Declarations for routines. */
/* Sets the current default syntax to SYNTAX, and return the old syntax.
You can also simply assign to the `re_syntax_options' variable. */
extern reg_syntax_t re_set_syntax (reg_syntax_t __syntax);
/* Compile the regular expression PATTERN, with length LENGTH
and syntax given by the global `re_syntax_options', into the buffer
BUFFER. Return NULL if successful, and an error string if not. */
extern const char *re_compile_pattern (const char *__pattern, size_t __length,
struct re_pattern_buffer *__buffer);
/* Compile a fastmap for the compiled pattern in BUFFER; used to
accelerate searches. Return 0 if successful and -2 if was an
internal error. */
extern int re_compile_fastmap (struct re_pattern_buffer *__buffer);
/* Search in the string STRING (with length LENGTH) for the pattern
compiled into BUFFER. Start searching at position START, for RANGE
characters. Return the starting position of the match, -1 for no
match, or -2 for an internal error. Also return register
information in REGS (if REGS and BUFFER->no_sub are nonzero). */
extern int re_search (struct re_pattern_buffer *__buffer, const char *__string,
int __length, int __start, int __range,
struct re_registers *__regs);
/* Like `re_search', but search in the concatenation of STRING1 and
STRING2. Also, stop searching at index START + STOP. */
extern int re_search_2 (struct re_pattern_buffer *__buffer,
const char *__string1, int __length1,
const char *__string2, int __length2, int __start,
int __range, struct re_registers *__regs, int __stop);
/* Like `re_search', but return how many characters in STRING the regexp
in BUFFER matched, starting at position START. */
extern int re_match (struct re_pattern_buffer *__buffer, const char *__string,
int __length, int __start, struct re_registers *__regs);
/* Relates to `re_match' as `re_search_2' relates to `re_search'. */
extern int re_match_2 (struct re_pattern_buffer *__buffer,
const char *__string1, int __length1,
const char *__string2, int __length2, int __start,
struct re_registers *__regs, int __stop);
/* Set REGS to hold NUM_REGS registers, storing them in STARTS and
ENDS. Subsequent matches using BUFFER and REGS will use this memory
for recording register information. STARTS and ENDS must be
allocated with malloc, and must each be at least `NUM_REGS * sizeof
(regoff_t)' bytes long.
If NUM_REGS == 0, then subsequent matches should allocate their own
register data.
Unless this function is called, the first search or match using
PATTERN_BUFFER will allocate its own register data, without
freeing the old data. */
extern void re_set_registers (struct re_pattern_buffer *__buffer,
struct re_registers *__regs,
unsigned int __num_regs,
regoff_t *__starts, regoff_t *__ends);
#if defined _REGEX_RE_COMP || defined _LIBC
# ifndef _CRAY
/* 4.2 bsd compatibility. */
extern char *re_comp (const char *);
extern int re_exec (const char *);
# endif
#endif
/* GCC 2.95 and later have "__restrict"; C99 compilers have
"restrict", and "configure" may have defined "restrict". */
#ifndef __restrict
# if ! (2 < __GNUC__ || (2 == __GNUC__ && 95 <= __GNUC_MINOR__))
# if defined restrict || 199901L <= __STDC_VERSION__
# define __restrict restrict
# else
# define __restrict
# endif
# endif
#endif
/* gcc 3.1 and up support the [restrict] syntax. */
#ifndef __restrict_arr
# if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) \
&& !defined __GNUG__
# define __restrict_arr __restrict
# else
# define __restrict_arr
# endif
#endif
/* POSIX compatibility. */
extern int regcomp (regex_t *__restrict __preg,
const char *__restrict __pattern,
int __cflags);
extern int regexec (const regex_t *__restrict __preg,
const char *__restrict __string, size_t __nmatch,
regmatch_t __pmatch[__restrict_arr],
int __eflags);
extern size_t regerror (int __errcode, const regex_t *__restrict __preg,
char *__restrict __errbuf, size_t __errbuf_size);
extern void regfree (regex_t *__preg);
#ifdef __cplusplus
}
#endif /* C++ */
#endif /* regex.h */
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff. Show more