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 box signs agents in to a Google AI subscription: Antigravity's Google sign-in runs on the box, the person pastes back the address Google sent them to, and the token file comes back once (POST /v1/google-token, google-token.ts); an agent socket given it (RAEA_GOOGLE_CREDENTIAL) has it written into its own GEMINI_HOME. With the box's Claude sign-in (claude-token.ts, per-socket keys and homes), live on raea-1 since 11-21 and committed here; antigravity-acp joins the box's default agents

shinyobjectz063ae93f3025
diff --git a/sdk/cloud/deploy/sprites/box.sh b/sdk/cloud/deploy/sprites/box.sh
index 1903ba11..3b4278b6 100755
--- a/sdk/cloud/deploy/sprites/box.sh
+++ b/sdk/cloud/deploy/sprites/box.sh
@@ -22,7 +22,7 @@ set -euo pipefail
NAME=${2:-}
[ -n "$NAME" ] || { echo "box: name the Sprite"; exit 2; }
RAEA_VERSION=${RAEA_VERSION:-0.1.6}
-AGENTS=${AGENTS:-kimi-code claude-acp}
+AGENTS=${AGENTS:-kimi-code claude-acp antigravity-acp}
HERE=$(cd "$(dirname "$0")/../.." && pwd)
FARM=${RAEA_FARM_ENV:-$HOME/.config/raea-cloud/farm.env}
diff --git a/sdk/cloud/server/claude-token.ts b/sdk/cloud/server/claude-token.ts
new file mode 100644
index 00000000..15c4d3ea
--- /dev/null
+++ b/sdk/cloud/server/claude-token.ts
@@ -0,0 +1,151 @@
+// A Claude subscription's token, made by Claude Code's own sign-in (`claude setup-token`) on this box, so a person
+// signs in with nothing but a browser: raea cloud asks for a sign-in, shows them the claude.com link it prints, they
+// sign in there and paste back the code Anthropic shows, and Claude Code prints the token (a year long, for Claude
+// Code's use only). The token goes back to the caller once and is never kept here: each sign-in runs in a config
+// folder of its own that's removed when it ends, and one left waiting is stopped after 15 minutes.
+// POST /v1/claude-token {id, url}: a sign-in started, and the link to open
+// POST /v1/claude-token/ID {code} {token}: the code pasted in; or {error}
+// POST /v1/claude-token/check {token} {ok, said}: one short turn on a token
+import { type ChildProcess, spawn } from "node:child_process"
+import { randomBytes } from "node:crypto"
+import { mkdtempSync, rmSync } from "node:fs"
+import { tmpdir } from "node:os"
+import path from "node:path"
+
+interface SignIn {
+ child: ChildProcess
+ dir: string
+ out: string
+ url?: string
+ token?: string
+ ended: boolean
+ timer: NodeJS.Timeout
+}
+
+const waiting = new Map<string, SignIn>()
+
+/** a program on a terminal (200x60), its input from our stdin and its screen to our stdout. script(1) was here first,
+ * but Claude Code never took Enter after a long code through it; written to the terminal directly, it does */
+const BRIDGE = `import os, pty, select, struct, fcntl, termios, sys
+pid, fd = pty.fork()
+if pid == 0:
+ os.execvp(sys.argv[1], sys.argv[1:])
+fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 60, 200, 0, 0))
+while True:
+ r, _, _ = select.select([fd, 0], [], [])
+ if fd in r:
+ try:
+ b = os.read(fd, 65536)
+ except OSError:
+ break
+ if not b:
+ break
+ os.write(1, b)
+ if 0 in r:
+ b = os.read(0, 65536)
+ if not b:
+ break
+ os.write(fd, b)
+os.kill(pid, 9) if os.waitpid(pid, os.WNOHANG) == (0, 0) else None
+`
+const CLAUDE = process.env.RAEA_CLAUDE_BIN ?? "claude"
+const TOKEN = /sk-ant-oat01-[A-Za-z0-9_-]{20,}/
+
+/** the text a terminal shows, with its escapes gone; OSC 8 links keep their address */
+export const plain = (s: string) =>
+ s
+ .replace(/\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)/g, " $1 ")
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "")
+ .replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "")
+
+/** the sign-in link Claude Code printed */
+export const urlIn = (out: string) => /https:\/\/claude\.(?:com|ai)\/\S*oauth\/authorize\?\S+/.exec(plain(out))?.[0]
+/** the token it printed once the code was accepted (on one line: the terminal is 200 columns wide, room for it; 1000 broke Enter after a long code) */
+export const tokenIn = (out: string) => TOKEN.exec(plain(out))?.[0]
+
+function end(id: string) {
+ const s = waiting.get(id)
+ if (!s) return
+ waiting.delete(id)
+ clearTimeout(s.timer)
+ if (s.child.exitCode === null) s.child.kill("SIGTERM")
+ rmSync(s.dir, { recursive: true, force: true })
+}
+
+const until = async (s: SignIn, ok: () => boolean, ms: number) => {
+ for (let t = 0; t < ms && !ok() && !s.ended; t += 200) await new Promise((r) => setTimeout(r, 200))
+}
+
+export async function startClaudeSignIn(env: NodeJS.ProcessEnv): Promise<{ id: string; url: string }> {
+ const dir = mkdtempSync(path.join(tmpdir(), "claude-sign-in-"))
+ const id = randomBytes(12).toString("hex")
+ const clean: NodeJS.ProcessEnv = { ...env, CLAUDE_CONFIG_DIR: dir, BROWSER: "true", TERM: "xterm-256color" }
+ for (const k of ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"]) delete clean[k]
+ // Claude Code on a terminal of its own (BRIDGE), 200 columns: the token fits on one line (the link is read from its
+ // OSC 8 address)
+ const child = spawn("python3", ["-I", "-c", BRIDGE, CLAUDE, "setup-token"], { cwd: dir, env: clean, stdio: ["pipe", "pipe", "pipe"] })
+ const s: SignIn = { child, dir, out: "", ended: false, timer: setTimeout(() => end(id), 15 * 60_000) }
+ waiting.set(id, s)
+ const read = (c: string) => {
+ s.out += c
+ s.url ??= urlIn(s.out)
+ s.token ??= tokenIn(s.out)
+ }
+ child.stdout!.setEncoding("utf8").on("data", read)
+ child.stderr!.setEncoding("utf8").on("data", read)
+ child.on("exit", () => (s.ended = true))
+ await until(s, () => !!s.url, 30_000)
+ if (!s.url) {
+ const why = plain(s.out).replace(/\s+/g, " ").trim().slice(-300)
+ end(id)
+ throw new Error(`Claude Code didn't print a sign-in link${why ? `: ${why}` : ""}`)
+ }
+ return { id, url: s.url }
+}
+
+export async function finishClaudeSignIn(id: string, code: string): Promise<{ token: string }> {
+ const s = waiting.get(id)
+ if (!s) throw new Error("that sign-in has ended (they last 15 minutes): start again")
+ const c = code.trim()
+ if (!/^[A-Za-z0-9_#.~-]{10,600}$/.test(c)) throw new Error("that doesn't look like the code claude.com showed")
+ const from = s.out.length
+ // the code as one paste, then Enter on its own a second later (Enter in the same write is taken as part of the paste)
+ s.child.stdin!.write(c)
+ await new Promise((r) => setTimeout(r, 1000))
+ s.child.stdin!.write("\r")
+ // done at the token, or as soon as Claude Code says the code was wrong
+ await until(s, () => !!s.token || /OAuth error|Invalid code|expired/i.test(plain(s.out.slice(from))), 60_000)
+ const token = s.token
+ const said = plain(s.out.slice(from)).replace(/\s+/g, " ").trim()
+ // what Claude Code said after the code, any token masked: the service log shows why a sign-in didn't finish
+ console.log(`raea-cloud: claude sign-in ${id.slice(0, 6)} ${token ? "got a token" : "no token"}: ${JSON.stringify(s.out.slice(from).replace(/sk-ant-[A-Za-z0-9_-]{8,}/g, "sk-ant-…")).slice(-1500)}`)
+ end(id)
+ if (!token) throw new Error(`Claude Code didn't accept the code${said ? `: ${said.slice(-300)}` : ""}`)
+ return { token }
+}
+
+/** whether a token (a subscription's, or an API key) gets an answer from Claude Code: one short turn, in a config folder
+ * of its own that's removed after. {ok, said} */
+export async function checkClaude(env: NodeJS.ProcessEnv, token: string): Promise<{ ok: boolean; said: string }> {
+ const t = token.trim()
+ if (!/^sk-ant-(oat01|api03)-[A-Za-z0-9_-]{20,}$/.test(t)) throw new Error("that isn't a Claude token (sk-ant-oat01-…) or API key (sk-ant-api03-…)")
+ const dir = mkdtempSync(path.join(tmpdir(), "claude-check-"))
+ const clean: NodeJS.ProcessEnv = { ...env, CLAUDE_CONFIG_DIR: dir }
+ delete clean.ANTHROPIC_API_KEY
+ delete clean.CLAUDE_CODE_OAUTH_TOKEN
+ clean[t.startsWith("sk-ant-oat01-") ? "CLAUDE_CODE_OAUTH_TOKEN" : "ANTHROPIC_API_KEY"] = t
+ try {
+ const child = spawn(CLAUDE, ["-p", "Reply with just the word: ready", "--max-turns", "1"], { cwd: dir, env: clean, stdio: ["ignore", "pipe", "pipe"] })
+ let out = ""
+ child.stdout.setEncoding("utf8").on("data", (c: string) => (out += c))
+ child.stderr.setEncoding("utf8").on("data", (c: string) => (out += c))
+ const code = await new Promise<number | null>((ok) => {
+ const timer = setTimeout(() => child.kill("SIGTERM"), 90_000)
+ child.on("exit", (c) => (clearTimeout(timer), ok(c)))
+ })
+ const said = plain(out).replace(/\s+/g, " ").trim().slice(0, 400)
+ return { ok: code === 0 && /ready/i.test(said), said }
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+}
diff --git a/sdk/cloud/server/google-token.ts b/sdk/cloud/server/google-token.ts
new file mode 100644
index 00000000..310d9588
--- /dev/null
+++ b/sdk/cloud/server/google-token.ts
@@ -0,0 +1,278 @@
+// A Google AI subscription (Google One AI Pro or Ultra) for the box's Gemini agent, Google Antigravity (the ACP
+// registry's antigravity-acp). Since 2026-06-18 Gemini CLI refuses personal Google sign-ins, and Antigravity is where
+// Google sends them; it is also where Pro and Ultra get Gemini 4 Neon. Its "Log in with Google" (ACP method
+// oauth-personal) is an OAuth sign-in whose address sends the browser back to 127.0.0.1 on the machine it runs on.
+// Here that machine is the box, so the person signs in in their own browser, lands on a page that doesn't load (their
+// computer has nothing on that port), and pastes that page's address back; the box hands it to Antigravity's own
+// listener on 127.0.0.1, exactly as their browser would have.
+//
+// Off macOS Antigravity keeps its Google token as one JSON file under GEMINI_HOME. After a sign-in that file goes back
+// to the caller once, as one string (agy1:BASE64 of {path under GEMINI_HOME: text}), and is never kept here: each
+// sign-in runs in a folder of its own that's removed when it ends, and one left waiting is stopped after 15 minutes.
+// An agent socket that's given the string (x-raea-agent-env RAEA_GOOGLE_CREDENTIAL, main.ts) has it written into its
+// own GEMINI_HOME before Antigravity starts.
+// POST /v1/google-token {id, url}: a sign-in started, and the link to open
+// POST /v1/google-token/ID {address} {credential, email?}: the address the browser landed on; or {error}
+// POST /v1/google-token/check {credential} {ok, said, models, current}: one short turn on a credential or a Gemini
+// API key (AIza…)
+import { type ChildProcess, spawn } from "node:child_process"
+import { randomBytes } from "node:crypto"
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
+import { tmpdir } from "node:os"
+import path from "node:path"
+import { spawnFor } from "./agents.ts"
+
+export const GOOGLE_AGENT = process.env.RAEA_GOOGLE_AGENT ?? "antigravity-acp"
+const PREFIX = "agy1:"
+const API_KEY = /^AIza[0-9A-Za-z_-]{30,}$/
+/** what never reaches Antigravity from the container: its own Google sign-ins and keys */
+const GOOGLE_ENV = ["GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_PROJECT", "GOOGLE_GENAI_USE_VERTEXAI", "GEMINI_HOME"]
+
+// ---- one Antigravity process, spoken to over ACP on its stdin and stdout ----
+interface Agy {
+ child: ChildProcess
+ /** everything it printed, both streams (its sign-in link goes to either) */
+ out: string
+ ended: boolean
+ request<T = any>(method: string, params: Record<string, unknown>, ms?: number): Promise<T>
+ onUpdate?: (u: any) => void
+}
+
+function startAgy(env: NodeJS.ProcessEnv, home: string, cwd: string, own: Record<string, string> = {}): Agy {
+ const a = spawnFor(GOOGLE_AGENT)
+ const clean: NodeJS.ProcessEnv = { ...env, ...a.env }
+ for (const k of GOOGLE_ENV) delete clean[k]
+ Object.assign(clean, own, { GEMINI_HOME: home, AGY_ACP_FORCE_FILE_STORAGE: "1", BROWSER: "true", NO_BROWSER: "true" })
+ const child = spawn(a.command, a.args, { cwd, env: clean, stdio: ["pipe", "pipe", "pipe"] })
+ const pending = new Map<number, { ok: (v: any) => void; no: (e: Error) => void }>()
+ let next = 1
+ let buf = ""
+ const agy: Agy = {
+ child,
+ out: "",
+ ended: false,
+ request(method, params, ms = 60_000) {
+ if (agy.ended) return Promise.reject(new Error(`Antigravity has stopped: ${tail(agy.out)}`))
+ const id = next++
+ return new Promise((ok, no) => {
+ const t = setTimeout(() => (pending.delete(id), no(new Error(`Antigravity didn't answer ${method} in ${ms / 1000} s`))), ms)
+ pending.set(id, { ok: (v) => (clearTimeout(t), ok(v)), no: (e) => (clearTimeout(t), no(e)) })
+ child.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n")
+ })
+ },
+ }
+ child.stdout!.setEncoding("utf8").on("data", (c: string) => {
+ agy.out += c
+ buf += c
+ for (let i; (i = buf.indexOf("\n")) >= 0; ) {
+ const line = buf.slice(0, i).trim()
+ buf = buf.slice(i + 1)
+ if (!line.startsWith("{")) continue
+ let m: any
+ try {
+ m = JSON.parse(line)
+ } catch {
+ continue
+ }
+ if (m.id !== undefined && m.method === undefined) {
+ const p = pending.get(m.id)
+ pending.delete(m.id)
+ if (m.error) p?.no(new Error(m.error.message ?? JSON.stringify(m.error)))
+ else p?.ok(m.result)
+ } else if (m.method === "session/update") agy.onUpdate?.(m.params?.update)
+ else if (m.id !== undefined) {
+ // its requests to us: a permission is granted (a check asks for none), anything else refused
+ const o = m.params?.options?.find((x: any) => x.kind === "allow_once") ?? m.params?.options?.[0]
+ const reply = m.method === "session/request_permission" && o ? { result: { outcome: { outcome: "selected", optionId: o.optionId } } } : { error: { code: -32601, message: `no ${m.method} here` } }
+ child.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id: m.id, ...reply }) + "\n")
+ }
+ }
+ })
+ child.stderr!.setEncoding("utf8").on("data", (c: string) => (agy.out += c))
+ child.on("exit", () => {
+ agy.ended = true
+ for (const p of pending.values()) p.no(new Error(`Antigravity stopped: ${tail(agy.out)}`))
+ pending.clear()
+ })
+ return agy
+}
+
+const initialize = (a: Agy) => a.request("initialize", { protocolVersion: 1, clientCapabilities: {}, clientInfo: { name: "raea-cloud", version: "1" } })
+/** its last words, without its Python warnings or log prefixes */
+const tail = (out: string) =>
+ out
+ .split("\n")
+ .filter((l) => l.trim() && !/SyntaxWarning|^\s*[IW]\d{4} /.test(l))
+ .slice(-3)
+ .join(" ")
+ .slice(-300)
+
+/** the Google sign-in link Antigravity printed, and where it sends the browser back to */
+export function linkIn(out: string): { url: string; port: number; state: string } | undefined {
+ const m = /https:\/\/accounts\.google\.com\/o\/oauth2\/[^\s"']+/.exec(out)
+ if (!m) return undefined
+ const u = new URL(m[0])
+ const back = new URL(u.searchParams.get("redirect_uri") ?? "")
+ if (!/^(127\.0\.0\.1|localhost|\[::1\])$/.test(back.hostname)) return undefined
+ return { url: m[0], port: Number(back.port), state: u.searchParams.get("state") ?? "" }
+}
+
+/** the address the person's browser landed on, checked against the sign-in it belongs to: the query to hand on */
+export function landedQuery(address: string, s: { port: number; state: string }): string {
+ let u: URL
+ try {
+ u = new URL(address.trim())
+ } catch {
+ throw new Error("paste the whole address of the page Google sent you to (it starts http://127.0.0.1)")
+ }
+ if (!/^(127\.0\.0\.1|localhost|\[::1\])$/.test(u.hostname) || Number(u.port) !== s.port) throw new Error("that address isn't the page this sign-in sent you to: sign in from the newest link")
+ if (u.searchParams.get("error")) throw new Error(`Google said ${u.searchParams.get("error")}`)
+ if (!u.searchParams.get("code")) throw new Error("that address has no code in it: copy it from the browser's address bar after you approve")
+ if (u.searchParams.get("state") !== s.state) throw new Error("that address is from another sign-in: sign in from the newest link")
+ return `${u.pathname}${u.search}`
+}
+
+// ---- the credential: the files under GEMINI_HOME that hold a refresh token, as one string ----
+export function packCredential(home: string): string | undefined {
+ const files: Record<string, string> = {}
+ const walk = (dir: string) => {
+ for (const d of readdirSync(dir, { withFileTypes: true })) {
+ const p = path.join(dir, d.name)
+ if (d.isDirectory()) walk(p)
+ else if (d.isFile() && d.name.endsWith(".json") && statSync(p).size < 64_000) {
+ const text = readFileSync(p, "utf8")
+ if (/"refresh_token"\s*:/.test(text)) files[path.relative(home, p)] = text
+ }
+ }
+ }
+ walk(home)
+ return Object.keys(files).length ? PREFIX + Buffer.from(JSON.stringify(files)).toString("base64") : undefined
+}
+
+/** writes a credential's files into an agent's GEMINI_HOME, 0600 under 0700 folders; each path stays inside it */
+export function unpackCredential(credential: string, home: string): void {
+ if (!credential.startsWith(PREFIX)) throw new Error("that isn't a Google sign-in from raea cloud")
+ let files: Record<string, unknown>
+ try {
+ files = JSON.parse(Buffer.from(credential.slice(PREFIX.length), "base64").toString("utf8"))
+ } catch {
+ throw new Error("that Google sign-in can't be read")
+ }
+ for (const [rel, text] of Object.entries(files)) {
+ const p = path.resolve(home, rel)
+ if (typeof text !== "string" || !p.startsWith(path.resolve(home) + path.sep)) throw new Error("that Google sign-in names a file outside its folder")
+ mkdirSync(path.dirname(p), { recursive: true, mode: 0o700 })
+ writeFileSync(p, text, { mode: 0o600 })
+ }
+}
+
+/** the account a credential is for, when its token file says */
+const emailIn = (credential: string): string | undefined => /"email"\s*:\s*"([^"]+@[^"]+)"/.exec(Buffer.from(credential.slice(PREFIX.length), "base64").toString("utf8"))?.[1]
+
+// ---- signing in ----
+interface SignIn {
+ agy: Agy
+ dir: string
+ home: string
+ port: number
+ state: string
+ authed: boolean
+ failed?: string
+ timer: NodeJS.Timeout
+}
+const waiting = new Map<string, SignIn>()
+
+function end(id: string) {
+ const s = waiting.get(id)
+ if (!s) return
+ waiting.delete(id)
+ clearTimeout(s.timer)
+ if (s.agy.child.exitCode === null) s.agy.child.kill("SIGTERM")
+ rmSync(s.dir, { recursive: true, force: true })
+}
+
+const until = async (ok: () => boolean, ms: number) => {
+ for (let t = 0; t < ms && !ok(); t += 200) await new Promise((r) => setTimeout(r, 200))
+}
+
+export async function startGoogleSignIn(env: NodeJS.ProcessEnv): Promise<{ id: string; url: string }> {
+ const dir = mkdtempSync(path.join(tmpdir(), "google-sign-in-"))
+ const home = path.join(dir, ".gemini")
+ mkdirSync(home, { mode: 0o700 })
+ const agy = startAgy(env, home, dir)
+ const id = randomBytes(12).toString("hex")
+ try {
+ await initialize(agy)
+ } catch (e) {
+ agy.child.kill("SIGTERM")
+ rmSync(dir, { recursive: true, force: true })
+ throw new Error(`Antigravity didn't start: ${(e as Error).message}`)
+ }
+ const s: SignIn = { agy, dir, home, port: 0, state: "", authed: false, timer: setTimeout(() => end(id), 15 * 60_000) }
+ waiting.set(id, s)
+ // authenticate answers only once the browser has come back: it waits for the whole sign-in
+ agy.request("authenticate", { methodId: "oauth-personal" }, 15 * 60_000).then(
+ () => (s.authed = true),
+ (e: Error) => (s.failed = e.message),
+ )
+ await until(() => !!linkIn(agy.out) || !!s.failed || agy.ended, 30_000)
+ const link = linkIn(agy.out)
+ if (!link) {
+ const why = s.failed ?? tail(agy.out)
+ end(id)
+ throw new Error(`Antigravity didn't print a Google sign-in link${why ? `: ${why}` : ""}`)
+ }
+ s.port = link.port
+ s.state = link.state
+ return { id, url: link.url }
+}
+
+export async function finishGoogleSignIn(id: string, address: string): Promise<{ credential: string; email?: string }> {
+ const s = waiting.get(id)
+ if (!s) throw new Error("that sign-in has ended (they last 15 minutes): start again")
+ const q = landedQuery(address, s)
+ // the browser's visit to Antigravity's listener, made from the box
+ const r = await fetch(`http://127.0.0.1:${s.port}${q}`, { signal: AbortSignal.timeout(30_000) }).catch((e: Error) => ({ ok: false, status: 0, statusText: e.message }))
+ await until(() => s.authed || !!s.failed || s.agy.ended, 60_000)
+ const credential = s.authed ? packCredential(s.home) : undefined
+ const why = s.failed ?? (r.ok ? tail(s.agy.out) : `its sign-in page answered ${r.status || r.statusText}`)
+ console.log(`raea-cloud: google sign-in ${id.slice(0, 6)} ${credential ? "got a credential" : `no credential: ${why}`}`)
+ end(id)
+ if (!credential) throw new Error(`Google's sign-in didn't finish${why ? `: ${why}` : ""}`)
+ return { credential, email: emailIn(credential) }
+}
+
+/** whether a credential (or a Gemini API key) gets an answer from Antigravity: one short turn in a folder of its own
+ * that's removed after; the models it offers that account, and the one it picked */
+export async function checkGoogle(env: NodeJS.ProcessEnv, credential: string): Promise<{ ok: boolean; said: string; models: { id: string; name: string }[]; current?: string }> {
+ const c = credential.trim()
+ const key = API_KEY.test(c)
+ if (!key && !c.startsWith(PREFIX)) throw new Error("that isn't a Google sign-in from raea cloud or a Gemini API key (AIza…)")
+ const dir = mkdtempSync(path.join(tmpdir(), "google-check-"))
+ const home = path.join(dir, ".gemini")
+ mkdirSync(home, { mode: 0o700 })
+ if (!key) unpackCredential(c, home)
+ const agy = startAgy(env, home, dir, key ? { GEMINI_API_KEY: c } : {})
+ let said = ""
+ agy.onUpdate = (u) => {
+ if (u?.sessionUpdate === "agent_message_chunk" && u.content?.type === "text") said += u.content.text ?? ""
+ }
+ const timer = setTimeout(() => agy.child.kill("SIGTERM"), 120_000)
+ try {
+ await initialize(agy)
+ // with a good credential it signs in from the file; a link printed means Google wants a new sign-in
+ const auth = agy.request("authenticate", { methodId: key ? "gemini-api-key" : "oauth-personal" }, 45_000)
+ await Promise.race([auth, until(() => !!linkIn(agy.out), 45_000).then(() => linkIn(agy.out) && Promise.reject(new Error("Google wants this account signed in again")))])
+ const s = await agy.request<{ sessionId: string; models?: { availableModels?: { modelId: string; name?: string }[]; currentModelId?: string } }>("session/new", { cwd: dir, mcpServers: [] })
+ const models = (s.models?.availableModels ?? []).map((m) => ({ id: m.modelId, name: m.name ?? m.modelId }))
+ await agy.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "Reply with just the word: ready" }] }, 90_000)
+ said = said.replace(/\s+/g, " ").trim().slice(0, 400)
+ return { ok: /ready/i.test(said), said, models, current: s.models?.currentModelId }
+ } catch (e) {
+ return { ok: false, said: (e as Error).message.slice(0, 400), models: [] }
+ } finally {
+ clearTimeout(timer)
+ if (agy.child.exitCode === null) agy.child.kill("SIGTERM")
+ rmSync(dir, { recursive: true, force: true })
+ }
+}
diff --git a/sdk/cloud/server/main.ts b/sdk/cloud/server/main.ts
index 48dbbe54..9b0a7902 100644
--- a/sdk/cloud/server/main.ts
+++ b/sdk/cloud/server/main.ts
@@ -11,8 +11,20 @@
// (10 min unless given, 1 h at most) its process group is stopped and the last
// line says {exit, timed_out: true}. For an agent's shell tool (raea cloud)
// POST /v1/login?agent=ID an agent's terminal sign-in: {url, code, state, output}; GET says where it is
+// POST /v1/claude-token a Claude subscription sign-in in a browser: {id, url} (claude-token.ts)
+// POST /v1/claude-token/ID {code} the code claude.com showed, in: {token}, handed back once and never kept
+// POST /v1/claude-token/check {token} one short Claude Code turn on it: {ok, said}
+// POST /v1/google-token a Google AI subscription sign-in (Antigravity): {id, url} (google-token.ts)
+// POST /v1/google-token/ID {address} the address Google's sign-in landed on, in: {credential, email?}, handed back once
+// POST /v1/google-token/check {credential} one short Antigravity turn on it (or a Gemini API key): {ok, said, models}
// WS /v1/acp?agent=ID one agent process per socket: a text frame is one ACP message to its stdin,
-// each line it prints is one frame back
+// each line it prints is one frame back. A caller signing the agent in as one of
+// its own clients (raea cloud, per workspace) sends x-raea-agent-env: JSON of the
+// model keys below, and x-raea-agent-home: a short name. That socket's agent gets
+// only those keys (never the container's) and its own config folder under
+// ~/.agent-homes/NAME, so one client's sign-in never runs another's work. A
+// Google sign-in (RAEA_GOOGLE_CREDENTIAL) is the one thing written: its token
+// file, into that socket's own GEMINI_HOME, where Antigravity reads it.
// POST /v1/jobs?args=JSON a render job: a folder in (tar.zst), `raea ARGS` on it, followed with
// GET /v1/jobs/ID?from=N short requests, and the files it made back from /out (jobs.ts); how a CPU
// GET /v1/jobs/ID/out box hands renders to a GPU worker (offload.ts)
@@ -29,6 +41,8 @@ import { WebSocketServer } from "ws"
import { installed, spawnFor } from "./agents.ts"
import { device } from "./gpu.ts"
import * as jobs from "./jobs.ts"
+import { checkClaude, finishClaudeSignIn, startClaudeSignIn } from "./claude-token.ts"
+import { checkGoogle, finishGoogleSignIn, startGoogleSignIn, unpackCredential } from "./google-token.ts"
import { login, loginState } from "./login.ts"
import { Outside, resolve, WORK } from "./workspace.ts"
@@ -48,6 +62,55 @@ const childEnv = (): NodeJS.ProcessEnv => {
}
let version: string | undefined
+
+/** the model keys a caller may hand one agent process, and the config folder each agent keeps its state in */
+const AGENT_KEYS = ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY", "CODEX_API_KEY", "GEMINI_API_KEY"] as const
+const AGENT_HOMES: Record<string, string> = { CLAUDE_CONFIG_DIR: "claude", CODEX_HOME: "codex", GEMINI_CLI_HOME: "gemini", GEMINI_HOME: "gemini/.gemini" }
+/** a Google sign-in's token file (google-token.ts), written into the socket's GEMINI_HOME rather than handed on */
+const GOOGLE_CREDENTIAL = "RAEA_GOOGLE_CREDENTIAL"
+
+/** a socket's own sign-in (its headers), or null to run on the container's environment */
+export function socketEnv(headers: Record<string, string | string[] | undefined>, home = process.env.HOME ?? "/root"): Record<string, string> | null {
+ const raw = headers["x-raea-agent-env"]
+ if (typeof raw !== "string" || !raw) return null
+ let given: Record<string, unknown>
+ try {
+ given = JSON.parse(raw)
+ } catch {
+ throw new Error("x-raea-agent-env isn't JSON")
+ }
+ const env: Record<string, string> = {}
+ for (const k of AGENT_KEYS) {
+ const v = given[k]
+ if (typeof v === "string" && v) env[k] = v
+ }
+ const google = typeof given[GOOGLE_CREDENTIAL] === "string" ? (given[GOOGLE_CREDENTIAL] as string) : ""
+ if (!Object.keys(env).length && !google) throw new Error(`x-raea-agent-env names none of ${[...AGENT_KEYS, GOOGLE_CREDENTIAL].join(", ")}`)
+ const name = String(headers["x-raea-agent-home"] ?? "")
+ if (!/^[a-z0-9][a-z0-9_-]{0,62}$/.test(name)) throw new Error("x-raea-agent-home must be a short lowercase name")
+ for (const [k, dir] of Object.entries(AGENT_HOMES)) {
+ env[k] = path.join(home, ".agent-homes", name, dir)
+ mkdirSync(env[k], { recursive: true, mode: 0o700 })
+ }
+ if (google) {
+ unpackCredential(google, env.GEMINI_HOME)
+ env.AGY_ACP_FORCE_FILE_STORAGE = "1"
+ }
+ return env
+}
+
+/** what a socket signed in as one of raea cloud's clients runs with: its agent works one turn at a time for a caller
+ * that ends the run when the turn ends, so Claude Code mustn't background a command and end its turn to wait for it
+ * (11-21: a render backgrounded, the turn ended, the project stopped with nothing to show), and a render through
+ * raea's MCP tools or in the shell gets half an hour */
+const RUN_DEFAULTS: Record<string, string> = { CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1", BASH_DEFAULT_TIMEOUT_MS: "1800000", BASH_MAX_TIMEOUT_MS: "3600000", MCP_TOOL_TIMEOUT: "1800000" }
+
+/** the container's environment less every model key: a socket with its own sign-in never falls back to the box's */
+const withoutKeys = (env: NodeJS.ProcessEnv) => {
+ const out = { ...env }
+ for (const k of [...AGENT_KEYS, "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS"]) delete out[k]
+ return out
+}
const raeaVersion = () => {
try {
version ??= execFileSync(RAEA, ["--version"], { encoding: "utf8", timeout: 20_000, env: childEnv() }).trim()
@@ -181,6 +244,26 @@ const server = createServer(async (req, res) => {
const f = await jobs.follow(job[1], Number(url.searchParams.get("from") ?? 0))
return f ? json(res, f) : json(res, { error: "no job with that id" }, 404)
}
+ if (url.pathname === "/v1/claude-token" && req.method === "POST") return json(res, await startClaudeSignIn(childEnv()))
+ if (url.pathname === "/v1/claude-token/check" && req.method === "POST") {
+ const b = JSON.parse((await body(req)).toString("utf8") || "{}") as { token?: unknown }
+ return json(res, await checkClaude(childEnv(), String(b.token ?? "")))
+ }
+ if (url.pathname === "/v1/google-token" && req.method === "POST") return json(res, await startGoogleSignIn(childEnv()))
+ if (url.pathname === "/v1/google-token/check" && req.method === "POST") {
+ const b = JSON.parse((await body(req)).toString("utf8") || "{}") as { credential?: unknown }
+ return json(res, await checkGoogle(childEnv(), String(b.credential ?? "")))
+ }
+ const gt = /^\/v1\/google-token\/([0-9a-f]{24})$/.exec(url.pathname)
+ if (gt && req.method === "POST") {
+ const b = JSON.parse((await body(req)).toString("utf8") || "{}") as { address?: unknown }
+ return json(res, await finishGoogleSignIn(gt[1], String(b.address ?? "")))
+ }
+ const ct = /^\/v1\/claude-token\/([0-9a-f]{24})$/.exec(url.pathname)
+ if (ct && req.method === "POST") {
+ const b = JSON.parse((await body(req)).toString("utf8") || "{}") as { code?: unknown }
+ return json(res, await finishClaudeSignIn(ct[1], String(b.code ?? "")))
+ }
if (url.pathname === "/v1/login") {
const a = spawnFor(url.searchParams.get("agent") ?? undefined)
return json(res, req.method === "POST" ? await login(a, childEnv()) : loginState(a.id))
@@ -204,8 +287,15 @@ server.on("upgrade", (req, socket, head) => {
return socket.end(`HTTP/1.1 400 Bad Request\r\ncontent-type: text/plain\r\n\r\n${(e as Error).message}`)
}
const agent = a
+ let own: Record<string, string> | null
+ try {
+ own = socketEnv(req.headers)
+ } catch (e) {
+ return socket.end(`HTTP/1.1 400 Bad Request\r\ncontent-type: text/plain\r\n\r\n${(e as Error).message}`)
+ }
+ const env = own ? { ...withoutKeys(childEnv()), ...agent.env, ...RUN_DEFAULTS, ...own } : { ...childEnv(), ...agent.env }
wss.handleUpgrade(req, socket, head, (ws) => {
- const child = spawn(agent.command, agent.args, { cwd: WORK, env: { ...childEnv(), ...agent.env }, stdio: ["pipe", "pipe", "inherit"] })
+ const child = spawn(agent.command, agent.args, { cwd: WORK, 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) => {
diff --git a/sdk/cloud/test/units.ts b/sdk/cloud/test/units.ts
index bd249f08..0932170b 100644
--- a/sdk/cloud/test/units.ts
+++ b/sdk/cloud/test/units.ts
@@ -9,6 +9,7 @@ import path from "node:path"
import { parseSummary, pick } from "../server/gpu.ts"
import { plan, projectRoot } from "../server/offload.ts"
import { shellEnv } from "../server/shell-os.ts"
+import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
const L4 = `Devices:
========
@@ -76,3 +77,32 @@ assert.deepEqual(shellEnv({ Path: "C:\\w" }, true, "C:\\g\\usr\\bin\\sh.exe"), {
assert.deepEqual(shellEnv({ PATH: "C:\\w" }, true, "bash"), { PATH: "C:\\w" })
assert.deepEqual(shellEnv({ PATH: "/usr/bin" }, false, "/bin/bash"), { PATH: "/usr/bin" })
console.log("units: ok")
+
+// google-token.ts: Antigravity's Google sign-in link, the address the browser lands on, the credential's files
+{
+ const out = `I1124 credential_manager.py:561] Launching browser login flow...\nhttps://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=x.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A54616%2F&state=abc123&access_type=offline\n`
+ const l = linkIn(out)!
+ assert.equal(l.port, 54616)
+ assert.equal(l.state, "abc123")
+ assert.equal(linkIn("https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=https%3A%2F%2Fevil.example%2F&state=x"), undefined, "a link back anywhere but this box is refused")
+ assert.equal(landedQuery("http://127.0.0.1:54616/?state=abc123&code=4/0Ab&scope=email", l), "/?state=abc123&code=4/0Ab&scope=email")
+ assert.throws(() => landedQuery("http://127.0.0.1:54616/?state=other&code=4/0Ab", l), /another sign-in/)
+ assert.throws(() => landedQuery("http://127.0.0.1:9999/?state=abc123&code=4/0Ab", l), /isn't the page/)
+ assert.throws(() => landedQuery("http://127.0.0.1:54616/?state=abc123", l), /no code/)
+ assert.throws(() => landedQuery("http://127.0.0.1:54616/?error=access_denied&state=abc123", l), /access_denied/)
+ assert.throws(() => landedQuery("4/0Ab-just-a-code", l), /whole address/)
+ const home = mkdtempSync(path.join(os.tmpdir(), "units-gemini-"))
+ mkdirSync(path.join(home, "antigravity-acp"), { recursive: true })
+ writeFileSync(path.join(home, "antigravity-acp", "oauth.json"), '{"refresh_token":"1//x","email":"[email protected]"}')
+ writeFileSync(path.join(home, "antigravity-acp", "settings.json"), '{"theme":"dark"}')
+ const c = packCredential(home)!
+ assert.ok(c.startsWith("agy1:"))
+ assert.deepEqual(Object.keys(JSON.parse(Buffer.from(c.slice(5), "base64").toString())), ["antigravity-acp/oauth.json"], "only the token file goes")
+ const other = mkdtempSync(path.join(os.tmpdir(), "units-gemini-"))
+ unpackCredential(c, other)
+ assert.equal(packCredential(other), c)
+ assert.throws(() => unpackCredential(`agy1:${Buffer.from(JSON.stringify({ "../../etc/x": "y" })).toString("base64")}`, other), /outside its folder/)
+ rmSync(home, { recursive: true, force: true })
+ rmSync(other, { recursive: true, force: true })
+ console.log("ok google-token")
+}