Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
sdk/cloud: renders on a GPU or a CPU from one image, render jobs, and a CPU box that hands its renders to a GPU worker (docs/cloud.feature CL13-CL15)
shinyobjectz3725537f3548
diff --git a/docs/cloud.feature b/docs/cloud.featureindex cce97ee3..45ee7c7f 100644--- a/docs/cloud.feature+++ b/docs/cloud.feature@@ -7,6 +7,9 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)with a TypeScript client. The cloud node image (apps/site/api/container) proved raea renders in a Linux containeron Mesa's llvmpipe. sdk/cloud makes them one module a developer deploys on their own account, wherever they runcontainers. raea sells no cloud compute: the server, the GPU and the agent's subscription are the developer's.+ Shane, later that day: "i mean the point is we provide a way to deploy raea to gpu and cpu". So one image runs on+ either and says which it's using, a GPU is a deploy target proven on a real NVIDIA card, and a cheap always-on CPU+ box (the agent's) hands its renders to a GPU worker that sleeps when idle.Background:Given one image, raea-cloud: Node 24 on Debian trixie, raea's Linux release (x86_64, checked against its .sha256),@@ -31,7 +34,8 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)Rule: one port, one tokenScenario: CL4. The server answers on :8080Then GET /healthz is "ok" without a token, for platform health checks- And GET /v1/health says raea's version, the default agent, the installed agents and the workspace+ And GET /v1/health says raea's version, the default agent, the installed agents, the workspace, the device raea+ renders on (CL13), the GPU worker it hands renders to (CL15) and the render jobs it holds (CL14)And every other route refuses a request without the token (Authorization: Bearer, or ?token= for a browser'sWebSocket) with 401, compared in constant time, and the server won't start without oneScenario: CL5. Files go in and out of the workspace@@ -54,20 +58,49 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)Then deploy/compose.yaml runs it with the home folder on a named volume, and deploy/compose.gpu.yaml adds anNVIDIA GPU (graphics capability, so Vulkan sees it)Scenario: CL10. The platforms- Then deploy/ has a Fly Machines app (a volume, stopped when idle, woken by a request), Kubernetes manifests- (a PersistentVolumeClaim, a Secret, a Deployment and a Service), and a Cloudflare Container (a Worker in- front, the container asleep when idle)- And where the disk doesn't outlive the container (Cloudflare), RAEA_CLOUD_STATE names an S3-compatible object- (R2, S3) the home folder is restored from on start and saved to on stop+ Then deploy/ has a Fly Machines app (a volume, stopped when idle, woken by a request) and Kubernetes manifests+ (a PersistentVolumeClaim, a Secret, a Deployment and a Service)+ And where the disk doesn't outlive the container (Cloudflare Containers, Cloud Run), RAEA_CLOUD_STATE names an+ S3-compatible object (R2, S3) the home folder is restored from on start and saved to on stop+ Scenario: CL10b. Cloudflare Containers+ Then deploy/ has a Cloudflare Container config: a Worker in front, the container asleep when idle, its home in R2Scenario: CL11. The TypeScript clientThen `new RaeaCloud({ url, token })` from sdk/cloud/src has health, read, write, list, run, login and session;a session is ACP: prompt(text, onUpdate) resolves with the stop reason, permission requests go toonPermission (allowed once by default: the container is the sandbox)And it runs on Node 22+, Bun and in a browser (fetch and WebSocket only)+ Rule: it renders on a GPU or a CPU+ Scenario: CL13. One image for both, and it says which+ Given a container given an NVIDIA GPU (Compose's gpu overlay, Kubernetes' nvidia.com/gpu, Modal), an AMD card in+ /dev/dri, or none+ Then the entrypoint opens NVIDIA's Vulkan driver when the host passed one in (the host's ICD file, else the+ image's, naming the library the NVIDIA runtime mounts), and raea renders on it; otherwise on Mesa (radv for+ an AMD card, llvmpipe on the CPU)+ And RAEA_CLOUD_DEVICE=gpu makes a GPU that doesn't open an error at start, never a quiet fall back to the CPU;+ RAEA_CLOUD_DEVICE=cpu keeps raea on llvmpipe+ And /v1/health's device says where renders run (gpu or cpu), on which device, and NVIDIA's own report+ And test/gpu/edit.tsx (576 lit, shadowed blocks, 1920x1080, 90 frames) times the same render on the GPU and on+ the CPU of one server+ Scenario: CL14. A render job, and a GPU that sleeps when idle+ Then POST /v1/jobs?args=JSON takes a project as a tar (zstd, gzip or none) and runs `raea ARGS` on it in a folder+ of its own; GET /v1/jobs/ID?from=N follows its output in requests of 20 s at most (a serverless platform's+ proxy cuts longer ones); GET /v1/jobs/ID/out returns the files it made or changed, and the job is dropped+ And deploy/modal/raea_cloud.py runs the image on a Modal GPU (an L4, else an A10G, else a T4, unless+ RAEA_CLOUD_GPU names others or none), one container that starts on a request and stops after five idle+ minutes, the token in a Modal secret+ Scenario: CL15. A CPU box hands its renders to a GPU worker+ Given RAEA_CLOUD_GPU_URL and RAEA_CLOUD_GPU_TOKEN on a CPU box (the agent's, always on, cheap)+ Then `raea render` there, from the agent, its shell or /v1/run, sends the render's project to the worker as a+ job and lands what it made back in the project; its paths are made relative to the project, an output outside+ it is moved to its place after, and an input outside it renders on the box with a line saying why+ And a worker that can't be reached fails the render unless RAEA_CLOUD_GPU_FALLBACK=cpu+ And every other raea command runs on the box+Rule: it is proven end to endScenario: CL12. A stand-in agent, then a real one- Then test/smoke.sh builds the image, starts it, and checks CL4-CL7 with test/echo-agent.mjs (a scripted ACP- agent): the token refused, a path escape refused, a frame rendered by /v1/run, an ACP turn round-tripped+ Then test/smoke.sh builds the image, starts it, and checks CL4-CL7, CL14 and CL15 with test/echo-agent.mjs (a+ scripted ACP agent): the token refused, a path escape refused, a frame rendered by /v1/run, a render job's file+ back, a second container handing its render to the first, an ACP turn round-trippedAnd with Kimi Code signed in, one real turn renders a title card with raea in the container, and the filecomes back through /v1/filesdiff --git a/sdk/cloud/.dockerignore b/sdk/cloud/.dockerignorenew file mode 100644index 00000000..4770de06--- /dev/null+++ b/sdk/cloud/.dockerignore@@ -0,0 +1,4 @@+node_modules+deploy+test+README.mddiff --git a/sdk/cloud/README.md b/sdk/cloud/README.mdindex 0e8280ab..2721fa7c 100644--- a/sdk/cloud/README.md+++ b/sdk/cloud/README.md@@ -1,13 +1,21 @@# raea cloudraea and an ACP agent on a server of your own. One image holds raea's Linux release, the agents you choose and a-small server; you deploy it wherever you run containers, and talk to it over HTTP and ACP. raea doesn't host it: the+small server. You deploy it wherever you run containers, and talk to it over HTTP and ACP. raea doesn't host it: theserver, the GPU and the agent's subscription are yours. Spec: [docs/cloud.feature](../../docs/cloud.feature).```-your code ── RaeaCloud (src/) ──▶ :8080 raea-cloud server ──▶ raea (render, play, check, ...)+your code ── RaeaCloud (src/) ──▶ :8080 raea-cloud server ──▶ raea (render, play, check, ...) on a GPU or the CPUHTTPS + one token /v1/acp (WebSocket) ──▶ the agent, over ACP, in ~/work- /v1/files, /v1/run, /v1/login, /v1/health+ /v1/files, /v1/run, /v1/jobs, /v1/login, /v1/health+```++One image runs on a CPU or an NVIDIA GPU and says which (`/v1/health`'s `device`). Two shapes:++```+A. one server agent + raea ── on a GPU host, or a CPU host+B. a box and a worker agent + raea (CPU, always on, cheap) ── raea render ──▶ GPU worker (asleep when idle)+ RAEA_CLOUD_GPU_URL /v1/jobs: the project in, what it made back```## Run it@@ -60,10 +68,13 @@ once by default (the container is the sandbox); pass `onPermission` to decide th| Route | ||---|---|| `GET /healthz` | `ok`, without the token, for health checks |-| `GET /v1/health` | raea's version, the default agent, the installed agents, the workspace |+| `GET /v1/health` | raea's version, the agents, the workspace, the device raea renders on, the GPU worker it hands renders to || `GET /v1/files?path=P` | a file in the workspace, or a folder's entries as JSON || `PUT /v1/files?path=P` | writes the body there, making its folders || `POST /v1/run` `{args, cwd}` | `raea ARGS` in the workspace; NDJSON `{out}`, `{err}`, then `{exit}` |+| `POST /v1/jobs?args=JSON` | a render job: the body is a project as a tar (zstd, gzip or none), `raea ARGS` runs on it; `{id}` |+| `GET /v1/jobs/ID?from=N` | the job's output since line N (held up to 20 s for more), and `exit` once it's done |+| `GET /v1/jobs/ID/out?as=zst` | the files the job made or changed, as a tar (`zst`, `gz` or `tar`); the job is dropped || `POST /v1/login?agent=ID` | an agent's terminal sign-in: `{url, code, state}`; `GET` says where it is || `WS /v1/acp?agent=ID` | one agent per socket; each text frame is one ACP JSON-RPC message |@@ -78,10 +89,10 @@ outside the workspace are refused, symlinks out of it too. The agent and raea ne| Compose with an NVIDIA GPU | `+ deploy/compose.gpu.yaml` | a named volume | not yet on a GPU host || Fly Machines | `deploy/fly.toml` | a Fly volume; the Machine stops when idle | config only || Kubernetes | `deploy/k8s.yaml` | a PersistentVolumeClaim | config only |-| Cloudflare Containers | `deploy/cloudflare/` | R2, through `RAEA_CLOUD_STATE` | config only || Any Linux VM | `docker run`, as above | a named volume | as Docker |-Where the disk doesn't outlive the container, set `RAEA_CLOUD_STATE` to an S3-compatible object (R2, S3) with+Where the disk doesn't outlive the container (Cloudflare Containers, Cloud Run), set `RAEA_CLOUD_STATE` to an+S3-compatible object (R2, S3) with`RAEA_CLOUD_STATE_KEY` and `RAEA_CLOUD_STATE_SECRET`: the home folder is restored from it on start and saved to itwhen the container stops (image/state.sh).@@ -89,10 +100,67 @@ Each file says how to deploy with it at its top.## Renders: CPU or GPU-raea renders through Vulkan. In a container without a GPU that's Mesa's llvmpipe on the CPU: right for stills, short-clips and checks, and faster with more cores. For long or heavy renders give the container an NVIDIA GPU-(compose.gpu.yaml, or `nvidia.com/gpu` on Kubernetes) with the graphics capability, so the toolkit mounts NVIDIA's-Vulkan driver.+raea renders through Vulkan. On start the entrypoint opens NVIDIA's Vulkan driver when the host passed a GPU in, and+raea renders on it; with no GPU it renders on Mesa's llvmpipe, on the CPU (an AMD card in `/dev/dri` gets Mesa's+radv). `GET /v1/health` says which:++```json+"device": { "renders": "gpu", "name": "NVIDIA L4", "nvidia": ["NVIDIA L4, 23034 MiB, 610.57.04"], "gpus": [...] }+```++`RAEA_CLOUD_DEVICE=gpu` makes a GPU that doesn't open an error at start, so a worker meant for a GPU never renders on+its CPU unnoticed; `RAEA_CLOUD_DEVICE=cpu` keeps raea on llvmpipe.++What one render costs where (`test/gpu/edit.tsx`: 576 lit blocks with shadows, 1920x1080, 90 frames, on Modal 11-10):++| Device | 90 frames | a frame |+|---|---|---|+| NVIDIA A10 | 115 s | 1229 ms |+| NVIDIA A10G | 133 s | 1392 ms |+| NVIDIA T4 | 156 s | 1652 ms |+| llvmpipe, 8 CPU cores of the T4's host | 203 s | 2005 ms |++That scene spends most of its time outside the GPU, so a GPU buys about 1.2-1.6x on it; heavier lighting (Solari,+path tracing) needs one.++Building your own image instead: NVIDIA's Vulkan driver, mounted by the container runtime, loads only with glvnd and+X11's libraries beside it (`libxext6 libx11-6 libgl1 libegl1` on Debian). With libEGL in the image, wgpu would pick+NVIDIA's OpenGL over llvmpipe for a CPU render and fail, so the image sets `WGPU_BACKEND=vulkan` and the entrypoint+hides EGL's vendors when it renders on the CPU.++**A. One server on a GPU.** Give the container an NVIDIA GPU: `compose.gpu.yaml`, `nvidia.com/gpu: 1` on Kubernetes,+or `deploy/modal/raea_cloud.py`. The image asks for the graphics capability, so the NVIDIA runtime mounts the Vulkan+driver.++**B. A CPU box that hands its renders to a GPU worker.** The agent lives on a small always-on CPU server; renders go+to a GPU that sleeps when idle. Deploy a worker (Modal below, or `deploy/k8s.gpu.yaml`), then set on the box:++```bash+RAEA_CLOUD_GPU_URL=https://you--raea-cloud-server.modal.run+RAEA_CLOUD_GPU_TOKEN=<the worker's token>+```++From then on, `raea render` on the box (from the agent, its shell or `/v1/run`) sends the render's project (its+folder, or the nearest one above with `package.json`, `raea.lock` or `brief.ts`; without `.git` or `out/`) to the+worker as a job, prints its output as it comes and lands the files it made back in the project. Every other raea+command runs on the box. An input outside the project renders on the box, with a line saying why;+`RAEA_CLOUD_GPU_ROOT` sends a wider folder. A worker that doesn't answer fails the render, unless+`RAEA_CLOUD_GPU_FALLBACK=cpu`. The project's `out/` goes to the worker empty, and raea renders only into a folder+that exists, so render into `out/` or another folder the project has.++The same jobs work from your own code: `cloud.job(["render", "edit.tsx", "-o", "out/a.mp4"], projectTar)`.++### A GPU on Modal++```bash+cd sdk/cloud+modal secret create raea-cloud RAEA_CLOUD_TOKEN=$(openssl rand -hex 32)+modal deploy deploy/modal/raea_cloud.py # an L4, else A10G, else T4; RAEA_CLOUD_GPU=L40S (or a list) for others+```++Modal builds the image from `image/Dockerfile`. One container takes every request (a job is followed on the+container that runs it); it starts on a request and stops after five idle minutes (`RAEA_CLOUD_IDLE`), so you pay+for the minutes it renders.## Known limitsdiff --git a/sdk/cloud/deploy/k8s.gpu.yaml b/sdk/cloud/deploy/k8s.gpu.yamlnew file mode 100644index 00000000..695ea4b1--- /dev/null+++ b/sdk/cloud/deploy/k8s.gpu.yaml@@ -0,0 +1,51 @@+# A GPU render worker for raea cloud on Kubernetes (docs/cloud.feature CL13, CL15): the same image on a node with an+# NVIDIA GPU, no agent and no volume, that k8s.yaml's server hands its renders to. The node needs NVIDIA's driver and+# its device plugin (or the GPU Operator); the image asks for the graphics capability, so Vulkan sees the card.+#+# kubectl create secret generic raea-cloud-gpu --from-literal=RAEA_CLOUD_TOKEN=$(openssl rand -hex 32)+# kubectl apply -f deploy/k8s.gpu.yaml+#+# then uncomment RAEA_CLOUD_GPU_URL and RAEA_CLOUD_GPU_TOKEN in k8s.yaml and apply it again. RAEA_CLOUD_DEVICE=gpu+# makes a pod whose GPU doesn't open fail to start, so it never renders on its CPU unnoticed. Scale it to 0 replicas+# between batches of renders (kubectl scale deploy/raea-cloud-gpu --replicas=0); the server then fails its renders+# with a line saying the worker didn't answer, unless it sets RAEA_CLOUD_GPU_FALLBACK=cpu.+apiVersion: apps/v1+kind: Deployment+metadata:+ name: raea-cloud-gpu+spec:+ # one replica: a render job is followed on the pod that runs it+ replicas: 1+ strategy: { type: Recreate }+ selector:+ matchLabels: { app: raea-cloud-gpu }+ template:+ metadata:+ labels: { app: raea-cloud-gpu }+ spec:+ securityContext: { runAsUser: 1000, runAsGroup: 1000, fsGroup: 1000 }+ containers:+ - name: raea+ image: ghcr.io/YOUR-ORG/raea-cloud:0.1.1+ ports:+ - containerPort: 8080+ envFrom:+ - secretRef: { name: raea-cloud-gpu }+ env:+ - { name: RAEA_CLOUD_DEVICE, value: gpu }+ readinessProbe:+ httpGet: { path: /healthz, port: 8080 }+ periodSeconds: 10+ resources:+ requests: { cpu: "4", memory: 8Gi }+ limits: { memory: 16Gi, nvidia.com/gpu: 1 }+ terminationGracePeriodSeconds: 60+---+apiVersion: v1+kind: Service+metadata:+ name: raea-cloud-gpu+spec:+ selector: { app: raea-cloud-gpu }+ ports:+ - { port: 8080, targetPort: 8080 }diff --git a/sdk/cloud/deploy/k8s.yaml b/sdk/cloud/deploy/k8s.yamlindex 778de767..1f95d989 100644--- a/sdk/cloud/deploy/k8s.yaml+++ b/sdk/cloud/deploy/k8s.yaml@@ -5,8 +5,9 @@# kubectl apply -f deploy/k8s.yaml# kubectl port-forward svc/raea-cloud 8080:8080 # or put an Ingress in front of the Service#-# Agents' keys go in the same Secret (--from-literal=ANTHROPIC_API_KEY=...). For a GPU node, uncomment the GPU lines:-# NVIDIA's device plugin hands the container the GPU, and NVIDIA_DRIVER_CAPABILITIES=all its Vulkan driver.+# Agents' keys go in the same Secret (--from-literal=ANTHROPIC_API_KEY=...). This server renders on its CPU; to render+# on a GPU, add deploy/k8s.gpu.yaml: a GPU worker this one hands its renders to (CL15), or give this Deployment the GPU+# itself with `nvidia.com/gpu: 1` under limits (CL13).apiVersion: v1kind: PersistentVolumeClaimmetadata:@@ -45,7 +46,10 @@ spec:- secretRef: { name: raea-cloud }env:- { name: RAEA_AGENT, value: kimi-code }- # - { name: NVIDIA_DRIVER_CAPABILITIES, value: all }+ # with deploy/k8s.gpu.yaml applied, renders go to the GPU worker:+ # - { name: RAEA_CLOUD_GPU_URL, value: "http://raea-cloud-gpu:8080" }+ # - name: RAEA_CLOUD_GPU_TOKEN+ # valueFrom: { secretKeyRef: { name: raea-cloud-gpu, key: RAEA_CLOUD_TOKEN } }volumeMounts:- { name: home, mountPath: /home/raea }readinessProbe:@@ -54,7 +58,6 @@ spec:resources:requests: { cpu: "2", memory: 4Gi }limits: { memory: 8Gi }- # nvidia.com/gpu: 1terminationGracePeriodSeconds: 60volumes:- name: homediff --git a/sdk/cloud/deploy/modal/raea_cloud.py b/sdk/cloud/deploy/modal/raea_cloud.pynew file mode 100644index 00000000..6306ceef--- /dev/null+++ b/sdk/cloud/deploy/modal/raea_cloud.py@@ -0,0 +1,57 @@+# raea cloud on Modal (docs/cloud.feature CL14): the image from image/Dockerfile, built by Modal, on an NVIDIA GPU that+# starts on the first request and stops when idle. From sdk/cloud:+#+# modal secret create raea-cloud RAEA_CLOUD_TOKEN=$(openssl rand -hex 32)+# modal deploy deploy/modal/raea_cloud.py # an L4, else an A10G, else a T4+# RAEA_CLOUD_GPU=L40S modal deploy deploy/modal/raea_cloud.py # one kind: T4, A10G, L40S, A100, H100, ... (Modal's)+# RAEA_CLOUD_GPU=none modal deploy deploy/modal/raea_cloud.py # CPU only, app raea-cloud-cpu+#+# The URL it prints is the server: GET /v1/health says which GPU raea renders on. Use it as a render worker for a CPU+# box (RAEA_CLOUD_GPU_URL, RAEA_CLOUD_GPU_TOKEN there) or on its own, agent and all.+#+# - A comma list is a fallback order: Modal starts the first kind it has free (L4s ran out for ten minutes on 11-10).+# - One container takes every request (max_containers=1): a render job is followed on the container that runs it.+# - It stops after RAEA_CLOUD_IDLE seconds without a request (300), and a request wakes it: about a minute cold.+# - Its home folder is the container's own, so it starts clean each time unless RAEA_CLOUD_STATE (in the secret) keeps+# it in a bucket; a render worker needs nothing kept.+# - Python because Modal apps are Python.++import os+import subprocess++import modal++HERE = os.path.dirname(os.path.abspath(__file__))+CLOUD = os.path.dirname(os.path.dirname(HERE))+GPU = os.environ.get("RAEA_CLOUD_GPU", "L4,A10G,T4")+GPU = None if GPU.lower() in ("", "none", "cpu") else [g.strip() for g in GPU.split(",") if g.strip()]++image = modal.Image.from_dockerfile(+ os.path.join(CLOUD, "image", "Dockerfile"),+ context_dir=CLOUD,+ build_args={+ "RAEA_VERSION": os.environ.get("RAEA_VERSION", "0.1.1"),+ "AGENTS": os.environ.get("RAEA_CLOUD_AGENTS", "kimi-code"),+ },+ # Modal runs the function in Python, which the image doesn't have+ add_python="3.12",+).entrypoint([])++app = modal.App(os.environ.get("RAEA_CLOUD_APP", "raea-cloud" if GPU else "raea-cloud-cpu"), image=image)+++ gpu=GPU,+ cpu=float(os.environ.get("RAEA_CLOUD_CPU", 8)),+ memory=int(os.environ.get("RAEA_CLOUD_MEMORY", 16384)),+ secrets=[modal.Secret.from_name(os.environ.get("RAEA_CLOUD_SECRET", "raea-cloud"))],+ scaledown_window=int(os.environ.get("RAEA_CLOUD_IDLE", 300)),+ timeout=24 * 3600,+ max_containers=1,+)[email protected](max_inputs=64)[email protected]_server(8080, startup_timeout=600)+def server():+ # gpu: a GPU that doesn't open is an error at start, never a quiet fall back to the CPU+ env = {**os.environ, "RAEA_CLOUD_DEVICE": "gpu" if GPU else "cpu"}+ subprocess.Popen(["/opt/raea-cloud/image/entrypoint.sh"], env=env)diff --git a/sdk/cloud/image/Dockerfile b/sdk/cloud/image/Dockerfileindex 4f6c7ed9..6ff05eb3 100644--- a/sdk/cloud/image/Dockerfile+++ b/sdk/cloud/image/Dockerfile@@ -6,21 +6,26 @@# docker run -p 8080:8080 -e RAEA_CLOUD_TOKEN=$(openssl rand -hex 32) -v raea-home:/home/raea raea-cloud## raea ships for Linux on x86_64 only, so the image is linux/amd64 (an arm64 machine runs it emulated, slowly).-# Renders run on Mesa's llvmpipe (Vulkan on the CPU) unless the container is given a GPU (deploy/compose.gpu.yaml).+# One image for both: given an NVIDIA GPU (deploy/compose.gpu.yaml, Kubernetes' nvidia.com/gpu, Modal) raea renders+# on it, and without one on Mesa's llvmpipe (Vulkan on the CPU); /v1/health says which (CL13).FROM node:24-trixie-slim-# raea's runtime libraries (what its ldd and Vulkan loader need on trixie: tools/release/linux/rl3.sh's list), and-# what the agents and the entrypoint use: git, curl (and its --aws-sigv4 for RAEA_CLOUD_STATE), zstd, script(1)+# raea's runtime libraries (what its ldd and Vulkan loader need: tools/release/linux/rl3.sh's list), and what the+# agents and the entrypoint use: git, curl (and its --aws-sigv4 for RAEA_CLOUD_STATE), zstd, script(1); vulkaninfo,+# which picks and reports the device. NVIDIA's Vulkan driver (libGLX_nvidia, which the container runtime mounts from+# the host) loads through glvnd and X11's libraries: without libxext6 it doesn't load, and without libgl1, libegl1 and+# libx11-6 it loads but gives the Vulkan loader no vkCreateInstance (driver 610.57 on Modal's T4 and A10G, 11-10).RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \ca-certificates curl git zstd xz-utils bzip2 unzip procps less ripgrep \- libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers \+ libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools \+ libxext6 libx11-6 libgl1 libegl1 \&& rm -rf /var/lib/apt/lists/* \&& userdel -r node \&& useradd -m -u 1000 -s /bin/bash raea# raea, checked against its release's .sha256 (and against RAEA_SHA256 too, when it's given)ARG RAEA_VERSION=0.1.1-ARG RAEA_SHA256=+ARG RAEA_SHA256=""ARG RAEA_REPO=shinyobjectz/raeaRUN set -e; f=raea-$RAEA_VERSION-linux-x86_64.tar.gz; u=https://github.com/$RAEA_REPO/releases/download/v$RAEA_VERSION; \cd /tmp && curl -fsSL -o $f "$u/$f" && curl -fsSL -o $f.sha256 "$u/$f.sha256" \@@ -32,17 +37,25 @@ RUN set -e; f=raea-$RAEA_VERSION-linux-x86_64.tar.gz; u=https://github.com/$RAEAWORKDIR /opt/raea-cloudCOPY package.json package-lock.json ./RUN npm ci --omit=dev --no-fund --no-audit --loglevel=error-COPY server server-COPY image/entrypoint.sh image/state.sh image/# the agents, by ACP registry id (cdn.agentclientprotocol.com/registry): kimi-code, claude-acp, codex-acp, gemini,# opencode, ... Their sign-ins and settings live in the home folder; their programs live here, in the image.+COPY server/agents.ts server/ARG AGENTS=kimi-code-RUN node server/agents.ts install $AGENTS && chmod +x image/*.sh+RUN node server/agents.ts install $AGENTS++COPY server server+COPY src src+COPY image/entrypoint.sh image/state.sh image/raea.sh image/nvidia_icd.json image/+# raea on PATH is image/raea.sh: raea itself, or a render handed to a GPU worker (RAEA_CLOUD_GPU_URL)+RUN chmod +x image/*.sh && ln -sf /opt/raea-cloud/image/raea.sh /usr/local/bin/raea# the entrypoint starts as root only to hand a freshly mounted home volume (Fly's, a bind mount) to raea, then drops to-# raea for everything else; a platform that starts it as uid 1000 (Kubernetes' runAsUser) skips that step-ENV HOME=/home/raea NODE_ENV=production PORT=8080+# raea for everything else; a platform that starts it as uid 1000 (Kubernetes' runAsUser) skips that step.+# NVIDIA_*: what the NVIDIA container runtime mounts when the container is given a GPU (graphics for Vulkan)+# WGPU_BACKEND: Bevy takes Vulkan only (the entrypoint's on_cpu says why GL must stay out)+ENV HOME=/home/raea NODE_ENV=production PORT=8080 NVIDIA_VISIBLE_DEVICES=all NVIDIA_DRIVER_CAPABILITIES=all \+ WGPU_BACKEND=vulkanRUN mkdir -p "$HOME/work" && chown -R raea:raea "$HOME"EXPOSE 8080HEALTHCHECK --interval=30s --timeout=5s CMD curl -fsS http://127.0.0.1:8080/healthz || exit 1diff --git a/sdk/cloud/image/entrypoint.sh b/sdk/cloud/image/entrypoint.shindex 180fb25a..a1b0a233 100755--- a/sdk/cloud/image/entrypoint.sh+++ b/sdk/cloud/image/entrypoint.sh@@ -9,12 +9,46 @@ here=/opt/raea-cloud# started as root: give the home folder to raea (a new volume is root's) and go on as raea, environment keptif [ "$(id -u)" = 0 ]; then[ "$(stat -c %u /home/raea)" = 1000 ] || chown -R raea:raea /home/raea+ # a platform may set its own HOME for root (Modal's is /root)+ export HOME=/home/raeaexec setpriv --reuid=raea --regid=raea --init-groups "$0" "$@"fi"$here/image/state.sh" restoremkdir -p "${RAEA_CLOUD_WORK:-$HOME/work}"+# the device raea renders on (CL13). auto: NVIDIA's Vulkan driver when the host passed a GPU in and the driver opens+# it (the host's ICD file, else the image's, which names the library the NVIDIA runtime mounts), else Mesa (llvmpipe+# on the CPU, or radv on an AMD card in /dev/dri). gpu: the same, but no GPU is an error. cpu: llvmpipe only.+device=${RAEA_CLOUD_DEVICE:-auto}+opens() {+ if [ -n "$1" ]; then VK_DRIVER_FILES=$1 timeout 60 vulkaninfo --summary; else timeout 60 vulkaninfo --summary; fi 2>/dev/null |+ grep -q 'PHYSICAL_DEVICE_TYPE_\(DISCRETE\|INTEGRATED\|VIRTUAL\)_GPU'+}+# raea renders through Vulkan. NVIDIA's Vulkan driver needs EGL installed (libegl1), and EGL is also a GL device to+# wgpu: NVIDIA's EGL counts as a discrete GPU and outranked lavapipe, so a render meant for the CPU went to GL and failed+# (11-10). Rendering on the CPU therefore hides EGL's vendors.+on_cpu() {+ # lvp_icd.json (Mesa 24 on), lvp_icd.x86_64.json before+ lvp=$(ls /usr/share/vulkan/icd.d/lvp_icd*.json 2>/dev/null | head -1)+ [ -n "$lvp" ] || { echo "raea-cloud: Mesa's lavapipe (lvp_icd*.json) isn't installed, so raea can't render on the CPU" >&2; exit 1; }+ export VK_DRIVER_FILES=$lvp __EGL_VENDOR_LIBRARY_DIRS=/nonexistent+}+if [ "$device" = cpu ]; then+ on_cpu+elif [ -z "${VK_DRIVER_FILES:-}" ]; then+ for icd in /etc/vulkan/icd.d/nvidia_icd.json /usr/share/vulkan/icd.d/nvidia_icd.json "$here/image/nvidia_icd.json"; do+ [ -f "$icd" ] && opens "$icd" && { export VK_DRIVER_FILES=$icd; break; }+ done+ if [ -z "${VK_DRIVER_FILES:-}" ] && ! opens ""; then+ if [ "$device" = gpu ]; then+ echo "raea-cloud: RAEA_CLOUD_DEVICE=gpu, but no GPU opened (vulkaninfo --summary lists none); was the container given one?" >&2+ exit 1+ fi+ on_cpu+ fi+fi+for a in $(node "$here/server/agents.ts" skills); doraea skills install --agent "$a" >/dev/null 2>&1 || echo "raea-cloud: raea's skills for $a weren't installed"donediff --git a/sdk/cloud/image/nvidia_icd.json b/sdk/cloud/image/nvidia_icd.jsonnew file mode 100644index 00000000..dceddc0d--- /dev/null+++ b/sdk/cloud/image/nvidia_icd.json@@ -0,0 +1,7 @@+{+ "file_format_version": "1.0.1",+ "ICD": {+ "library_path": "libGLX_nvidia.so.0",+ "api_version": "1.3"+ }+}diff --git a/sdk/cloud/image/raea.sh b/sdk/cloud/image/raea.shnew file mode 100644index 00000000..848a0622--- /dev/null+++ b/sdk/cloud/image/raea.sh@@ -0,0 +1,10 @@+#!/bin/sh+# raea in raea cloud's image (docs/cloud.feature CL15): with RAEA_CLOUD_GPU_URL set, `raea render ...` (each command in+# RAEA_CLOUD_GPU_COMMANDS) goes to that GPU worker (server/offload.ts); everything else, and everything when it isn't+# set, is raea itself. The server, the agents and their shells all reach raea through this one.+if [ -n "${RAEA_CLOUD_GPU_URL:-}" ] && [ -n "${1:-}" ]; then+ case " ${RAEA_CLOUD_GPU_COMMANDS:-render} " in+ *" $1 "*) exec node /opt/raea-cloud/server/offload.ts "$@" ;;+ esac+fi+exec /opt/raea/bin/raea "$@"diff --git a/sdk/cloud/package.json b/sdk/cloud/package.jsonindex 93b9eae4..27b60673 100644--- a/sdk/cloud/package.json+++ b/sdk/cloud/package.json@@ -3,7 +3,7 @@"license": "FSL-1.1-ALv2","private": true,"version": "0.1.1",- "description": "raea and an ACP agent on a server of your own (docs/cloud.feature): one image (image/Dockerfile) with raea's Linux release, any agent the ACP registry lists and a small authenticated server, deploy files for Docker, Compose, Fly Machines, Kubernetes and Cloudflare Containers, and a TypeScript client (src/).",+ "description": "raea and an ACP agent on a server of your own (docs/cloud.feature): one image (image/Dockerfile) with raea's Linux release, any agent the ACP registry lists and a small authenticated server, deploy files for Docker, Compose, Fly Machines and Kubernetes, and a TypeScript client (src/).","type": "module","main": "src/index.ts","exports": {diff --git a/sdk/cloud/server/gpu.ts b/sdk/cloud/server/gpu.tsnew file mode 100644index 00000000..8969fad8--- /dev/null+++ b/sdk/cloud/server/gpu.ts@@ -0,0 +1,69 @@+// Which device raea renders on here (docs/cloud.feature CL13): the Vulkan devices this container sees, from+// `vulkaninfo --summary` with the environment raea runs with. raea's 3D goes through wgpu, which takes a GPU over the+// CPU, so it renders on the first device that isn't the CPU's; with none it renders on Mesa's llvmpipe (the CPU).+// The entrypoint has already pointed the Vulkan loader at the GPU's driver when one opened (VK_DRIVER_FILES).++import { execFileSync } from "node:child_process"++export interface Gpu {+ name: string+ type: "discrete" | "integrated" | "virtual" | "cpu" | "other"+ driver: string+ vendor: string+}++export interface Device {+ /** where raea's renders run */+ renders: "gpu" | "cpu"+ /** the device they run on */+ name: string+ gpus: Gpu[]+ /** NVIDIA's own report, when nvidia-smi is here: name, memory, driver */+ nvidia?: string[]+}++/** The devices in `vulkaninfo --summary`'s output. */+export function parseSummary(text: string): Gpu[] {+ const out: Gpu[] = []+ for (const block of text.split(/^GPU\d+:\s*$/m).slice(1)) {+ const field = (k: string) => new RegExp(`^\\s*${k}\\s*=\\s*(.*)$`, "m").exec(block)?.[1].trim() ?? ""+ const t = field("deviceType").replace("PHYSICAL_DEVICE_TYPE_", "").toLowerCase()+ out.push({+ name: field("deviceName"),+ type: t === "discrete_gpu" ? "discrete" : t === "integrated_gpu" ? "integrated" : t === "virtual_gpu" ? "virtual" : t === "cpu" ? "cpu" : "other",+ driver: [field("driverName"), field("driverInfo")].filter(Boolean).join(" "),+ vendor: field("vendorID"),+ })+ }+ return out+}++const RANK = { discrete: 0, integrated: 1, virtual: 2, other: 3, cpu: 4 }++export function pick(gpus: Gpu[]): Pick<Device, "renders" | "name"> {+ const best = [...gpus].sort((a, b) => RANK[a.type] - RANK[b.type])[0]+ return best && best.type !== "cpu" ? { renders: "gpu", name: best.name } : { renders: "cpu", name: best?.name || "llvmpipe" }+}++let cached: Device | undefined++export function device(env: NodeJS.ProcessEnv): Device {+ if (cached) return cached+ let gpus: Gpu[] = []+ try {+ gpus = parseSummary(execFileSync("vulkaninfo", ["--summary"], { encoding: "utf8", env, timeout: 30_000, stdio: ["ignore", "pipe", "ignore"] }))+ } catch {+ // no vulkaninfo, or the loader found nothing: raea falls back the same way+ }+ let nvidia: string[] | undefined+ try {+ nvidia = execFileSync("nvidia-smi", ["--query-gpu=name,memory.total,driver_version", "--format=csv,noheader"], { encoding: "utf8", timeout: 10_000, stdio: ["ignore", "pipe", "ignore"] })+ .trim()+ .split("\n")+ .filter(Boolean)+ } catch {+ // not an NVIDIA host+ }+ cached = { ...pick(gpus), gpus, nvidia }+ return cached+}diff --git a/sdk/cloud/server/jobs.ts b/sdk/cloud/server/jobs.tsnew file mode 100644index 00000000..48626cf4--- /dev/null+++ b/sdk/cloud/server/jobs.ts@@ -0,0 +1,127 @@+// Render jobs (docs/cloud.feature CL14, CL15): a folder sent in, `raea ARGS` run on it here, and the files the run+// made or changed sent back. A CPU box hands its renders to a GPU worker this way (bin/raea, offload.ts); anyone can+// use it to render on this server without a workspace. A job runs in the background and is followed by short+// requests, so a platform's request timeout (a serverless GPU's proxy) never cuts a long render.+//+// POST /v1/jobs?args=JSON body: the folder as a tar (zstd, gzip, xz or none: GNU tar tells). {id}+// GET /v1/jobs/ID?from=N {log: [{out}|{err}], next, exit?}: the output since line N, waiting up to 20 s for+// more while it runs; exit once it has finished+// GET /v1/jobs/ID/out?as=zst the files the run made or changed, as tar.zst (as=gz: tar.gz, as=tar: a plain tar);+// the job is removed after+//+// Jobs live under ~/jobs and are removed an hour after they finish if nobody fetched them.++import { spawn, spawnSync } from "node:child_process"+import { randomUUID } from "node:crypto"+import { mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"+import os from "node:os"+import path from "node:path"++const ROOT = path.join(os.homedir(), "jobs")+const KEEP_MS = 3_600_000++type Line = { out: string } | { err: string }+interface Job {+ id: string+ dir: string+ log: Line[]+ exit?: number+ ended?: number+ before: Map<string, string>+ wake: (() => void)[]+}++const jobs = new Map<string, Job>()++/** Every file under `dir` with its size and modification time, to tell what a run made or changed. */+function snapshot(dir: string, at = dir, into = new Map<string, string>()): Map<string, string> {+ for (const e of readdirSync(at, { withFileTypes: true })) {+ const p = path.join(at, e.name)+ if (e.isDirectory()) snapshot(dir, p, into)+ else if (e.isFile()) {+ const s = statSync(p)+ into.set(path.relative(dir, p), `${s.size}:${s.mtimeMs}`)+ }+ }+ return into+}++function sweep() {+ const now = Date.now()+ for (const j of jobs.values())+ if (j.ended && now - j.ended > KEEP_MS) {+ rmSync(j.dir, { recursive: true, force: true })+ jobs.delete(j.id)+ }+}++/** Starts `raea ARGS` on the folder in `tar` (a tar's bytes, compressed or not). */+export function start(args: string[], tar: Buffer, raea: string, env: NodeJS.ProcessEnv): Job {+ sweep()+ const id = randomUUID()+ const dir = path.join(ROOT, id)+ mkdirSync(dir, { recursive: true })+ const file = path.join(ROOT, `${id}.tar`)+ writeFileSync(file, tar)+ // GNU tar reads the compression from the file, refuses members with .., and strips a leading /, so nothing lands+ // outside the job's folder+ const x = spawnSync("tar", ["-xf", file, "-C", dir, "--no-same-owner", "--no-same-permissions"], { encoding: "utf8" })+ rmSync(file, { force: true })+ if (x.status !== 0) {+ rmSync(dir, { recursive: true, force: true })+ throw new Error(`the folder didn't unpack: ${x.stderr.trim()}`)+ }+ const j: Job = { id, dir, log: [], before: snapshot(dir), wake: [] }+ jobs.set(id, j)+ const push = (l: Line) => {+ j.log.push(l)+ for (const w of j.wake.splice(0)) w()+ }+ const child = spawn(raea, args, { cwd: dir, env, stdio: ["ignore", "pipe", "pipe"] })+ child.stdout.setEncoding("utf8").on("data", (out: string) => push({ out }))+ child.stderr.setEncoding("utf8").on("data", (err: string) => push({ err }))+ child.on("error", (e) => push({ err: String(e) }))+ child.on("close", (code) => {+ j.exit = code ?? 128+ j.ended = Date.now()+ for (const w of j.wake.splice(0)) w()+ })+ return j+}++/** The job's output from line `from`, waiting up to `wait` ms for more while it runs. */+export async function follow(id: string, from: number, wait = 20_000) {+ const j = jobs.get(id)+ if (!j) return undefined+ if (j.log.length <= from && j.exit === undefined) await new Promise<void>((ok) => (j.wake.push(ok), setTimeout(ok, wait)))+ return { log: j.log.slice(from), next: j.log.length, exit: j.exit }+}++const PACK = { zst: ["--zstd"], gz: ["--gzip"], tar: [] } as const+export type Packing = keyof typeof PACK+export const packing = (as: string | null): Packing => (as === "gz" || as === "tar" ? as : "zst")++/** The files the job's run made or changed, as a tar; the job is removed. */+export function out(id: string, as: Packing = "zst"): Buffer | undefined {+ const j = jobs.get(id)+ if (!j || j.exit === undefined) return undefined+ const after = snapshot(j.dir)+ const changed = [...after].filter(([p, s]) => j.before.get(p) !== s).map(([p]) => p)+ const list = path.join(ROOT, `${id}.list`)+ writeFileSync(list, changed.join("\n") + (changed.length ? "\n" : ""))+ const tar = spawnSync("tar", [...PACK[as], "-cf", "-", "-C", j.dir, "--verbatim-files-from", "-T", list], { maxBuffer: 16 << 30 })+ rmSync(list, { force: true })+ rmSync(j.dir, { recursive: true, force: true })+ jobs.delete(id)+ if (tar.status !== 0) throw new Error(`the results didn't pack: ${tar.stderr.toString().trim()}`)+ return tar.stdout+}++/** The ids of the jobs held now, for /v1/health. */+export const held = () => [...jobs.values()].map((j) => ({ id: j.id, running: j.exit === undefined }))++export const readArgs = (q: string | null): string[] => {+ const a = JSON.parse(q ?? "null") as unknown+ if (!Array.isArray(a) || !a.every((x) => typeof x === "string")) throw new Error("args must be a JSON array of strings: raea's own arguments")+ return a+}diff --git a/sdk/cloud/server/main.ts b/sdk/cloud/server/main.tsindex c5c0d9fc..bd813c77 100644--- a/sdk/cloud/server/main.ts+++ b/sdk/cloud/server/main.ts@@ -1,13 +1,17 @@// raea cloud's server (docs/cloud.feature CL4-CL8): raea and an ACP agent behind one port and one token.//// GET /healthz "ok", no token (platform health checks)-// GET /v1/health {raea, agent, agents, workspace}+// GET /v1/health {raea, agent, agents, workspace, device, offload, jobs}: device says whether+// raea renders on a GPU here, and which (gpu.ts)// GET /v1/files?path=P a file in the workspace, or a folder's entries as JSON// PUT /v1/files?path=P writes the body to P, making its folders// POST /v1/run {args, cwd?} `raea ARGS` in the workspace: NDJSON {out} and {err} lines, then {exit}// POST /v1/login?agent=ID an agent's terminal sign-in: {url, code, state, output}; GET says where it is// 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+// 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)//// Every route but /healthz needs RAEA_CLOUD_TOKEN: `Authorization: Bearer TOKEN`, or ?token= (a browser's WebSocket// can't set headers). The agent and raea get the container's environment without the token or the state keys.@@ -19,6 +23,8 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:htimport path from "node:path"import { WebSocketServer } from "ws"import { installed, spawnFor } from "./agents.ts"+import { device } from "./gpu.ts"+import * as jobs from "./jobs.ts"import { login, loginState } from "./login.ts"import { Outside, resolve, WORK } from "./workspace.ts"@@ -109,10 +115,39 @@ const server = createServer(async (req, res) => {return null}})()- return json(res, { raea: raeaVersion(), agent: def, agents: installed().map((a) => ({ id: a.id, version: a.version })), workspace: WORK })+ const gpu = process.env.RAEA_CLOUD_GPU_URL+ return json(res, {+ raea: raeaVersion(),+ 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(),+ })}if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url)if (url.pathname === "/v1/run" && req.method === "POST") return await run(req, res)+ if (url.pathname === "/v1/jobs" && req.method === "POST") {+ const args = jobs.readArgs(url.searchParams.get("args"))+ // a job runs raea here, never handed on again+ const env = childEnv()+ delete env.RAEA_CLOUD_GPU_URL+ delete env.RAEA_CLOUD_GPU_TOKEN+ return json(res, { id: jobs.start(args, await body(req), RAEA, env).id })+ }+ const job = /^\/v1\/jobs\/([0-9a-f-]{36})(\/out)?$/.exec(url.pathname)+ if (job && req.method === "GET") {+ if (job[2]) {+ const as = jobs.packing(url.searchParams.get("as"))+ const tar = jobs.out(job[1], as)+ if (!tar) return json(res, { error: "no finished job with that id" }, 404)+ const type = { zst: "application/zstd", gz: "application/gzip", tar: "application/x-tar" }[as]+ return res.writeHead(200, { "content-type": type, "content-length": tar.length }).end(tar)+ }+ 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/login") {const a = spawnFor(url.searchParams.get("agent") ?? undefined)return json(res, req.method === "POST" ? await login(a, childEnv()) : loginState(a.id))@@ -152,4 +187,10 @@ server.on("upgrade", (req, socket, head) => {})mkdirSync(WORK, { recursive: true })-server.listen(PORT, () => console.log(`raea-cloud: :${PORT}, workspace ${WORK}, agents ${installed().map((a) => a.id).join(", ") || "none"}, raea ${raeaVersion()}`))+server.listen(PORT, () => {+ const d = device(childEnv())+ const gpu = process.env.RAEA_CLOUD_GPU_URL+ console.log(+ `raea-cloud: :${PORT}, workspace ${WORK}, agents ${installed().map((a) => a.id).join(", ") || "none"}, raea ${raeaVersion()}, renders on ${d.renders === "gpu" ? `the GPU (${d.name})` : `the CPU (${d.name})`}${gpu ? `, renders handed to ${gpu}` : ""}`,+ )+})diff --git a/sdk/cloud/server/offload.ts b/sdk/cloud/server/offload.tsnew file mode 100644index 00000000..89a8c37c--- /dev/null+++ b/sdk/cloud/server/offload.ts@@ -0,0 +1,140 @@+// raea on a CPU box with its renders on a GPU worker (docs/cloud.feature CL15). image/raea.sh runs this for+// `raea render ...` when RAEA_CLOUD_GPU_URL names a raea cloud server on a GPU (RAEA_CLOUD_GPU_TOKEN its token):+//+// 1. the render's project goes there as tar.zst: the folder of its composition, or the nearest one above it with+// package.json, raea.lock or brief.ts (RAEA_CLOUD_GPU_ROOT names another), without .git or what's in out/+// (RAEA_CLOUD_GPU_EXCLUDE: tar patterns, space-separated, to send instead);+// 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.+//+// A render that reads a path outside its project (an input, --words, ...) can't go: it runs here, on the CPU, and+// says why. So does every render when the worker can't be reached and RAEA_CLOUD_GPU_FALLBACK=cpu; otherwise that+// fails, so a box meant to render on a GPU never quietly renders on its CPU.++import { spawnSync } from "node:child_process"+import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"+import os from "node:os"+import path from "node:path"+import { pathToFileURL } from "node:url"+import { RaeaCloud } from "../src/index.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+const WRITES = new Set(["-o", "--out", "--audio", "--manifest", "--review"])+const READS = new Set(["--input", "--words", "--perception", "--bundle", "--dir", "--taste"])+const COMPOSITION = /\.(tsx|ts|jsx|js|mjs|html)$/++const say = (s: string) => process.stderr.write(`raea cloud: ${s}\n`)++function local(args: string[], why?: string): never {+ if (why) say(`${why}, so this runs here, on the CPU`)+ const r = spawnSync(REAL, args, { stdio: "inherit" })+ process.exit(r.status ?? 1)+}++const inside = (root: string, p: string) => p === root || p.startsWith(root + path.sep)++/** The project a render's composition is in: its folder, or the nearest above it that holds a project's files. */+export function projectRoot(composition: string, cwd: string, stop = os.homedir()): string {+ const start = path.dirname(path.resolve(cwd, composition))+ for (let d = start; ; d = path.dirname(d)) {+ if (["package.json", "raea.lock", "brief.ts"].some((f) => existsSync(path.join(d, f)))) return d+ if (d === stop || d === path.dirname(d)) return start+ }+}++export interface Plan {+ root: string+ args: string[]+ /** outputs outside the root: where the worker writes them (relative to root), and where they go after */+ moves: { from: string; to: string }[]+}++/** The render's arguments made relative to its project, or why it can't leave this machine. */+export function plan(args: string[], cwd: string, root?: string): Plan | string {+ const comp = args.find((a, i) => i > 0 && !a.startsWith("-") && COMPOSITION.test(a) && !WRITES.has(args[i - 1]))+ const bundle = args[args.indexOf("--bundle") + 1]+ const from = comp ?? (args.includes("--bundle") ? bundle : undefined)+ if (!from) return "this render names no composition"+ const r = root ? path.resolve(cwd, root) : projectRoot(from, cwd)+ const moves: Plan["moves"] = []+ const out: string[] = []+ for (let i = 0; i < args.length; i++) {+ const a = args[i]+ const flag = args[i - 1]+ const isPath = i > 0 && !a.startsWith("-") && (WRITES.has(flag) || READS.has(flag) || a === from || existsSync(path.resolve(cwd, a)))+ if (!isPath) {+ out.push(a)+ continue+ }+ 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)}`)+ moves.push({ from: rel, to: abs })+ out.push(rel)+ } else return `${a} is outside the project sent to the GPU (${r})`+ }+ return { root: r, args: out, moves }+}++async function main() {+ const args = process.argv.slice(2)+ const url = process.env.RAEA_CLOUD_GPU_URL+ const token = process.env.RAEA_CLOUD_GPU_TOKEN ?? ""+ if (!url) local(args)+ const p = plan(args, process.cwd(), process.env.RAEA_CLOUD_GPU_ROOT)+ if (typeof p === "string") local(args, p)++ 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)+ // 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")+ const pack = spawnSync("tar", [gnu ? "--zstd" : "-z", "-cf", sent, ...excludes.map((e) => `--exclude=${e}`), "-C", p.root, "."], { encoding: "utf8" })+ if (pack.status !== 0) throw new Error(`the project didn't pack: ${pack.stderr.trim()}`)+ const folder = new Uint8Array(readFileSync(sent))++ const cloud = new RaeaCloud({ url, token })+ const t0 = performance.now()+ let h+ try {+ h = await cloud.health()+ } catch (e) {+ if (process.env.RAEA_CLOUD_GPU_FALLBACK === "cpu") local(args, `the GPU worker at ${url} didn't answer (${(e as Error).message})`)+ 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`)+ const { exit, files } = await cloud.job(p.args, folder, { as: gnu ? "zst" : "gz", onOutput: (t, s) => (s === "out" ? process.stdout : process.stderr).write(t) })++ const back = path.join(tmp, "out.tar")+ writeFileSync(back, files)+ const unpack = spawnSync("tar", ["-xf", back, "-C", p.root], { encoding: "utf8" })+ if (unpack.status !== 0) throw new Error(`the results didn't unpack: ${unpack.stderr.trim()}`)+ for (const m of p.moves) {+ const from = path.join(p.root, m.from)+ if (!existsSync(from)) continue+ mkdirSync(path.dirname(m.to), { recursive: true })+ // a move across filesystems (into /tmp) is a copy+ try {+ renameSync(from, m.to)+ } catch {+ spawnSync("cp", ["-R", from, m.to])+ }+ }+ rmSync(path.join(p.root, ".raea-cloud-out"), { recursive: true, force: true })+ say(`done on the GPU worker in ${((performance.now() - t0) / 1000).toFixed(1)} s, exit ${exit}`)+ process.exitCode = exit+ } finally {+ rmSync(tmp, { recursive: true, force: true })+ }+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)+ main().catch((e) => {+ say((e as Error).message)+ process.exit(1)+ })diff --git a/sdk/cloud/src/index.ts b/sdk/cloud/src/index.tsindex cd49796d..950762d1 100644--- a/sdk/cloud/src/index.ts+++ b/sdk/cloud/src/index.ts@@ -9,6 +9,8 @@// 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()+// const { exit, files } = await cloud.job(["render", "edit.tsx", "-o", "out/a.mp4"], projectTar) // a render job:+// // a project in as a tar, what the render made back as one (CL14)import { Session, type Permission } from "./session.ts"@@ -19,6 +21,17 @@ export interface Health {agent: string | nullagents: { id: string; version: string }[]workspace: string+ /** where raea renders on this server: a GPU (and which) or the CPU */+ device: { renders: "gpu" | "cpu"; name: string; gpus: { name: string; type: string; driver: string; vendor: string }[]; nvidia?: string[] }+ /** the GPU worker this server hands its renders to, when it has one */+ offload: { url: string; commands: string[] } | null+ jobs: { id: string; running: boolean }[]+}++export interface JobLog {+ log: ({ out: string } | { err: string })[]+ next: number+ exit?: number}export interface Entry {@@ -91,6 +104,45 @@ export class RaeaCloud {throw new Error("raea's run ended without an exit code")}+ /** Starts `raea ARGS` on a folder sent as a tar (zstd, gzip or none), in a folder of its own on the server (a+ * render job): its id. */+ async startJob(args: string[], folder: Uint8Array, signal?: AbortSignal): Promise<string> {+ const r = await this.call(`/v1/jobs?args=${encodeURIComponent(JSON.stringify(args))}`, { method: "POST", body: new Blob([folder as BlobPart]), headers: { "content-type": "application/octet-stream" }, signal })+ return ((await r.json()) as { id: string }).id+ }++ /** A job's output since line `from`; the server holds the request up to 20 s for more. `exit` once it's done. */+ followJob(id: string, from = 0, signal?: AbortSignal): Promise<JobLog> {+ return this.call(`/v1/jobs/${id}?from=${from}`, { signal }).then((r) => r.json())+ }++ /** 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.call(`/v1/jobs/${id}/out?as=${as}`)).arrayBuffer())+ }++ /** A job from start to end: its output to onOutput as it comes; its exit code and the files it made or changed. A+ * dropped follow request (a platform's proxy, a cold start) is tried again, up to five times in a row. */+ async job(args: string[], folder: Uint8Array, o: { onOutput?: (text: string, stream: "out" | "err") => void; signal?: AbortSignal; as?: "zst" | "gz" | "tar" } = {}): Promise<{ exit: number; files: Uint8Array }> {+ const id = await this.startJob(args, folder, o.signal)+ let from = 0+ for (let misses = 0; ; ) {+ let f: JobLog+ try {+ f = await this.followJob(id, from, o.signal)+ misses = 0+ } catch (e) {+ if (o.signal?.aborted || ++misses > 5) throw e+ await new Promise((ok) => setTimeout(ok, 1000 * misses))+ continue+ }+ for (const l of f.log) "out" in l ? o.onOutput?.(l.out, "out") : o.onOutput?.(l.err, "err")+ from = f.next+ if (f.exit !== undefined) return { exit: f.exit, files: await this.jobFiles(id, o.as) }+ }+ }+/** Starts an agent's terminal sign-in (Kimi Code's device code): open `url` and enter `code` once; the sign-in is* kept in the server's home folder. */login(agent?: string): Promise<Login> {diff --git a/sdk/cloud/test/gpu/edit.tsx b/sdk/cloud/test/gpu/edit.tsxnew file mode 100644index 00000000..3204c31c--- /dev/null+++ b/sdk/cloud/test/gpu/edit.tsx@@ -0,0 +1,42 @@+// raea cloud's GPU check (docs/cloud.feature CL13): a lit, shadowed 3D scene heavy enough that a GPU shows, 1920x1080+// at 30 fps for 3 s: 576 turning blocks on a floor under a sun with shadows. test/gpu.sh renders it on a server's GPU+// and on its CPU (llvmpipe) and compares the times.++import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea";+import { Camera3d } from "raea/camera";+import { AmbientLight, DirectionalLight } from "raea/light";+import { Cuboid, Mesh3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { Quat, Transform } from "raea/transform";++const N = 24;+const COLOURS = ["#e05030", "#f0b030", "#30a0e0", "#60c070", "#d0d0d8"];++function Edit() {+ const f = useCurrentFrame();+ const blocks = []+ for (let x = 0; x < N; x++)+ for (let z = 0; z < N; z++) {+ const h = 0.4 + 0.35 * Math.sin(x * 0.7 + z * 0.4 + f * 0.12)+ blocks.push(+ <Mesh3d key={`${x}-${z}`} transform={Transform.fromXyz((x - N / 2) * 0.9, h, (z - N / 2) * 0.9).withRotation(Quat.fromEuler("XYZ", 0, f * 0.03 + x * 0.2, 0))}>+ <Cuboid half_size={[0.32, h, 0.32]} />+ <StandardMaterial base_color={COLOURS[(x + z) % COLOURS.length]} perceptual_roughness={0.35} metallic={(x * z) % 3 === 0 ? 0.8 : 0} />+ </Mesh3d>,+ )+ }+ return (+ <AbsoluteFill style={{ background: "#101018" }}>+ <Camera3d transform={Transform.fromXyz(Math.cos(f * 0.01) * 18, 11, Math.sin(f * 0.01) * 18).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.75 } }} />+ <AmbientLight brightness={120} />+ <DirectionalLight transform={Transform.fromXyz(6, 12, 4).lookingAt([0, 0, 0])} illuminance={20000} shadow_maps_enabled />+ <Mesh3d transform={Transform.fromXyz(0, -0.05, 0)}>+ <Cuboid half_size={[14, 0.05, 14]} />+ <StandardMaterial base_color="#2a2a33" perceptual_roughness={0.8} />+ </Mesh3d>+ {blocks}+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="gpu" component={Edit} width={1920} height={1080} fps={30} durationInFrames={90} />);diff --git a/sdk/cloud/test/smoke.sh b/sdk/cloud/test/smoke.shindex 5be7ce3c..6c84928e 100755--- a/sdk/cloud/test/smoke.sh+++ b/sdk/cloud/test/smoke.sh@@ -1,6 +1,8 @@#!/bin/bash# raea cloud's end-to-end smoke test (docs/cloud.feature CL12): builds the image (unless IMAGE names one), starts it-# with test/echo-agent.mjs as its agent, runs test/smoke.ts against it, and removes the container and its volume.+# with test/echo-agent.mjs as its agent, and a second container (the box) that hands its renders to the first as its+# GPU worker (CL15; both render on the CPU here), runs test/smoke.ts against them, and removes both, their volumes+# and their network.## test/smoke.sh [RAEA_VERSION] default: the version in package.json# IMAGE=raea-cloud:dev test/smoke.sh an image already built@@ -13,21 +15,36 @@ if [ -z "$image" ]; thendocker build --platform linux/amd64 -f "$here/image/Dockerfile" --build-arg RAEA_VERSION="$v" --build-arg AGENTS="${AGENTS:-kimi-code}" -t "$image" "$here" || exit 1finame=raea-cloud-smoke-$$+box=$name-boxtoken=$(openssl rand -hex 32)+boxtoken=$(openssl rand -hex 32)port=${PORT:-18080}-cleanup() { docker rm -f "$name" >/dev/null 2>&1; docker volume rm "$name-home" >/dev/null 2>&1; }+boxport=$((port + 1))+cleanup() {+ docker rm -f "$name" "$box" >/dev/null 2>&1+ docker volume rm "$name-home" "$box-home" >/dev/null 2>&1+ docker network rm "$name" >/dev/null 2>&1+}trap cleanup EXIT-docker run -d --platform linux/amd64 --name "$name" -p "127.0.0.1:$port:8080" -v "$name-home:/home/raea" \+docker network create "$name" >/dev/null || exit 1+docker run -d --platform linux/amd64 --name "$name" --network "$name" -p "127.0.0.1:$port:8080" -v "$name-home:/home/raea" \-v "$here/test:/opt/raea-cloud/test:ro" -e RAEA_CLOUD_TOKEN="$token" \-e RAEA_AGENT=custom -e RAEA_AGENT_CMD="node /opt/raea-cloud/test/echo-agent.mjs" "$image" >/dev/null || exit 1-for _ in $(seq 1 120); do- curl -fsS "http://127.0.0.1:$port/healthz" >/dev/null 2>&1 && break- docker inspect -f '{{.State.Running}}' "$name" 2>/dev/null | grep -q true || { docker logs "$name"; exit 1; }- perl -e 'select(undef,undef,undef,0.5)'+docker run -d --platform linux/amd64 --name "$box" --network "$name" -p "127.0.0.1:$boxport:8080" -v "$box-home:/home/raea" \+ -v "$here/test:/opt/raea-cloud/test:ro" -e RAEA_CLOUD_TOKEN="$boxtoken" \+ -e RAEA_CLOUD_GPU_URL="http://$name:8080" -e RAEA_CLOUD_GPU_TOKEN="$token" \+ -e RAEA_AGENT=custom -e RAEA_AGENT_CMD="node /opt/raea-cloud/test/echo-agent.mjs" "$image" >/dev/null || exit 1+for c in "$name:$port" "$box:$boxport"; do+ for _ in $(seq 1 120); do+ curl -fsS "http://127.0.0.1:${c#*:}/healthz" >/dev/null 2>&1 && break+ docker inspect -f '{{.State.Running}}' "${c%%:*}" 2>/dev/null | grep -q true || { docker logs "${c%%:*}"; exit 1; }+ perl -e 'select(undef,undef,undef,0.5)'+ donedone# a symlink in the workspace that points out of it, for the path checkdocker exec "$name" sh -c 'ln -sfn /etc "$HOME/work/out-link"'-node "$here/test/smoke.ts" "http://127.0.0.1:$port" "$token"+node "$here/test/smoke.ts" "http://127.0.0.1:$port" "$token" "http://127.0.0.1:$boxport" "$boxtoken"code=$?-echo "--- container log"; docker logs "$name" 2>&1 | tail -15+echo "--- worker log"; docker logs "$name" 2>&1 | tail -8+echo "--- box log"; docker logs "$box" 2>&1 | tail -8exit $codediff --git a/sdk/cloud/test/smoke.ts b/sdk/cloud/test/smoke.tsindex 5e03ef9d..18e33150 100644--- a/sdk/cloud/test/smoke.ts+++ b/sdk/cloud/test/smoke.ts@@ -1,10 +1,15 @@// raea cloud's smoke test against a running server (docs/cloud.feature CL12), with test/echo-agent.mjs as its agent:-// node test/smoke.ts URL TOKEN-// smoke.sh starts the container and runs this. Each check prints one line; the exit code is the number that failed.+// node test/smoke.ts URL TOKEN [BOX_URL BOX_TOKEN]+// BOX is a second server that hands its renders to the first (RAEA_CLOUD_GPU_URL; CL15). smoke.sh starts the+// containers and runs this. Each check prints one line; the exit code is the number that failed.+import { spawnSync } from "node:child_process"+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"+import os from "node:os"+import path from "node:path"import { RaeaCloud, type Update } from "../src/index.ts"-const [url, token] = process.argv.slice(2)-if (!url || !token) throw new Error("usage: node test/smoke.ts URL TOKEN")+const [url, token, boxUrl, boxToken] = process.argv.slice(2)+if (!url || !token) throw new Error("usage: node test/smoke.ts URL TOKEN [BOX_URL BOX_TOKEN]")const cloud = new RaeaCloud({ url, token })let failed = 0const check = async (name: string, f: () => Promise<string>) => {@@ -36,7 +41,8 @@ await check("health", async () => {const h = await cloud.health()workspace = h.workspaceexpect(/^\d+\.\d+\.\d+/.test(h.raea), `raea ${h.raea}`)- return `${h.raea}, agent ${h.agent}, installed ${h.agents.map((a) => `${a.id} ${a.version}`).join(", ") || "none"}, ${h.workspace}`+ expect(h.device && (h.device.renders === "gpu" || h.device.renders === "cpu") && h.device.name, `device ${JSON.stringify(h.device)}`)+ return `${h.raea}, agent ${h.agent}, installed ${h.agents.map((a) => `${a.id} ${a.version}`).join(", ") || "none"}, ${h.workspace}, renders on ${h.device.renders} (${h.device.name})`})await check("files round trip", async () => {await cloud.write("smoke/a/b.txt", "hello cloud")@@ -68,6 +74,66 @@ await check("raea renders through /v1/run", async () => {expect(png[0] === 0x89 && png[1] === 0x50, "not a PNG")return `card.png ${png.length} bytes, render ${Math.round(performance.now() - t0)} ms`})+/** A folder of the workspace copied here, file by file through /v1/files. */+async function fetchDir(c: RaeaCloud, rel: string, to: string) {+ mkdirSync(to, { recursive: true })+ for (const e of await c.list(rel))+ if (e.dir) await fetchDir(c, `${rel}/${e.name}`, path.join(to, e.name))+ else writeFileSync(path.join(to, e.name), await c.read(`${rel}/${e.name}`))+}++await check("a render job: a project in, what it made back", async () => {+ const tmp = mkdtempSync(path.join(os.tmpdir(), "raea-cloud-smoke-"))+ try {+ // the project raea init made in the last check, sent back as a job of its own+ await fetchDir(cloud, "smoke/p", path.join(tmp, "p"))+ rmSync(path.join(tmp, "p", "card.png"), { force: true })+ const tar = spawnSync("tar", ["-czf", "-", "-C", path.join(tmp, "p"), "."], { maxBuffer: 1 << 30 })+ expect(tar.status === 0, `tar: ${tar.stderr}`)+ let log = ""+ const t0 = performance.now()+ const { exit, files } = await cloud.job(["render", "edit.tsx", "--frame", "15", "-o", "out/job.png"], new Uint8Array(tar.stdout), { as: "gz", onOutput: (t) => (log += t) })+ expect(exit === 0, `job exit ${exit}: ${log.slice(-400)}`)+ writeFileSync(path.join(tmp, "back.tgz"), files)+ const listed = spawnSync("tar", ["-tzf", path.join(tmp, "back.tgz")], { encoding: "utf8" }).stdout.split("\n").filter(Boolean)+ expect(listed.some((f) => f.replace(/^\.\//, "") === "out/job.png"), `came back: ${listed.join(", ")}`)+ expect(!listed.some((f) => f.endsWith("edit.tsx")), `unchanged files came back: ${listed.join(", ")}`)+ mkdirSync(path.join(tmp, "back"))+ spawnSync("tar", ["-xzf", path.join(tmp, "back.tgz"), "-C", path.join(tmp, "back")])+ const png = readFileSync(path.join(tmp, "back", "out", "job.png"))+ expect(png[0] === 0x89 && png[1] === 0x50, "not a PNG")+ return `out/job.png ${png.length} bytes back of ${listed.length} file(s), ${Math.round(performance.now() - t0)} ms`+ } finally {+ rmSync(tmp, { recursive: true, force: true })+ }+})+await check("jobs: bad args 400, no such job 404", async () => {+ const auth = { authorization: `Bearer ${token}` }+ const a = await status(`/v1/jobs?args=${encodeURIComponent('"render"')}`, { method: "POST", body: "", headers: auth })+ const b = await status("/v1/jobs/00000000-0000-0000-0000-000000000000", { headers: auth })+ const c = await status("/v1/jobs/00000000-0000-0000-0000-000000000000/out", { headers: auth })+ expect(a === 400 && b === 404 && c === 404, `${a}, ${b}, ${c}`)+ return `${a}, ${b}, ${c}`+})+if (boxUrl && boxToken) {+ const box = new RaeaCloud({ url: boxUrl, token: boxToken })+ await check("a CPU box hands its renders to the worker", async () => {+ const h = await box.health()+ expect(h.offload?.url, `the box has no worker: ${JSON.stringify(h.offload)}`)+ let log = ""+ const init = await box.run(["init"], { cwd: "smoke/q", onOutput: (t) => (log += t) })+ expect(init === 0, `raea init exit ${init}: ${log.slice(-400)}`)+ const before = (await cloud.health()).jobs.length+ const r = await box.run(["render", "edit.tsx", "--frame", "15", "-o", "out/handed.png"], { cwd: "smoke/q", onOutput: (t) => (log += t) })+ expect(r === 0, `render exit ${r}: ${log.slice(-600)}`)+ expect(/raea cloud: rendering on .*sent/.test(log) && /done on the GPU worker/.test(log), `not handed on: ${log.slice(-600)}`)+ const png = await box.read("smoke/q/out/handed.png")+ expect(png[0] === 0x89 && png[1] === 0x50, "not a PNG")+ // the worker dropped the job once its files were fetched+ expect((await cloud.health()).jobs.length === before, "the worker still holds the job")+ return `${log.match(/raea cloud: rendering on [^\n]*/)?.[0]}; out/handed.png ${png.length} bytes on the box`+ })+}await check("ACP turn with the stand-in agent", async () => {const s = await cloud.session({ cwd: "smoke" })const said: string[] = []diff --git a/sdk/cloud/test/units.ts b/sdk/cloud/test/units.tsnew file mode 100644index 00000000..d80ac6f0--- /dev/null+++ b/sdk/cloud/test/units.ts@@ -0,0 +1,72 @@+// raea cloud's pure parts, checked without a container: node test/units.ts+// (gpu.ts reads vulkaninfo's summary and picks the device; offload.ts plans which project a render sends and how its+// paths read on the worker)++import assert from "node:assert/strict"+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 { plan, projectRoot } from "../server/offload.ts"++const L4 = `Devices:+========+GPU0:+ apiVersion = 1.3.289+ driverVersion = 580.95.5.0+ vendorID = 0x10de+ deviceID = 0x27b8+ deviceType = PHYSICAL_DEVICE_TYPE_DISCRETE_GPU+ deviceName = NVIDIA L4+ driverID = DRIVER_ID_NVIDIA_PROPRIETARY+ driverName = NVIDIA+ driverInfo = 580.95.05+GPU1:+ apiVersion = 1.4.305+ vendorID = 0x10005+ deviceType = PHYSICAL_DEVICE_TYPE_CPU+ deviceName = llvmpipe (LLVM 19.1.7, 256 bits)+ driverName = llvmpipe+ driverInfo = Mesa 25.0.7-2 (LLVM 19.1.7)+`+const gpus = parseSummary(L4)+assert.equal(gpus.length, 2)+assert.deepEqual(gpus[0], { name: "NVIDIA L4", type: "discrete", driver: "NVIDIA 580.95.05", vendor: "0x10de" })+assert.equal(gpus[1].type, "cpu")+assert.deepEqual(pick(gpus), { renders: "gpu", name: "NVIDIA L4" })+assert.deepEqual(pick([gpus[1]]), { renders: "cpu", name: "llvmpipe (LLVM 19.1.7, 256 bits)" })+assert.deepEqual(pick([]), { renders: "cpu", name: "llvmpipe" })++const root = mkdtempSync(path.join(os.tmpdir(), "raea-units-"))+try {+ const proj = path.join(root, "work", "card")+ mkdirSync(path.join(proj, "scenes"), { recursive: true })+ writeFileSync(path.join(proj, "package.json"), "{}")+ writeFileSync(path.join(proj, "scenes", "edit.tsx"), "")+ writeFileSync(path.join(proj, "words.json"), "[]")+ writeFileSync(path.join(root, "work", "elsewhere.json"), "[]")+ const work = path.join(root, "work")++ // the composition's project is the nearest folder above it with a project's files+ assert.equal(projectRoot("card/scenes/edit.tsx", work, root), proj)+ // from the workspace root: paths made relative to the project, the flags' values left alone+ assert.deepEqual(plan(["render", "card/scenes/edit.tsx", "-o", "card/out/x.mp4", "--frames", "30"], work), {+ root: proj,+ 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+ 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" }])+ // 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+ assert.match(plan(["render", "--help"], proj) as string, /names no composition/)+ // RAEA_CLOUD_GPU_ROOT widens what's sent+ assert.equal((plan(["render", "card/scenes/edit.tsx", "-o", "x.mp4", "--words", "elsewhere.json"], work, ".") as { root: string }).root, work)+} finally {+ rmSync(root, { recursive: true, force: true })+}+console.log("units: ok")diff --git a/sdk/cloud/tsconfig.json b/sdk/cloud/tsconfig.jsonindex e72d333a..cf19a554 100644--- a/sdk/cloud/tsconfig.json+++ b/sdk/cloud/tsconfig.json@@ -1 +1 @@-{ "extends": "../tsconfig.base.json", "compilerOptions": { "types": ["node"], "lib": ["ES2023", "DOM"], "allowImportingTsExtensions": true, "noEmit": true }, "include": ["src", "server", "test"] }+{ "extends": "../tsconfig.base.json", "compilerOptions": { "types": ["node"], "lib": ["ES2023", "DOM"], "allowImportingTsExtensions": true, "noEmit": true }, "include": ["src", "server", "test"], "exclude": ["test/gpu"] }