Files
shaneandshinyobjectz 06a48730d1 A box says a Claude agent's turn has ended from its Stop hook (#302)
The hook is written into the socket's own settings and touches a file the box watches; as with a transcript's end, it's said only when nothing the agent started still runs.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 21:53:29 -08:00

182 lines
11 KiB
TypeScript

// raea cloud's pure parts, checked without a container: node test/units.ts
// (gpu.ts reads vulkaninfo's summary and picks the device; offload.ts plans which project a render sends and how its
// paths read on the worker)
import assert from "node:assert/strict"
import { execSync } from "node:child_process"
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { parseSummary, pick } from "../server/gpu.ts"
import { plan, projectRoot } from "../server/offload.ts"
import { shellEnv } from "../server/shell-os.ts"
import { claudeStopHook, jobsOf, lastLine, markedEnd, newestTranscript, turnEndOf, watchEnd, watchTurnEnd } from "../server/turn-end.ts"
import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
const L4 = `Devices:
========
GPU0:
apiVersion = 1.3.289
driverVersion = 580.95.5.0
vendorID = 0x10de
deviceID = 0x27b8
deviceType = PHYSICAL_DEVICE_TYPE_DISCRETE_GPU
deviceName = NVIDIA L4
driverID = DRIVER_ID_NVIDIA_PROPRIETARY
driverName = NVIDIA
driverInfo = 580.95.05
GPU1:
apiVersion = 1.4.305
vendorID = 0x10005
deviceType = PHYSICAL_DEVICE_TYPE_CPU
deviceName = llvmpipe (LLVM 19.1.7, 256 bits)
driverName = llvmpipe
driverInfo = Mesa 25.0.7-2 (LLVM 19.1.7)
`
const gpus = parseSummary(L4)
assert.equal(gpus.length, 2)
assert.deepEqual(gpus[0], { name: "NVIDIA L4", type: "discrete", driver: "NVIDIA 580.95.05", vendor: "0x10de" })
assert.equal(gpus[1].type, "cpu")
assert.deepEqual(pick(gpus), { renders: "gpu", name: "NVIDIA L4" })
assert.deepEqual(pick([gpus[1]]), { renders: "cpu", name: "llvmpipe (LLVM 19.1.7, 256 bits)" })
assert.deepEqual(pick([]), { renders: "cpu", name: "llvmpipe" })
const root = mkdtempSync(path.join(os.tmpdir(), "raea-units-"))
try {
const proj = path.join(root, "work", "card")
mkdirSync(path.join(proj, "scenes"), { recursive: true })
writeFileSync(path.join(proj, "package.json"), "{}")
writeFileSync(path.join(proj, "scenes", "edit.tsx"), "")
writeFileSync(path.join(proj, "words.json"), "[]")
writeFileSync(path.join(root, "work", "elsewhere.json"), "[]")
const work = path.join(root, "work")
// the composition's project is the nearest folder above it with a project's files
assert.equal(projectRoot("card/scenes/edit.tsx", work, root), proj)
// from the workspace root: paths made relative to the project, the flags' values left alone
assert.deepEqual(plan(["render", "card/scenes/edit.tsx", "-o", "card/out/x.mp4", "--frames", "30"], work), {
root: proj,
args: ["render", "scenes/edit.tsx", "-o", "out/x.mp4", "--frames", "30"],
moves: [],
})
// an output outside the project is written at its top as .raea-cloud-out-N-NAME (no folder to make) and moved after
const p = plan(["render", "scenes/edit.tsx", "-o", "/tmp/x.mp4", "--words", "words.json"], proj)
assert.ok(typeof p !== "string")
assert.deepEqual(p.args, ["render", "scenes/edit.tsx", "-o", ".raea-cloud-out-0-x.mp4", "--words", "words.json"])
assert.deepEqual(p.moves, [{ from: ".raea-cloud-out-0-x.mp4", to: "/tmp/x.mp4" }])
// an input outside the project can't go
assert.match(plan(["render", "scenes/edit.tsx", "-o", "x.mp4", "--words", "../elsewhere.json"], proj) as string, /outside the project/)
// no composition: nothing to send
assert.match(plan(["render", "--help"], proj) as string, /names no composition/)
// RAEA_CLOUD_GPU_ROOT widens what's sent
assert.equal((plan(["render", "card/scenes/edit.tsx", "-o", "x.mp4", "--words", "elsewhere.json"], work, ".") as { root: string }).root, work)
} finally {
rmSync(root, { recursive: true, force: true })
}
// the box's shell on Windows: its own folder first on PATH, whatever case Windows gave the name; untouched elsewhere
assert.deepEqual(shellEnv({ Path: "C:\\w" }, true, "C:\\g\\usr\\bin\\sh.exe"), { Path: "C:\\g\\usr\\bin;C:\\w" })
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")
}
{
// a turn's end in Antigravity's transcript: a finished model step that called no tool (turn-end.ts)
const done = { step_index: 1716, source: "MODEL", type: "PLANNER_RESPONSE", status: "DONE", created_at: "2026-12-02T03:34:18Z", content: "All six cuts are delivered." }
assert.deepEqual(turnEndOf(JSON.stringify(done)), { step: 1716, at: Date.parse("2026-12-02T03:34:18Z") })
assert.equal(turnEndOf(JSON.stringify({ ...done, tool_calls: [{ name: "run_command" }] })), null)
assert.equal(turnEndOf(JSON.stringify({ ...done, status: "RUNNING" })), null)
assert.equal(turnEndOf(JSON.stringify({ ...done, type: "RUN_COMMAND" })), null)
assert.equal(turnEndOf("not json"), null)
const home = mkdtempSync(path.join(os.tmpdir(), "raea-turn-end-"))
const logs = path.join(home, "antigravity-acp", "brain", "s1", ".system_generated", "logs")
mkdirSync(logs, { recursive: true })
const file = path.join(logs, "transcript.jsonl")
const now = Date.now()
const line = (o: object) => JSON.stringify(o) + "\n"
writeFileSync(file, line({ ...done, step_index: 1, created_at: new Date(now - 60_000).toISOString() }))
assert.equal(newestTranscript(home)?.file, file)
assert.equal(JSON.parse(lastLine(file)).step_index, 1)
// an end from before the agent was last told anything isn't this turn's; one after it is said once
const said: string[] = []
let busy = true
const stop = watchTurnEnd(home, () => now, (by) => said.push(by), () => busy, 10)
await new Promise((ok) => setTimeout(ok, 60))
assert.deepEqual(said, [])
writeFileSync(file, line({ ...done, step_index: 2, tool_calls: [{ name: "x" }], created_at: new Date(now + 1000).toISOString() }) + line({ ...done, step_index: 3, created_at: new Date(now + 2000).toISOString() }))
// the step ended, but a job the agent started still runs: it's waiting, not done
await new Promise((ok) => setTimeout(ok, 80))
assert.deepEqual(said, [])
busy = false
await new Promise((ok) => setTimeout(ok, 80))
stop()
assert.deepEqual(said, ["its transcript, and nothing of its own running"])
// an agent's own jobs, from a made-up /proc: its session's and its children's, not its own programs or raea cloud's
const proc = path.join(home, "proc")
const put = (pid: number, ppid: number, sid: number, exe: string, cmd: string, cwd = "/") => {
mkdirSync(path.join(proc, String(pid)), { recursive: true })
writeFileSync(path.join(proc, String(pid), "stat"), `${pid} (a (odd) name) S ${ppid} ${sid} ${sid} 0 -1`)
writeFileSync(path.join(proc, String(pid), "cmdline"), cmd.replace(/ /g, "\0"))
symlinkSync(exe, path.join(proc, String(pid), "exe"))
symlinkSync(cwd, path.join(proc, String(pid), "cwd"))
}
put(100, 1, 100, "/opt/raea-cloud/agents/antigravity-acp/agy", "agy")
put(101, 100, 100, "/opt/raea-cloud/agents/antigravity-acp/localharness_external", "localharness_external")
put(50, 1, 50, "/usr/bin/node", "node /opt/raea-cloud/server/main.ts")
put(60, 50, 50, "/usr/bin/node", "node .raea-cloud/live/live.cjs", "/srv/work/threads/r1")
assert.deepEqual(jobsOf(100, "/opt/raea-cloud/agents/antigravity-acp", "/srv/work", proc), [])
put(200, 101, 100, "/opt/raea/bin/raea", "raea render edit.tsx")
put(300, 1, 300, "/usr/bin/ffmpeg", "ffmpeg -i a.mp4", "/srv/work/threads/r1/out")
assert.deepEqual(jobsOf(100, "/opt/raea-cloud/agents/antigravity-acp", "/srv/work", proc).sort(), [200, 300])
// Claude's Stop hook: added to the settings there once, what was there kept; its file's touch is the turn's end
const cfg = path.join(home, "claude")
mkdirSync(cfg, { recursive: true })
writeFileSync(path.join(cfg, "settings.json"), JSON.stringify({ model: "opus", hooks: { Stop: [{ hooks: [{ type: "command", command: "true" }] }] } }))
const mark = claudeStopHook(cfg)
claudeStopHook(cfg)
const set = JSON.parse(readFileSync(path.join(cfg, "settings.json"), "utf8"))
assert.equal(set.model, "opus")
assert.deepEqual(set.hooks.Stop.map((g: any) => g.hooks[0].command), ["true", `touch '${mark}'`])
assert.equal(markedEnd(mark), null)
const heard: string[] = []
const stop2 = watchEnd(() => markedEnd(mark), "its Stop hook", () => Date.now() - 500, (by) => heard.push(by), () => false, 10)
await new Promise((ok) => setTimeout(ok, 40))
assert.deepEqual(heard, [])
execSync(set.hooks.Stop[1].hooks[0].command)
await new Promise((ok) => setTimeout(ok, 80))
stop2()
assert.deepEqual(heard, ["its Stop hook, and nothing of its own running"])
rmSync(home, { recursive: true, force: true })
console.log("ok turn-end")
}