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: raea and an ACP agent on a developer's own server (docs/cloud.feature CL1-CL12). One image (image/Dockerfile): Node 24 on Debian trixie, raea's Linux release checked against its .sha256, any agent the ACP registry lists installed from its entry at build time (AGENTS=kimi-code claude-acp ...; npm at the registry's version, or a linux archive checked by sha256), and a server on :8080 behind one token: /v1/health, /v1/files (paths confined to the workspace, symlinks out refused), /v1/run (raea ARGS streamed as NDJSON), /v1/login (an agent's terminal sign-in found from its ACP authMethods, under script(1), handing back the device link and code) and /v1/acp (one agent process per WebSocket). The agent and raea never see the token. raea's skills are installed for each agent on every start; RAEA_CLOUD_STATE keeps the home folder in an S3-compatible object where the disk doesn't outlive the container. A TypeScript client (src/, fetch and WebSocket only), and deploy files for Compose (CPU, or an NVIDIA GPU with the graphics capability for Vulkan), Fly Machines and Kubernetes. test/smoke.sh on 0.1.1-rc3's Linux release with a stand-in agent: 8 of 8 (the token refused, four path escapes refused, a frame rendered through /v1/run in 19.5 s under amd64 emulation, an ACP turn with the permission answered); Kimi Code 2.5.3's device sign-in started through /v1/login. The Fly, Kubernetes and GPU files are written, not yet deployed
shinyobjectz98e215b4c94b
diff --git a/docs/cloud.feature b/docs/cloud.featurenew file mode 100644index 00000000..cce97ee3--- /dev/null+++ b/docs/cloud.feature@@ -0,0 +1,73 @@+@spec+Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)+ Shane, 2026-11-10: "getting the kpop concept and its docker image up and running as a true module called cloud and+ would support the many configurations we could set up for deployment of raea engine to the cloud with acp agent.+ this is more of a developer thing for now".+ kpop proved the idea on one Fly Sprite: an agent in the cloud next to raea, spoken to over ACP through a small relay,+ with a TypeScript client. The cloud node image (apps/site/api/container) proved raea renders in a Linux container+ on Mesa's llvmpipe. sdk/cloud makes them one module a developer deploys on their own account, wherever they run+ containers. raea sells no cloud compute: the server, the GPU and the agent's subscription are the developer's.++ Background:+ Given one image, raea-cloud: Node 24 on Debian trixie, raea's Linux release (x86_64, checked against its .sha256),+ the server (sdk/cloud/server) and the agents named when it was built (AGENTS, ACP registry ids)+ And one secret, RAEA_CLOUD_TOKEN, that every request but /healthz carries++ Rule: the image holds raea and any ACP agent+ Scenario: CL1. The image is built from a raea release+ Then `docker build --build-arg RAEA_VERSION=V sdk/cloud` downloads raea V's Linux tarball, checks it against+ the release's .sha256 (and RAEA_SHA256 when given), and `raea --version` in the image says V+ And it runs as a user named raea, the workspace ~/work in raea's home folder+ Scenario: CL2. Agents come from the ACP registry by id+ Given AGENTS="kimi-code claude-acp codex-acp gemini opencode" (any ids the registry lists)+ Then each is installed from its registry entry when the image is built: an npx entry with npm at the registry's+ version, a binary entry from its linux archive checked by sha256; a uvx entry is refused with a reason+ And /opt/raea-cloud/agents/ID/spawn.json says how to start it, and the registry's entry is kept beside it+ And RAEA_AGENT picks the default agent; RAEA_AGENT_CMD runs any other ACP agent by its command line+ Scenario: CL3. Each agent gets raea's skill, matched to the image's raea+ Then on every start `raea skills install --agent A` runs for each installed agent raea has skills for (kimi,+ claude, codex, gemini), so a mounted home from an older image is brought up to date++ Rule: one port, one token+ Scenario: CL4. The server answers on :8080+ Then 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 every other route refuses a request without the token (Authorization: Bearer, or ?token= for a browser's+ WebSocket) with 401, compared in constant time, and the server won't start without one+ Scenario: CL5. Files go in and out of the workspace+ Then PUT /v1/files?path=P writes P (its folders made), GET reads it or lists a folder as JSON+ And a path that leaves the workspace (.., an absolute path, a symlink out) is refused with 403+ Scenario: CL6. raea runs without an agent+ Then POST /v1/run {args, cwd} runs `raea ARGS` in the workspace, streaming {out}, {err} and last {exit} lines+ And the token and the state keys are never in its environment, and a dropped request stops the run+ Scenario: CL7. ACP over a WebSocket+ Then each WebSocket on /v1/acp?agent=ID is one agent process in the workspace: a text frame is one JSON-RPC+ message to its stdin, each line it prints is a frame back, and closing either end ends the other+ And the agent's environment is the container's (its API keys) without RAEA_CLOUD_TOKEN or the state keys+ Scenario: CL8. Agents that sign in by a device code sign in through the server+ Then POST /v1/login?agent=kimi-code starts Kimi Code's login and returns the URL to approve; the login is kept+ in the home folder+ And agents that take a key (claude-acp, codex-acp, gemini) take it from the environment++ Rule: it deploys anywhere containers run+ Scenario: CL9. Docker and Compose+ Then deploy/compose.yaml runs it with the home folder on a named volume, and deploy/compose.gpu.yaml adds an+ NVIDIA 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+ Scenario: CL11. The TypeScript client+ Then `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 to+ onPermission (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 is proven end to end+ Scenario: 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+ And with Kimi Code signed in, one real turn renders a title card with raea in the container, and the file+ comes back through /v1/filesdiff --git a/sdk/cloud/README.md b/sdk/cloud/README.mdnew file mode 100644index 00000000..0e8280ab--- /dev/null+++ b/sdk/cloud/README.md@@ -0,0 +1,109 @@+# raea cloud++raea 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+server, 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, ...)+ HTTPS + one token /v1/acp (WebSocket) ──▶ the agent, over ACP, in ~/work+ /v1/files, /v1/run, /v1/login, /v1/health+```++## Run it++```bash+cd sdk/cloud+docker build --platform linux/amd64 -f image/Dockerfile \+ --build-arg RAEA_VERSION=0.1.1 --build-arg AGENTS="kimi-code" -t raea-cloud .+export RAEA_CLOUD_TOKEN=$(openssl rand -hex 32)+docker run -d -p 127.0.0.1:8080:8080 -e RAEA_CLOUD_TOKEN -v raea-home:/home/raea raea-cloud+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=`).+`RAEA_AGENT_CMD` runs an agent the registry doesn't list, by its command line.++Signing the agent in:++- **Kimi Code** signs in by a device code: `POST /v1/login?agent=kimi-code` (or `cloud.login()`) returns a link and+ a code to approve once. The sign-in is kept in the home folder.+- **Claude, Codex, Gemini** take their key from the container's environment: `ANTHROPIC_API_KEY` (or+ `CLAUDE_CODE_OAUTH_TOKEN`), `OPENAI_API_KEY`, `GEMINI_API_KEY`.++## Use it++```ts+import { RaeaCloud } from "@raea/cloud" // sdk/cloud/src++const cloud = new RaeaCloud({ url: "https://raea.example.com", token: process.env.RAEA_CLOUD_TOKEN! })++// raea on its own+await cloud.run(["init"], { cwd: "card" })+await cloud.run(["render", "edit.tsx", "-o", "card.mp4"], { cwd: "card", onOutput: (t) => process.stdout.write(t) })+const mp4 = await cloud.read("card/card.mp4")++// or an agent that uses raea, over ACP+const s = await cloud.session()+const stop = await s.prompt("Make card/edit.tsx a 3 s title card that says hello, and render it", (u) => {+ if (u.sessionUpdate === "agent_message_chunk") process.stdout.write(u.content?.text ?? "")+})+s.close()+```++The client needs only `fetch` and `WebSocket`: Node 22+, Bun, Deno or a browser. Permission requests are allowed+once by default (the container is the sandbox); pass `onPermission` to decide them yourself.++| 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/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/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 |++Every route but `/healthz` needs `Authorization: Bearer TOKEN` (or `?token=`, for a browser's WebSocket). Paths+outside the workspace are refused, symlinks out of it too. The agent and raea never see the token.++## Deploy it++| Where | File | The home folder lives on | Checked |+|---|---|---|---|+| Docker, Compose | `deploy/compose.yaml` | a named volume | end to end (test/smoke.sh) |+| 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+`RAEA_CLOUD_STATE_KEY` and `RAEA_CLOUD_STATE_SECRET`: the home folder is restored from it on start and saved to it+when the container stops (image/state.sh).++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.++## Known limits++- raea ships for Linux on x86_64 only, so the image is linux/amd64; an arm64 machine (Graviton, Ampere, Apple+ Silicon's Docker) runs it emulated and slowly.+- One server is one workspace, for one person or one team that trusts each other: everyone with the token has the+ agent's whole sandbox.+- Agents installed with uvx (Python) aren't supported by the image; add Python in your own image or run them by+ `RAEA_AGENT_CMD`.++## Test it++`test/smoke.sh 0.1.1` builds the image, starts it with a stand-in agent (test/echo-agent.mjs) and checks the token,+the path rules, a render through `/v1/run` and an ACP turn.diff --git a/sdk/cloud/deploy/compose.gpu.yaml b/sdk/cloud/deploy/compose.gpu.yamlnew file mode 100644index 00000000..964869fc--- /dev/null+++ b/sdk/cloud/deploy/compose.gpu.yaml@@ -0,0 +1,20 @@+# An NVIDIA GPU for raea's renders (docs/cloud.feature CL9), on top of compose.yaml:+#+# docker compose -f compose.yaml -f compose.gpu.yaml up -d+#+# The host needs NVIDIA's driver and the NVIDIA Container Toolkit. raea renders through Vulkan, so the container asks+# for the graphics capability too ("all" below): the toolkit then mounts NVIDIA's Vulkan driver and its ICD file, and+# raea's Vulkan picks the GPU over Mesa's llvmpipe. `docker compose exec raea nvidia-smi` shows the GPU the container+# sees, and raea's process on it while a render runs.+services:+ raea:+ environment:+ NVIDIA_VISIBLE_DEVICES: all+ NVIDIA_DRIVER_CAPABILITIES: all+ deploy:+ resources:+ reservations:+ devices:+ - driver: nvidia+ count: all+ capabilities: [gpu]diff --git a/sdk/cloud/deploy/compose.yaml b/sdk/cloud/deploy/compose.yamlnew file mode 100644index 00000000..2cefa3b9--- /dev/null+++ b/sdk/cloud/deploy/compose.yaml@@ -0,0 +1,35 @@+# raea cloud on one machine with Docker (docs/cloud.feature CL9): the image, its port and the home folder on a named+# volume (the agents' sign-ins, raea's settings and the workspace). From sdk/cloud/deploy:+#+# export RAEA_CLOUD_TOKEN=$(openssl rand -hex 32) # keep it: every request carries it+# docker compose up -d # builds the image the first time+# curl -H "authorization: Bearer $RAEA_CLOUD_TOKEN" localhost:8080/v1/health+#+# With an NVIDIA GPU: docker compose -f compose.yaml -f compose.gpu.yaml up -d+# Agents that take a key read it from here: set it in the shell (or an .env file beside this one) before `up`.+services:+ raea:+ image: ${RAEA_CLOUD_IMAGE:-raea-cloud:${RAEA_VERSION:-0.1.1}}+ build:+ context: ..+ dockerfile: image/Dockerfile+ args:+ RAEA_VERSION: ${RAEA_VERSION:-0.1.1}+ AGENTS: ${AGENTS:-kimi-code}+ platform: linux/amd64+ ports:+ - "${RAEA_CLOUD_BIND:-127.0.0.1}:${RAEA_CLOUD_PORT:-8080}:8080"+ environment:+ RAEA_CLOUD_TOKEN: ${RAEA_CLOUD_TOKEN:?set RAEA_CLOUD_TOKEN (openssl rand -hex 32)}+ RAEA_AGENT: ${RAEA_AGENT:-}+ # the agents' own keys, passed through when set+ ANTHROPIC_API_KEY:+ CLAUDE_CODE_OAUTH_TOKEN:+ OPENAI_API_KEY:+ GEMINI_API_KEY:+ OPENROUTER_API_KEY:+ volumes:+ - home:/home/raea+ restart: unless-stopped+volumes:+ home:diff --git a/sdk/cloud/deploy/fly.toml b/sdk/cloud/deploy/fly.tomlnew file mode 100644index 00000000..b64dc063--- /dev/null+++ b/sdk/cloud/deploy/fly.toml@@ -0,0 +1,44 @@+# raea cloud on Fly Machines (docs/cloud.feature CL10): one Machine with a volume for the home folder, stopped when+# it's idle and started again by the next request. From sdk/cloud (the image is built from image/Dockerfile):+#+# fly apps create YOUR-APP # and set app below to it+# fly volumes create raea_home --size 20 --region iad -c deploy/fly.toml+# fly secrets set RAEA_CLOUD_TOKEN=$(openssl rand -hex 32) -c deploy/fly.toml+# fly deploy -c deploy/fly.toml --dockerfile image/Dockerfile .+#+# Agents that take a key get it as a secret too (fly secrets set ANTHROPIC_API_KEY=...). Kimi Code signs in once+# through POST /v1/login, and the volume keeps the sign-in.+app = "raea-cloud"+primary_region = "iad"++[build]+ [build.args]+ RAEA_VERSION = "0.1.1"+ AGENTS = "kimi-code"++[env]+ RAEA_AGENT = "kimi-code"++[[mounts]]+ source = "raea_home"+ destination = "/home/raea"+ initial_size = "20gb"++[http_service]+ internal_port = 8080+ force_https = true+ auto_stop_machines = "stop"+ auto_start_machines = true+ min_machines_running = 0++ [[http_service.checks]]+ grace_period = "60s"+ interval = "30s"+ method = "GET"+ path = "/healthz"+ timeout = "5s"++# raea renders on the CPU here (Mesa's llvmpipe): more cores render faster+[[vm]]+ size = "performance-4x"+ memory = "8gb"diff --git a/sdk/cloud/deploy/k8s.yaml b/sdk/cloud/deploy/k8s.yamlnew file mode 100644index 00000000..778de767--- /dev/null+++ b/sdk/cloud/deploy/k8s.yaml@@ -0,0 +1,70 @@+# raea cloud on Kubernetes (docs/cloud.feature CL10): a Secret for the token, a PersistentVolumeClaim for the home+# folder, one Deployment and a Service. Push the image to a registry your cluster pulls from, set it below, then:+#+# kubectl create secret generic raea-cloud --from-literal=RAEA_CLOUD_TOKEN=$(openssl rand -hex 32)+# 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.+apiVersion: v1+kind: PersistentVolumeClaim+metadata:+ name: raea-cloud-home+spec:+ accessModes: [ReadWriteOnce]+ resources:+ requests:+ storage: 20Gi+---+apiVersion: apps/v1+kind: Deployment+metadata:+ name: raea-cloud+ labels: { app: raea-cloud }+spec:+ replicas: 1+ # one home folder, one writer: the old pod goes before the new one starts+ strategy: { type: Recreate }+ selector:+ matchLabels: { app: raea-cloud }+ template:+ metadata:+ labels: { app: raea-cloud }+ 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 }+ env:+ - { name: RAEA_AGENT, value: kimi-code }+ # - { name: NVIDIA_DRIVER_CAPABILITIES, value: all }+ volumeMounts:+ - { name: home, mountPath: /home/raea }+ readinessProbe:+ httpGet: { path: /healthz, port: 8080 }+ periodSeconds: 10+ resources:+ requests: { cpu: "2", memory: 4Gi }+ limits: { memory: 8Gi }+ # nvidia.com/gpu: 1+ terminationGracePeriodSeconds: 60+ volumes:+ - name: home+ persistentVolumeClaim: { claimName: raea-cloud-home }+---+apiVersion: v1+kind: Service+metadata:+ name: raea-cloud+spec:+ selector: { app: raea-cloud }+ ports:+ - { port: 8080, targetPort: 8080 }diff --git a/sdk/cloud/image/Dockerfile b/sdk/cloud/image/Dockerfilenew file mode 100644index 00000000..4f6c7ed9--- /dev/null+++ b/sdk/cloud/image/Dockerfile@@ -0,0 +1,49 @@+# raea cloud (docs/cloud.feature): raea's Linux release, the ACP agents named in AGENTS and the server+# (sdk/cloud/server) on one port. Build from sdk/cloud:+#+# docker build --platform linux/amd64 -f image/Dockerfile --build-arg RAEA_VERSION=0.1.1 \+# --build-arg AGENTS="kimi-code claude-acp" -t raea-cloud .+# 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).+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)+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 \+ && 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_REPO=shinyobjectz/raea+RUN 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" \+ && sha256sum -c $f.sha256 \+ && { [ -z "$RAEA_SHA256" ] || echo "$RAEA_SHA256 $f" | sha256sum -c -; } \+ && mkdir -p /opt/raea && tar -xzf $f -C /opt/raea --strip-components=1 && rm -f $f $f.sha256 \+ && ln -s /opt/raea/bin/raea /usr/local/bin/raea && raea --version++WORKDIR /opt/raea-cloud+COPY 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.+ARG AGENTS=kimi-code+RUN node server/agents.ts install $AGENTS && chmod +x image/*.sh++# 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+RUN mkdir -p "$HOME/work" && chown -R raea:raea "$HOME"+EXPOSE 8080+HEALTHCHECK --interval=30s --timeout=5s CMD curl -fsS http://127.0.0.1:8080/healthz || exit 1+ENTRYPOINT ["/opt/raea-cloud/image/entrypoint.sh"]diff --git a/sdk/cloud/image/entrypoint.sh b/sdk/cloud/image/entrypoint.shnew file mode 100755index 00000000..180fb25a--- /dev/null+++ b/sdk/cloud/image/entrypoint.sh@@ -0,0 +1,31 @@+#!/bin/bash+# raea cloud's entrypoint (docs/cloud.feature CL3, CL10): the home folder back from RAEA_CLOUD_STATE when it's set,+# raea's skills for each installed agent (matched to this image's raea), then the server. On SIGTERM (a platform+# stopping or sleeping the container) the server stops and the home folder is saved again.+set -uo pipefail+here=/opt/raea-cloud+: "${RAEA_CLOUD_TOKEN:?raea-cloud: set RAEA_CLOUD_TOKEN (openssl rand -hex 32); every request must carry it}"++# started as root: give the home folder to raea (a new volume is root's) and go on as raea, environment kept+if [ "$(id -u)" = 0 ]; then+ [ "$(stat -c %u /home/raea)" = 1000 ] || chown -R raea:raea /home/raea+ exec setpriv --reuid=raea --regid=raea --init-groups "$0" "$@"+fi++"$here/image/state.sh" restore+mkdir -p "${RAEA_CLOUD_WORK:-$HOME/work}"++for a in $(node "$here/server/agents.ts" skills); do+ raea skills install --agent "$a" >/dev/null 2>&1 || echo "raea-cloud: raea's skills for $a weren't installed"+done++node "$here/server/main.ts" &+server=$!+stop() {+ kill -TERM "$server" 2>/dev/null+ wait "$server" 2>/dev/null+ "$here/image/state.sh" save+ exit 0+}+trap stop TERM INT+wait "$server"diff --git a/sdk/cloud/image/state.sh b/sdk/cloud/image/state.shnew file mode 100755index 00000000..d4f3de5a--- /dev/null+++ b/sdk/cloud/image/state.sh@@ -0,0 +1,38 @@+#!/bin/bash+# The home folder kept in an S3-compatible object (docs/cloud.feature CL10), for platforms whose disk doesn't outlive+# the container (Cloudflare Containers): `state.sh restore` on start, `state.sh save` on stop. It holds the agents'+# sign-ins (~/.kimi-code, ~/.claude, ~/.codex, ...), raea's settings (~/.raea) and the workspace (~/work).+#+# RAEA_CLOUD_STATE the object's URL: https://ACCOUNT.r2.cloudflarestorage.com/BUCKET/home.tar.zst, or+# https://BUCKET.s3.REGION.amazonaws.com/home.tar.zst. Unset: nothing is restored or saved+# (a volume keeps the home instead).+# RAEA_CLOUD_STATE_KEY the access key id, and RAEA_CLOUD_STATE_SECRET its secret+# RAEA_CLOUD_STATE_REGION the signing region (auto for R2, the default)+#+# Caches that rebuild themselves stay out. curl signs the requests itself (--aws-sigv4).+set -uo pipefail+url=${RAEA_CLOUD_STATE:-}+[ -n "$url" ] || exit 0+sign=(--aws-sigv4 "aws:amz:${RAEA_CLOUD_STATE_REGION:-auto}:s3" --user "${RAEA_CLOUD_STATE_KEY:?}:${RAEA_CLOUD_STATE_SECRET:?}")+snap=/tmp/raea-home.tar.zst++case ${1:-} in+ restore)+ code=$(curl -sS "${sign[@]}" -o "$snap" -w '%{http_code}' "$url")+ if [ "$code" = 200 ]; then+ tar --zstd -xf "$snap" -C "$HOME" && echo "raea-cloud: home restored ($(du -sh "$HOME" | cut -f1))"+ elif [ "$code" = 404 ]; then+ echo "raea-cloud: no saved home yet; starting a new one"+ else+ echo "raea-cloud: couldn't read the saved home (HTTP $code); starting without it" >&2+ fi+ rm -f "$snap"+ ;;+ save)+ tar --zstd -cf "$snap" -C "$HOME" --exclude=./.npm/_cacache --exclude=./.cache --exclude=./tmp . || exit 1+ code=$(curl -sS "${sign[@]}" -T "$snap" -o /dev/null -w '%{http_code}' "$url")+ [ "$code" = 200 ] && echo "raea-cloud: home saved ($(du -h "$snap" | cut -f1))" || echo "raea-cloud: saving the home FAILED (HTTP $code)" >&2+ rm -f "$snap"+ ;;+ *) echo "usage: state.sh restore|save" >&2; exit 2 ;;+esacdiff --git a/sdk/cloud/package-lock.json b/sdk/cloud/package-lock.jsonnew file mode 100644index 00000000..29a54b13--- /dev/null+++ b/sdk/cloud/package-lock.json@@ -0,0 +1,71 @@+{+ "name": "@raea/cloud",+ "version": "0.1.1",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@raea/cloud",+ "version": "0.1.1",+ "license": "FSL-1.1-ALv2",+ "dependencies": {+ "ws": "8.18.3"+ },+ "devDependencies": {+ "@types/node": "24.10.1",+ "@types/ws": "8.18.1"+ },+ "engines": {+ "node": ">=22.19"+ }+ },+ "node_modules/@types/node": {+ "version": "24.10.1",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz",+ "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~7.16.0"+ }+ },+ "node_modules/@types/ws": {+ "version": "8.18.1",+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/undici-types": {+ "version": "7.16.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",+ "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/ws": {+ "version": "8.18.3",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",+ "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ }+ }+}diff --git a/sdk/cloud/package.json b/sdk/cloud/package.jsonnew file mode 100644index 00000000..93b9eae4--- /dev/null+++ b/sdk/cloud/package.json@@ -0,0 +1,23 @@+{+ "name": "@raea/cloud",+ "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/).",+ "type": "module",+ "main": "src/index.ts",+ "exports": {+ ".": "./src/index.ts"+ },+ "files": ["src", "server", "image", "deploy", "README.md"],+ "engines": {+ "node": ">=22.19"+ },+ "dependencies": {+ "ws": "8.18.3"+ },+ "devDependencies": {+ "@types/node": "24.10.1",+ "@types/ws": "8.18.1"+ }+}diff --git a/sdk/cloud/server/agents.ts b/sdk/cloud/server/agents.tsnew file mode 100644index 00000000..986e9dae--- /dev/null+++ b/sdk/cloud/server/agents.ts@@ -0,0 +1,145 @@+// The ACP agents a raea cloud runs (docs/cloud.feature CL2, CL3): any agent the ACP registry lists+// (github.com/agentclientprotocol/registry), installed from its registry entry when the image is built. An npx entry+// is installed with npm at the registry's version; a binary entry is fetched from its linux archive and checked by+// sha256; a uvx entry is refused (the image has no Python). Each install leaves AGENTS/ID/spawn.json (how to start it)+// and AGENTS/ID/entry.json (the registry entry it came from).+//+// node agents.ts install ID... install agents (the Dockerfile's AGENTS)+// node agents.ts skills the raea skill names for the installed agents (entrypoint.sh)+// node agents.ts list the installed agents, one per line++import { execFileSync } from "node:child_process"+import { createHash } from "node:crypto"+import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"+import path from "node:path"+import { pathToFileURL } from "node:url"++export const REGISTRY_URL = process.env.RAEA_CLOUD_REGISTRY ?? "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json"+export const AGENTS_DIR = process.env.RAEA_CLOUD_AGENTS ?? "/opt/raea-cloud/agents"++interface Binary {+ archive: string+ cmd: string+ args?: string[]+ env?: Record<string, string>+ sha256?: string+}+interface Entry {+ id: string+ name: string+ version: string+ distribution: { binary?: Record<string, Binary>; npx?: { package: string; args?: string[]; env?: Record<string, string> }; uvx?: unknown }+}++/** How to start one agent: a command, its arguments and the environment it adds. */+export interface Spawn {+ id: string+ version: string+ command: string+ args: string[]+ env: Record<string, string>+}++/** raea's skill folder names (`raea skills install --agent`) for the registry ids that have one. */+const SKILLS: Record<string, string> = { "kimi-code": "kimi", kimi: "kimi", "claude-acp": "claude", "codex-acp": "codex", gemini: "gemini" }++const platform = () => `linux-${process.arch === "arm64" ? "aarch64" : "x86_64"}`++async function registry(): Promise<Entry[]> {+ if (!/^https?:/.test(REGISTRY_URL)) return JSON.parse(readFileSync(REGISTRY_URL, "utf8")).agents+ const res = await fetch(REGISTRY_URL)+ if (!res.ok) throw new Error(`ACP registry: ${res.status} from ${REGISTRY_URL}`)+ return ((await res.json()) as { agents: Entry[] }).agents+}++/** The command an npm package installs: its one bin, or the one named like the package. */+function binOf(dir: string, pkg: string): string {+ const name = pkg.replace(/@[^@/]+$/, "")+ const manifest = JSON.parse(readFileSync(path.join(dir, "node_modules", name, "package.json"), "utf8")) as { bin?: string | Record<string, string> }+ const short = name.split("/").pop()!+ if (typeof manifest.bin === "string") return short+ const bins = Object.keys(manifest.bin ?? {})+ const bin = bins.length === 1 ? bins[0] : (bins.find((b) => b === short) ?? bins[0])+ if (!bin) throw new Error(`${name} installs no command`)+ return bin+}++async function fetchArchive(b: Binary, dir: string): Promise<void> {+ const res = await fetch(b.archive)+ if (!res.ok) throw new Error(`${b.archive}: ${res.status}`)+ const bytes = Buffer.from(await res.arrayBuffer())+ const sum = createHash("sha256").update(bytes).digest("hex")+ if (b.sha256 && sum !== b.sha256) throw new Error(`${b.archive}: sha256 ${sum}, the registry says ${b.sha256}`)+ const file = path.join(dir, path.basename(new URL(b.archive).pathname))+ writeFileSync(file, bytes)+ if (/\.(tar\.gz|tgz)$/.test(file)) execFileSync("tar", ["-xzf", file, "-C", dir])+ else if (/\.tar\.xz$/.test(file)) execFileSync("tar", ["-xJf", file, "-C", dir])+ else if (/\.tar\.bz2$/.test(file)) execFileSync("tar", ["-xjf", file, "-C", dir])+ else if (/\.zip$/.test(file)) execFileSync("unzip", ["-q", "-o", file, "-d", dir])+ else return // a bare program: the download is the command+ rmSync(file)+}++/** Installs one registry agent under AGENTS_DIR/ID and says how to start it. */+export async function install(id: string, agents?: Entry[]): Promise<Spawn> {+ const e = (agents ?? (await registry())).find((a) => a.id === id)+ if (!e) throw new Error(`${id} isn't in the ACP registry (${REGISTRY_URL})`)+ const dir = path.join(AGENTS_DIR, id)+ rmSync(dir, { recursive: true, force: true })+ mkdirSync(dir, { recursive: true })+ const d = e.distribution+ const bin = d.binary?.[platform()]+ let spawn: Spawn+ // npx first when an agent has both: node is in the image, and the npm package is the one its authors run+ if (d.npx) {+ execFileSync("npm", ["install", "--prefix", dir, "--no-fund", "--no-audit", "--omit=dev", "--loglevel=error", d.npx.package], { stdio: "inherit" })+ spawn = { id, version: e.version, command: path.join(dir, "node_modules/.bin", binOf(dir, d.npx.package)), args: d.npx.args ?? [], env: d.npx.env ?? {} }+ } else if (bin) {+ await fetchArchive(bin, dir)+ const command = path.resolve(dir, bin.cmd)+ if (!existsSync(command)) throw new Error(`${id}: ${bin.cmd} isn't in ${bin.archive}`)+ chmodSync(command, 0o755)+ spawn = { id, version: e.version, command, args: bin.args ?? [], env: bin.env ?? {} }+ } else if (d.uvx) throw new Error(`${id} installs with uvx, and this image has no Python: build an image that adds it, or run it by RAEA_AGENT_CMD`)+ else throw new Error(`${id} has no ${platform()} build in the registry`)+ writeFileSync(path.join(dir, "spawn.json"), JSON.stringify(spawn, null, 2))+ writeFileSync(path.join(dir, "entry.json"), JSON.stringify(e, null, 2))+ return spawn+}++/** The agents installed in this image. */+export function installed(): Spawn[] {+ if (!existsSync(AGENTS_DIR)) return []+ return readdirSync(AGENTS_DIR)+ .map((id) => path.join(AGENTS_DIR, id, "spawn.json"))+ .filter((f) => existsSync(f))+ .map((f) => JSON.parse(readFileSync(f, "utf8")) as Spawn)+}++/** How to start agent ID (the default agent when none is named). RAEA_AGENT_CMD, a shell command line, runs an agent+ * that isn't installed from the registry (one of your own, or one mounted into the container). */+export function spawnFor(id?: string): Spawn {+ const want = id || process.env.RAEA_AGENT || ""+ const cmd = process.env.RAEA_AGENT_CMD+ if (cmd && (!want || want === "custom")) return { id: "custom", version: "", command: "/bin/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")+ return s+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ const [cmd, ...ids] = process.argv.slice(2)+ if (cmd === "install") {+ const agents = await registry()+ for (const id of ids.flatMap((s) => s.split(/[\s,]+/)).filter(Boolean)) {+ const s = await install(id, agents)+ console.log(`raea-cloud: ${id} ${s.version} -> ${s.command} ${s.args.join(" ")}`)+ }+ } else if (cmd === "skills") console.log([...new Set(installed().flatMap((a) => SKILLS[a.id] ?? []))].join("\n"))+ else if (cmd === "list") console.log(installed().map((a) => `${a.id} ${a.version}`).join("\n"))+ else {+ console.error("usage: node agents.ts install ID... | skills | list")+ process.exit(2)+ }+}diff --git a/sdk/cloud/server/login.ts b/sdk/cloud/server/login.tsnew file mode 100644index 00000000..bed7cc35--- /dev/null+++ b/sdk/cloud/server/login.ts@@ -0,0 +1,82 @@+// An agent's own sign-in, for agents that sign in from a terminal by a device code (docs/cloud.feature CL8): Kimi Code,+// and any agent whose ACP initialize lists a terminal auth method. There's no terminal on a server, so the login runs+// under script(1) (the device code is printed only to a terminal) and what it prints is handed back: the link to open+// and the code to enter. The login itself keeps running until it's approved, then writes the agent's sign-in into+// the home folder, which outlives the container (a volume, or RAEA_CLOUD_STATE).++import { type ChildProcess, spawn } from "node:child_process"+import type { Spawn } from "./agents.ts"+import { WORK } from "./workspace.ts"++interface Method {+ id: string+ type?: string+ args?: string[]+ env?: Record<string, string>+ _meta?: { "terminal-auth"?: { command: string; args?: string[]; env?: Record<string, string> } }+}++export interface Login {+ agent: string+ method?: string+ url?: string+ code?: string+ state: "waiting" | "done" | "failed" | "none"+ output: string+}++const running = new Map<string, { login: Login; child: ChildProcess }>()++/** The agent's auth methods, from its ACP initialize. */+async function methods(a: Spawn, env: NodeJS.ProcessEnv): Promise<Method[]> {+ const child = spawn(a.command, a.args, { cwd: WORK, env: { ...env, ...a.env }, stdio: ["pipe", "pipe", "ignore"] })+ child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: 1, clientCapabilities: { terminal: true, _meta: { "terminal-auth": true } } } }) + "\n")+ return new Promise((ok) => {+ let buf = ""+ const done = (m: Method[]) => (child.kill(), clearTimeout(t), ok(m))+ const t = setTimeout(() => done([]), 30_000)+ child.stdout.setEncoding("utf8").on("data", (c: string) => {+ buf += c+ for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) {+ try {+ const m = JSON.parse(buf.slice(0, i))+ if (m.id === 1) return done(m.result?.authMethods ?? [])+ } catch {}+ }+ })+ child.on("exit", () => done([]))+ })+}++const quote = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`++/** Starts agent `a`'s terminal login (or answers the one already waiting): resolves once it has printed its link, or+ * has finished, or after 20 s. */+export async function login(a: Spawn, env: NodeJS.ProcessEnv): Promise<Login> {+ const had = running.get(a.id)+ if (had && had.login.state === "waiting") return had.login+ const m = (await methods(a, env)).find((x) => x._meta?.["terminal-auth"] || x.type === "terminal")+ if (!m) return { agent: a.id, state: "none", output: `${a.id} lists no terminal sign-in; give it its key in the container's environment` }+ const t = m._meta?.["terminal-auth"]+ const command = t?.command ?? a.command+ const args = t ? (t.args ?? []) : [...a.args, ...(m.args ?? [])]+ // Kimi's login defaults to kimi.com (mainland China); kimi.ai's is "global"+ if (/(^|\/)kimi$/.test(command) && args.includes("login") && !args.includes("--region")) args.push("--region", env.RAEA_KIMI_REGION ?? "global")+ const line = [command, ...args].map(quote).join(" ")+ const child = spawn("script", ["-qfec", line, "/dev/null"], { cwd: WORK, env: { ...env, ...a.env, ...t?.env, ...m.env }, stdio: ["pipe", "pipe", "pipe"] })+ const l: Login = { agent: a.id, method: m.id, state: "waiting", output: "" }+ running.set(a.id, { login: l, child })+ const read = (c: string) => {+ l.output += c.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "")+ l.url ??= /https:\/\/\S+/.exec(l.output)?.[0]?.replace(/[)\].,'"]+$/, "")+ l.code ??= /\b[Cc]ode:?\s+([A-Z0-9]{3,}(?:-[A-Z0-9]{3,})*)\b/.exec(l.output)?.[1] ?? (l.url ? (new URL(l.url).searchParams.get("user_code") ?? undefined) : undefined)+ }+ child.stdout!.setEncoding("utf8").on("data", read)+ child.stderr!.setEncoding("utf8").on("data", read)+ child.on("exit", (code) => (l.state = code === 0 ? "done" : "failed"))+ for (let i = 0; i < 100 && !l.url && l.state === "waiting"; i++) await new Promise((r) => setTimeout(r, 200))+ return l+}++/** Where agent `id`'s login is now. */+export const loginState = (id: string): Login => running.get(id)?.login ?? { agent: id, state: "none", output: "" }diff --git a/sdk/cloud/server/main.ts b/sdk/cloud/server/main.tsnew file mode 100644index 00000000..c5c0d9fc--- /dev/null+++ b/sdk/cloud/server/main.ts@@ -0,0 +1,155 @@+// 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/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+//+// Every route but /healthz needs RAEA_CLOUD_TOKEN: `Authorization: Bearer TOKEN`, or ?token= (a browser's WebSocket+// can't set headers). The agent and raea get the container's environment without the token or the state keys.++import { execFileSync, spawn } from "node:child_process"+import { timingSafeEqual } from "node:crypto"+import { mkdirSync, readdirSync, readFileSync, statSync, 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 { login, loginState } from "./login.ts"+import { Outside, resolve, WORK } from "./workspace.ts"++const TOKEN = process.env.RAEA_CLOUD_TOKEN ?? ""+if (TOKEN.length < 16) {+ console.error("raea-cloud: set RAEA_CLOUD_TOKEN to a secret of 16 characters or more (openssl rand -hex 32); every request must carry it")+ process.exit(1)+}+const PORT = Number(process.env.PORT ?? 8080)+const RAEA = process.env.RAEA_BIN ?? "raea"++/** The environment raea and the agents run with: the container's, less this server's own secrets. */+const childEnv = (): NodeJS.ProcessEnv => {+ const env = { ...process.env }+ for (const k of Object.keys(env)) if (k === "RAEA_CLOUD_TOKEN" || k.startsWith("RAEA_CLOUD_STATE")) delete env[k]+ return env+}++let version: string | undefined+const raeaVersion = () => {+ try {+ version ??= execFileSync(RAEA, ["--version"], { encoding: "utf8", timeout: 20_000, env: childEnv() }).trim()+ } catch {+ version = "unknown"+ }+ return version+}++function authorized(req: IncomingMessage, url: URL): boolean {+ const given = /^Bearer (.+)$/.exec(req.headers.authorization ?? "")?.[1] ?? url.searchParams.get("token") ?? ""+ const a = Buffer.from(given)+ const b = Buffer.from(TOKEN)+ return a.length === b.length && timingSafeEqual(a, b)+}++const json = (res: ServerResponse, v: unknown, status = 200) => res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(v))++async function body(req: IncomingMessage): Promise<Buffer> {+ const parts: Buffer[] = []+ for await (const c of req) parts.push(c as Buffer)+ return Buffer.concat(parts)+}++function files(req: IncomingMessage, res: ServerResponse, url: URL) {+ const p = resolve(url.searchParams.get("path") ?? ".")+ if (req.method === "PUT")+ return body(req).then((b) => {+ mkdirSync(path.dirname(p), { recursive: true })+ writeFileSync(p, b)+ json(res, { path: path.relative(WORK, p), bytes: b.length })+ })+ let st+ try {+ st = statSync(p)+ } catch {+ return json(res, { error: `${url.searchParams.get("path")} doesn't exist` }, 404)+ }+ if (st.isDirectory()) return json(res, readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, dir: d.isDirectory(), bytes: d.isFile() ? statSync(path.join(p, d.name)).size : undefined })))+ res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size }).end(readFileSync(p))+}++async function run(req: IncomingMessage, res: ServerResponse) {+ const { args, cwd } = JSON.parse((await body(req)).toString() || "{}") as { args?: unknown; cwd?: string }+ if (!Array.isArray(args) || !args.every((a) => typeof a === "string")) return json(res, { error: "args must be an array of strings: raea's own arguments" }, 400)+ const dir = resolve(cwd ?? ".")+ mkdirSync(dir, { recursive: true })+ res.writeHead(200, { "content-type": "application/x-ndjson" })+ const child = spawn(RAEA, args, { cwd: dir, env: childEnv(), stdio: ["ignore", "pipe", "pipe"] })+ const line = (v: unknown) => res.write(JSON.stringify(v) + "\n")+ child.stdout.setEncoding("utf8").on("data", (out: string) => line({ out }))+ child.stderr.setEncoding("utf8").on("data", (err: string) => line({ err }))+ child.on("error", (e) => (line({ err: String(e) }), res.end(JSON.stringify({ exit: 127 }) + "\n")))+ child.on("close", (code, signal) => res.end(JSON.stringify({ exit: code ?? 128, signal: signal ?? undefined }) + "\n"))+ // the caller went away: the run stops with it+ res.on("close", () => child.exitCode === null && child.kill("SIGTERM"))+}++const server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://raea-cloud")+ if (url.pathname === "/healthz") return res.writeHead(200, { "content-type": "text/plain" }).end("ok")+ if (!authorized(req, url)) return json(res, { error: "unauthorized" }, 401)+ try {+ if (url.pathname === "/v1/health" && req.method === "GET") {+ const def = (() => {+ try {+ return spawnFor().id+ } catch {+ return null+ }+ })()+ return json(res, { raea: raeaVersion(), agent: def, agents: installed().map((a) => ({ id: a.id, version: a.version })), workspace: WORK })+ }+ 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/login") {+ const a = spawnFor(url.searchParams.get("agent") ?? undefined)+ return json(res, req.method === "POST" ? await login(a, childEnv()) : loginState(a.id))+ }+ json(res, { error: `no route ${req.method} ${url.pathname}` }, 404)+ } catch (e) {+ if (e instanceof Outside) return json(res, { error: e.message }, 403)+ if (!res.headersSent) json(res, { error: (e as Error).message }, 400)+ }+})++// the WebSocket upgrade checks the token before a socket opens+const wss = new WebSocketServer({ noServer: true })+server.on("upgrade", (req, socket, head) => {+ const url = new URL(req.url ?? "/", "http://raea-cloud")+ if (url.pathname !== "/v1/acp" || !authorized(req, url)) return socket.end("HTTP/1.1 401 Unauthorized\r\n\r\n")+ let a+ try {+ a = spawnFor(url.searchParams.get("agent") ?? undefined)+ } 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 agent = a+ wss.handleUpgrade(req, socket, head, (ws) => {+ const child = spawn(agent.command, agent.args, { cwd: WORK, env: { ...childEnv(), ...agent.env }, stdio: ["pipe", "pipe", "inherit"] })+ let buf = ""+ // ACP messages are newline-delimited JSON: split on \n only+ child.stdout.setEncoding("utf8").on("data", (c: string) => {+ buf += c+ for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) if (i > 0) ws.send(buf.slice(0, i))+ })+ ws.on("message", (m) => child.stdin.write(m.toString() + "\n"))+ ws.on("close", () => child.exitCode === null && child.kill("SIGTERM"))+ 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}`))+ })+})++mkdirSync(WORK, { recursive: true })+server.listen(PORT, () => console.log(`raea-cloud: :${PORT}, workspace ${WORK}, agents ${installed().map((a) => a.id).join(", ") || "none"}, raea ${raeaVersion()}`))diff --git a/sdk/cloud/server/workspace.ts b/sdk/cloud/server/workspace.tsnew file mode 100644index 00000000..b3ea78e4--- /dev/null+++ b/sdk/cloud/server/workspace.ts@@ -0,0 +1,25 @@+// The workspace a raea cloud works in (docs/cloud.feature CL5): every path a request names resolves inside it, or the+// request is refused. A path is checked twice: as written (no .., no absolute path out) and as the disk has it (no+// symlink inside the workspace pointing out), the second on the deepest part of the path that exists.++import { existsSync, realpathSync } from "node:fs"+import os from "node:os"+import path from "node:path"++export const WORK = path.resolve(process.env.RAEA_CLOUD_WORK ?? path.join(os.homedir(), "work"))++export class Outside extends Error {}++const inside = (root: string, p: string) => p === root || p.startsWith(root + path.sep)++/** The absolute path of `rel` in the workspace, or Outside. */+export function resolve(rel: string, root = WORK): string {+ // an absolute path must already be in the workspace; a relative one is taken from it+ const p = path.resolve(root, rel)+ if (!inside(root, p)) throw new Outside(`${rel} is outside the workspace`)+ const real = realpathSync(existsSync(root) ? root : path.dirname(root))+ let probe = p+ while (!existsSync(probe) && probe !== root) probe = path.dirname(probe)+ if (existsSync(probe) && !inside(real, realpathSync(probe))) throw new Outside(`${rel} leads outside the workspace`)+ return p+}diff --git a/sdk/cloud/src/index.ts b/sdk/cloud/src/index.tsnew file mode 100644index 00000000..cd49796d--- /dev/null+++ b/sdk/cloud/src/index.ts@@ -0,0 +1,121 @@+// The raea cloud client (docs/cloud.feature CL11): raea and an ACP agent on a server of your own, from any TypeScript+// with fetch and WebSocket (Node 22+, Bun, a browser).+//+// const cloud = new RaeaCloud({ url: "https://raea.example.com", token: process.env.RAEA_CLOUD_TOKEN })+// 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+// 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()++import { Session, type Permission } from "./session.ts"++export { Session, type Permission, type Update } from "./session.ts"++export interface Health {+ raea: string+ agent: string | null+ agents: { id: string; version: string }[]+ workspace: string+}++export interface Entry {+ name: string+ dir: boolean+ bytes?: number+}++export interface Login {+ agent: string+ method?: string+ url?: string+ code?: string+ state: "waiting" | "done" | "failed" | "none"+ output: string+}++export class RaeaCloud {+ readonly url: string+ private token: string+ private ws?: Promise<string>++ constructor(o: { url: string; token: string }) {+ this.url = o.url.replace(/\/+$/, "")+ this.token = o.token+ }++ private async call(path: string, init: RequestInit = {}): Promise<Response> {+ const res = await fetch(this.url + path, { ...init, headers: { authorization: `Bearer ${this.token}`, ...init.headers } })+ if (!res.ok) throw new Error(`${init.method ?? "GET"} ${path}: ${res.status} ${await res.text()}`)+ return res+ }++ health(): Promise<Health> {+ return this.call("/v1/health").then((r) => r.json())+ }++ async read(path: string): Promise<Uint8Array> {+ return new Uint8Array(await (await this.call(`/v1/files?path=${encodeURIComponent(path)}`)).arrayBuffer())+ }++ async text(path: string): Promise<string> {+ return new TextDecoder().decode(await this.read(path))+ }++ list(path = "."): Promise<Entry[]> {+ return this.call(`/v1/files?path=${encodeURIComponent(path)}`).then((r) => r.json())+ }++ async write(path: string, data: string | Uint8Array): Promise<void> {+ await this.call(`/v1/files?path=${encodeURIComponent(path)}`, { method: "PUT", body: typeof data === "string" ? data : new Blob([data as BlobPart]) })+ }++ /** `raea ARGS` in the workspace (or `cwd` in it): resolves with its exit code; output goes to onOutput as it comes. */+ async run(args: string[], o: { cwd?: string; onOutput?: (text: string, stream: "out" | "err") => void; signal?: AbortSignal } = {}): Promise<number> {+ const res = await this.call("/v1/run", { method: "POST", body: JSON.stringify({ args, cwd: o.cwd }), headers: { "content-type": "application/json" }, signal: o.signal })+ const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader()+ let buf = ""+ for (;;) {+ const { value, done } = await reader.read()+ if (done) break+ buf += value+ for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) {+ const m = JSON.parse(buf.slice(0, i)) as { out?: string; err?: string; exit?: number }+ if (m.out !== undefined) o.onOutput?.(m.out, "out")+ if (m.err !== undefined) o.onOutput?.(m.err, "err")+ if (m.exit !== undefined) return m.exit+ }+ }+ throw new Error("raea's run ended without an exit code")+ }++ /** 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> {+ return this.call(`/v1/login${agent ? `?agent=${encodeURIComponent(agent)}` : ""}`, { method: "POST" }).then((r) => r.json())+ }++ loginState(agent?: string): Promise<Login> {+ return this.call(`/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). */+ 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 } : {}) })+ const ws = new WebSocket(`${this.url.replace(/^http/, "ws")}/v1/acp?${q}`)+ await new Promise((ok, no) => {+ ws.onopen = ok+ ws.onerror = () => no(new Error(`couldn't open the ACP socket at ${this.url}`))+ })+ const s = new Session(ws, o.onPermission)+ await s.request("initialize", { protocolVersion: 1, clientCapabilities: {} })+ const root = await work+ const cwd = !o.cwd ? root : o.cwd.startsWith("/") ? o.cwd : `${root}/${o.cwd}`+ const { sessionId } = (await s.request("session/new", { cwd, mcpServers: [] })) as { sessionId: string }+ s.id = sessionId+ return s+ }+}diff --git a/sdk/cloud/src/session.ts b/sdk/cloud/src/session.tsnew file mode 100644index 00000000..b4bbfb0c--- /dev/null+++ b/sdk/cloud/src/session.ts@@ -0,0 +1,71 @@+// One ACP session over raea cloud's WebSocket (agentclientprotocol.com): JSON-RPC requests out, their answers and the+// agent's session/update notifications in, and its permission requests answered by onPermission.++export interface Update {+ sessionUpdate: string+ content?: { type: string; text?: string }+ [k: string]: unknown+}++export interface Permission {+ sessionId: string+ options: { optionId: string; kind: string; name?: string }[]+ toolCall?: unknown+}++/** By default a permission is allowed once: the container is the sandbox. */+const allowOnce = (p: Permission) => (p.options.find((o) => o.kind === "allow_once") ?? p.options.find((o) => o.kind.startsWith("allow")) ?? p.options[0]).optionId++export class Session {+ id = ""+ private n = 0+ private waiting = new Map<number, { ok: (v: unknown) => void; no: (e: Error) => void }>()+ private onUpdate: ((u: Update) => void) | null = null+ private ws: WebSocket+ private permit: (p: Permission) => string | Promise<string>++ constructor(ws: WebSocket, permit?: (p: Permission) => string | Promise<string>) {+ this.ws = ws+ this.permit = permit ?? allowOnce+ ws.onmessage = async (e) => {+ const m = JSON.parse(String(e.data))+ if (m.id != null && !m.method && this.waiting.has(m.id)) {+ const w = this.waiting.get(m.id)!+ this.waiting.delete(m.id)+ return m.error ? w.no(new Error(m.error.message ?? JSON.stringify(m.error))) : w.ok(m.result)+ }+ if (m.method === "session/update") return this.onUpdate?.(m.params.update)+ if (m.method === "session/request_permission") {+ const optionId = await this.permit(m.params)+ return ws.send(JSON.stringify({ jsonrpc: "2.0", id: m.id, result: { outcome: { outcome: "selected", optionId } } }))+ }+ // a request this client doesn't serve (fs/*, terminal/*): it said so in initialize, but answer rather than hang+ if (m.id != null && m.method) ws.send(JSON.stringify({ jsonrpc: "2.0", id: m.id, error: { code: -32601, message: `${m.method} isn't offered by this client` } }))+ }+ ws.onclose = (e) => {+ for (const w of this.waiting.values()) w.no(new Error(`the ACP socket closed${e.reason ? `: ${e.reason}` : ""}`))+ this.waiting.clear()+ }+ }++ request(method: string, params: unknown): Promise<unknown> {+ const id = ++this.n+ this.ws.send(JSON.stringify({ jsonrpc: "2.0", id, method, params }))+ return new Promise((ok, no) => this.waiting.set(id, { ok, no }))+ }++ /** One turn: resolves with its stop reason once the agent is done; each update on the way goes to onUpdate. */+ async prompt(text: string, onUpdate?: (u: Update) => void): Promise<string> {+ this.onUpdate = onUpdate ?? null+ const r = (await this.request("session/prompt", { sessionId: this.id, prompt: [{ type: "text", text }] })) as { stopReason: string }+ return r.stopReason+ }++ cancel() {+ this.ws.send(JSON.stringify({ jsonrpc: "2.0", method: "session/cancel", params: { sessionId: this.id } }))+ }++ close() {+ this.ws.close()+ }+}diff --git a/sdk/cloud/test/echo-agent.mjs b/sdk/cloud/test/echo-agent.mjsnew file mode 100644index 00000000..28d2426f--- /dev/null+++ b/sdk/cloud/test/echo-agent.mjs@@ -0,0 +1,35 @@+// A stand-in ACP agent for raea cloud's smoke test (docs/cloud.feature CL12): it answers initialize and session/new,+// and each prompt with two updates, the prompt's text echoed and the `raea --version` it finds in the container, so a+// turn shows the agent runs next to raea. It asks one permission per turn, to check the client answers it.+import { execFileSync } from "node:child_process"+import { createInterface } from "node:readline"++const send = (m) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...m }) + "\n")+const update = (sessionId, text) => send({ method: "session/update", params: { sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } })+let asked = 1000+const pending = new Map()++createInterface({ input: process.stdin }).on("line", (line) => {+ const m = JSON.parse(line)+ if (m.id != null && !m.method && pending.has(m.id)) return pending.get(m.id)(m.result)+ if (m.method === "initialize") return send({ id: m.id, result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] } })+ if (m.method === "session/new") return send({ id: m.id, result: { sessionId: `echo-${process.pid}`, cwd: m.params.cwd } })+ if (m.method === "session/prompt") {+ const { sessionId, prompt } = m.params+ update(sessionId, `echo: ${prompt.map((p) => p.text ?? "").join("")}`)+ let v+ try {+ v = execFileSync("raea", ["--version"], { encoding: "utf8" }).trim()+ } catch (e) {+ v = `no raea: ${e.message}`+ }+ update(sessionId, `raea: ${v}; cwd: ${process.cwd()}; token visible: ${process.env.RAEA_CLOUD_TOKEN ? "yes" : "no"}`)+ const id = ++asked+ pending.set(id, (r) => {+ update(sessionId, `permission: ${r?.outcome?.optionId}`)+ send({ id: m.id, result: { stopReason: "end_turn" } })+ })+ return send({ id, method: "session/request_permission", params: { sessionId, toolCall: { toolCallId: "t1", title: "echo" }, options: [{ optionId: "yes", kind: "allow_once", name: "Allow" }, { optionId: "no", kind: "reject_once", name: "Reject" }] } })+ }+ if (m.id != null) send({ id: m.id, error: { code: -32601, message: `echo-agent: no ${m.method}` } })+})diff --git a/sdk/cloud/test/live.ts b/sdk/cloud/test/live.tsnew file mode 100644index 00000000..0d1d9a8e--- /dev/null+++ b/sdk/cloud/test/live.ts@@ -0,0 +1,34 @@+// raea cloud's live check (docs/cloud.feature CL12): one real agent turn that makes and renders a title card with+// raea in the container, then reads the video back through /v1/files.+// node test/live.ts URL TOKEN [AGENT]+// The agent must be signed in (POST /v1/login for Kimi Code, or its key in the container's environment).+import { writeFileSync } from "node:fs"+import { RaeaCloud } from "../src/index.ts"++const [url, token, agent] = process.argv.slice(2)+if (!url || !token) throw new Error("usage: node test/live.ts URL TOKEN [AGENT]")+const cloud = new RaeaCloud({ url, token })+const dir = `live-${Date.now().toString(36)}`+const h = await cloud.health()+console.log(`raea ${h.raea}, agent ${agent ?? h.agent}, workspace ${h.workspace}`)++const t0 = performance.now()+const s = await cloud.session({ agent, cwd: dir })+const tools: string[] = []+let said = ""+const stop = await s.prompt(+ `In this folder, run \`raea init\`, then change edit.tsx so the whole composition is a 3 second title card that says "raea cloud" in large white text on a dark background. Render it with \`raea render edit.tsx -o card.mp4\`, and reply with the size of card.mp4 in bytes.`,+ (u) => {+ if (u.sessionUpdate === "agent_message_chunk") said += u.content?.text ?? ""+ if (u.sessionUpdate === "tool_call") tools.push(String((u as { title?: string }).title ?? "tool"))+ },+)+s.close()+console.log(`turn: ${stop} in ${Math.round((performance.now() - t0) / 1000)} s, ${tools.length} tool calls`)+console.log(`tools: ${tools.slice(0, 12).join(" | ")}`)+console.log(`agent: ${said.trim().slice(-400)}`)+const mp4 = await cloud.read(`${dir}/card.mp4`)+const out = `${process.env.OUT ?? "."}/live-card.mp4`+writeFileSync(out, mp4)+console.log(`card.mp4: ${mp4.length} bytes, ${new TextDecoder().decode(mp4.subarray(4, 8)) === "ftyp" ? "an mp4" : "NOT an mp4"} -> ${out}`)+process.exit(stop === "end_turn" && mp4.length > 1000 ? 0 : 1)diff --git a/sdk/cloud/test/smoke.sh b/sdk/cloud/test/smoke.shnew file mode 100755index 00000000..5be7ce3c--- /dev/null+++ b/sdk/cloud/test/smoke.sh@@ -0,0 +1,33 @@+#!/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.+#+# test/smoke.sh [RAEA_VERSION] default: the version in package.json+# IMAGE=raea-cloud:dev test/smoke.sh an image already built+set -uo pipefail+here=$(cd "$(dirname "$0")/.." && pwd)+v=${1:-$(node -p "require('$here/package.json').version")}+image=${IMAGE:-}+if [ -z "$image" ]; then+ image=raea-cloud:smoke+ docker build --platform linux/amd64 -f "$here/image/Dockerfile" --build-arg RAEA_VERSION="$v" --build-arg AGENTS="${AGENTS:-kimi-code}" -t "$image" "$here" || exit 1+fi+name=raea-cloud-smoke-$$+token=$(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; }+trap cleanup EXIT+docker run -d --platform linux/amd64 --name "$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)'+done+# a symlink in the workspace that points out of it, for the path check+docker exec "$name" sh -c 'ln -sfn /etc "$HOME/work/out-link"'+node "$here/test/smoke.ts" "http://127.0.0.1:$port" "$token"+code=$?+echo "--- container log"; docker logs "$name" 2>&1 | tail -15+exit $codediff --git a/sdk/cloud/test/smoke.ts b/sdk/cloud/test/smoke.tsnew file mode 100644index 00000000..5e03ef9d--- /dev/null+++ b/sdk/cloud/test/smoke.ts@@ -0,0 +1,92 @@+// 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.+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 cloud = new RaeaCloud({ url, token })+let failed = 0+const check = async (name: string, f: () => Promise<string>) => {+ const t0 = performance.now()+ try {+ console.log(`ok ${name}: ${await f()} (${Math.round(performance.now() - t0)} ms)`)+ } catch (e) {+ failed+++ console.log(`FAIL ${name}: ${(e as Error).message}`)+ }+}+const status = async (path: string, init: RequestInit = {}) => (await fetch(url + path, init)).status+const expect = (cond: unknown, msg: string) => {+ if (!cond) throw new Error(msg)+}++await check("healthz needs no token", async () => {+ expect((await status("/healthz")) === 200, "not 200")+ return "200"+})+await check("no token, a wrong token: 401", async () => {+ const a = await status("/v1/health")+ const b = await status("/v1/health", { headers: { authorization: `Bearer ${"x".repeat(token.length)}` } })+ expect(a === 401 && b === 401, `${a}, ${b}`)+ return `${a}, ${b}`+})+let workspace = ""+await check("health", async () => {+ const h = await cloud.health()+ workspace = h.workspace+ expect(/^\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}`+})+await check("files round trip", async () => {+ await cloud.write("smoke/a/b.txt", "hello cloud")+ const back = await cloud.text("smoke/a/b.txt")+ const ls = await cloud.list("smoke/a")+ expect(back === "hello cloud", `read back ${JSON.stringify(back)}`)+ expect(ls.some((e) => e.name === "b.txt" && e.bytes === 11), `listed ${JSON.stringify(ls)}`)+ return "written, read, listed"+})+await check("paths out of the workspace: 403", async () => {+ const auth = { authorization: `Bearer ${token}` }+ const got = [+ await status(`/v1/files?path=${encodeURIComponent("../../../etc/passwd")}`, { headers: auth }),+ await status(`/v1/files?path=${encodeURIComponent("/etc/passwd")}`, { headers: auth }),+ await status(`/v1/files?path=${encodeURIComponent("/tmp/x")}`, { method: "PUT", body: "x", headers: auth }),+ await status(`/v1/files?path=${encodeURIComponent("out-link/passwd")}`, { headers: auth }),+ ]+ expect(got.every((s) => s === 403), got.join(", "))+ return `.., absolute, PUT absolute, symlink out: ${got.join(", ")}`+})+await check("raea renders through /v1/run", async () => {+ let log = ""+ const init = await cloud.run(["init"], { cwd: "smoke/p", onOutput: (t) => (log += t) })+ expect(init === 0, `raea init exit ${init}: ${log.slice(-400)}`)+ const t0 = performance.now()+ const r = await cloud.run(["render", "edit.tsx", "--frame", "15", "-o", "card.png"], { cwd: "smoke/p", onOutput: (t) => (log += t) })+ expect(r === 0, `render exit ${r}: ${log.slice(-400)}`)+ const png = await cloud.read("smoke/p/card.png")+ expect(png[0] === 0x89 && png[1] === 0x50, "not a PNG")+ return `card.png ${png.length} bytes, render ${Math.round(performance.now() - t0)} ms`+})+await check("ACP turn with the stand-in agent", async () => {+ const s = await cloud.session({ cwd: "smoke" })+ const said: string[] = []+ const stop = await s.prompt("hello from the smoke test", (u: Update) => u.content?.text && said.push(u.content.text))+ s.close()+ const all = said.join(" | ")+ expect(stop === "end_turn", `stop ${stop}`)+ expect(said.includes("echo: hello from the smoke test"), all)+ expect(/raea: \d+\.\d+\.\d+/.test(all), `no raea in ${all}`)+ expect(all.includes(`cwd: ${workspace}`), `cwd not the workspace: ${all}`)+ expect(all.includes("token visible: no"), `the agent sees the token: ${all}`)+ expect(all.includes("permission: yes"), `permission not allowed once: ${all}`)+ return all+})+await check("ACP socket without a token: refused", async () => {+ const ws = new WebSocket(`${url.replace(/^http/, "ws")}/v1/acp`)+ const opened = await new Promise<boolean>((r) => ((ws.onopen = () => r(true)), (ws.onerror = () => r(false))))+ expect(!opened, "opened")+ return "refused"+})+console.log(failed ? `smoke: ${failed} FAILED` : "smoke: all passed")+process.exit(failed)diff --git a/sdk/cloud/tsconfig.json b/sdk/cloud/tsconfig.jsonnew file mode 100644index 00000000..e72d333a--- /dev/null+++ b/sdk/cloud/tsconfig.json@@ -0,0 +1 @@+{ "extends": "../tsconfig.base.json", "compilerOptions": { "types": ["node"], "lib": ["ES2023", "DOM"], "allowImportingTsExtensions": true, "noEmit": true }, "include": ["src", "server", "test"] }