Skip to content

armgit / raea

Public Imported from GitHub
0

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.

raea cloud's server gets POST /v1/shell {command, cwd, timeout_ms} (CL6b), for an agent whose loop runs elsewhere (raea-bot's shell tool): a bash command line in the workspace with /v1/run's NDJSON, in a process group of its own so a timeout (10 min default, 1 h most) or a dropped request stops all of it, the last line saying timed_out. RaeaCloud.shell() reads it through the same follow() as run(). test/smoke.ts checks output, exit code, the timeout, an empty command (400) and a cwd outside the workspace (403); passed against a local server.

shinyobjectz93b8e5553746
diff --git a/docs/cloud.feature b/docs/cloud.feature
index 45ee7c7f..2620735b 100644
--- a/docs/cloud.feature
+++ b/docs/cloud.feature
@@ -44,6 +44,12 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
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: CL6b. A shell for an agent the server doesn't run (raea-bot, 11-17)
+ Then POST /v1/shell {command, cwd, timeout_ms} runs a bash command line in the workspace, streaming the same
+ {out}, {err} and last {exit} lines
+ And past its timeout (10 minutes unless given, an hour at most), or when the request drops, its whole process
+ group is stopped, and a timeout's last line says timed_out
+ And an empty command is a 400 and a cwd outside the workspace a 403; test/smoke.ts checks all three
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
diff --git a/sdk/cloud/server/main.ts b/sdk/cloud/server/main.ts
index bd813c77..610a8ba9 100644
--- a/sdk/cloud/server/main.ts
+++ b/sdk/cloud/server/main.ts
@@ -6,6 +6,10 @@
// 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/shell {command, cwd?, timeout_ms?}
+// a bash command line in the workspace, the same NDJSON; past its timeout
+// (10 min unless given, 1 h at most) its process group is stopped and the last
+// line says {exit, timed_out: true}. For an agent's shell tool (raea-bot)
// 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
@@ -102,6 +106,36 @@ async function run(req: IncomingMessage, res: ServerResponse) {
res.on("close", () => child.exitCode === null && child.kill("SIGTERM"))
}
+const SHELL_DEFAULT_MS = 600_000
+const SHELL_MAX_MS = 3_600_000
+
+async function shell(req: IncomingMessage, res: ServerResponse) {
+ const { command, cwd, timeout_ms } = JSON.parse((await body(req)).toString() || "{}") as { command?: unknown; cwd?: string; timeout_ms?: unknown }
+ if (typeof command !== "string" || !command.trim()) return json(res, { error: "command must be a bash command line" }, 400)
+ const ms = typeof timeout_ms === "number" && timeout_ms > 0 ? Math.min(timeout_ms, SHELL_MAX_MS) : SHELL_DEFAULT_MS
+ const dir = resolve(cwd ?? ".")
+ mkdirSync(dir, { recursive: true })
+ res.writeHead(200, { "content-type": "application/x-ndjson" })
+ // in a process group of its own, so a timeout or a caller leaving stops what the command started too
+ const child = spawn("bash", ["-c", command], { cwd: dir, env: childEnv(), stdio: ["ignore", "pipe", "pipe"], detached: true })
+ const line = (v: unknown) => res.write(JSON.stringify(v) + "\n")
+ const stop = () => {
+ try {
+ if (child.pid && child.exitCode === null) process.kill(-child.pid, "SIGTERM")
+ } catch {}
+ }
+ let timedOut = false
+ const timer = setTimeout(() => ((timedOut = true), stop()), ms)
+ child.stdout.setEncoding("utf8").on("data", (out: string) => line({ out }))
+ child.stderr.setEncoding("utf8").on("data", (err: string) => line({ err }))
+ child.on("error", (e) => (clearTimeout(timer), line({ err: String(e) }), res.end(JSON.stringify({ exit: 127 }) + "\n")))
+ child.on("close", (code, signal) => {
+ clearTimeout(timer)
+ res.end(JSON.stringify({ exit: code ?? 128, signal: signal ?? undefined, timed_out: timedOut || undefined }) + "\n")
+ })
+ res.on("close", () => (clearTimeout(timer), stop()))
+}
+
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")
@@ -128,6 +162,7 @@ const server = createServer(async (req, res) => {
}
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/shell" && req.method === "POST") return await shell(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
diff --git a/sdk/cloud/src/index.ts b/sdk/cloud/src/index.ts
index cf8b0ea1..9890be06 100644
--- a/sdk/cloud/src/index.ts
+++ b/sdk/cloud/src/index.ts
@@ -68,6 +68,24 @@ export interface Login {
output: string
}
+/** Reads a /v1/run or /v1/shell answer: NDJSON {out} and {err} lines to onOutput, until the line with the exit code. */
+async function follow(res: Response, onOutput: ((text: string, stream: "out" | "err") => void) | undefined, what: string): Promise<{ exit: number; timedOut: boolean }> {
+ 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; timed_out?: boolean }
+ if (m.out !== undefined) onOutput?.(m.out, "out")
+ if (m.err !== undefined) onOutput?.(m.err, "err")
+ if (m.exit !== undefined) return { exit: m.exit, timedOut: !!m.timed_out }
+ }
+ }
+ throw new Error(`${what} ended without an exit code`)
+}
+
export class RaeaCloud {
readonly url: string
private token: string
@@ -107,20 +125,14 @@ export class RaeaCloud {
/** `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")
+ return (await follow(res, o.onOutput, "raea's run")).exit
+ }
+
+ /** A bash command line in the workspace (or `cwd` in it): its exit code, and whether it was stopped at its
+ * timeout (the server's 10 minutes unless `timeoutMs`, an hour at most); output goes to onOutput as it comes. */
+ async shell(command: string, o: { cwd?: string; timeoutMs?: number; onOutput?: (text: string, stream: "out" | "err") => void; signal?: AbortSignal } = {}): Promise<{ exit: number; timedOut: boolean }> {
+ const res = await this.call("/v1/shell", { method: "POST", body: JSON.stringify({ command, cwd: o.cwd, timeout_ms: o.timeoutMs }), headers: { "content-type": "application/json" }, signal: o.signal })
+ return follow(res, o.onOutput, "the shell command")
}
/** Starts `raea ARGS` on a folder sent as a tar (zstd, gzip or none), in a folder of its own on the server (a
diff --git a/sdk/cloud/test/smoke.ts b/sdk/cloud/test/smoke.ts
index 18e33150..418ebedb 100644
--- a/sdk/cloud/test/smoke.ts
+++ b/sdk/cloud/test/smoke.ts
@@ -74,6 +74,23 @@ 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`
})
+await check("a command line through /v1/shell", async () => {
+ let out = "", err = ""
+ const r = await cloud.shell("pwd; echo two >&2; printf 'a\\nb\\n' | wc -l; exit 3", { cwd: "smoke/sh", onOutput: (t, s) => (s === "out" ? (out += t) : (err += t)) })
+ expect(r.exit === 3 && !r.timedOut, `exit ${r.exit}, timed out ${r.timedOut}`)
+ expect(out.split("\n")[0].endsWith("/smoke/sh") && out.trim().endsWith("2") && err.trim() === "two", `out ${JSON.stringify(out)}, err ${JSON.stringify(err)}`)
+ const t0 = performance.now()
+ const slow = await cloud.shell("sleep 30 & sleep 30; echo never", { timeoutMs: 1500 })
+ const ms = performance.now() - t0
+ expect(slow.timedOut && ms < 10_000, `timed out ${slow.timedOut} after ${Math.round(ms)} ms`)
+ const auth = { authorization: `Bearer ${token}`, "content-type": "application/json" }
+ const bad = [
+ (await fetch(url + "/v1/shell", { method: "POST", headers: auth, body: JSON.stringify({ command: "" }) })).status,
+ (await fetch(url + "/v1/shell", { method: "POST", headers: auth, body: JSON.stringify({ command: "pwd", cwd: "../.." }) })).status,
+ ]
+ expect(bad[0] === 400 && bad[1] === 403, `empty ${bad[0]}, cwd outside ${bad[1]}`)
+ return `exit 3 with its output, stopped at 1.5 s (${Math.round(ms)} ms), empty ${bad[0]}, outside ${bad[1]}`
+})
/** 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 })