AI Engineering Workspace
PartialChat, files, terminal and preview in one place. Chat sessions run on a durable Postgres-backed queue (chat only: no tools or shell). Live models need an API key; the terminal is unavailable.
Project files
read-onlyagent/zoo-cloud-agent.mjs
1#!/usr/bin/env node2// Zloud Agent 0.2.0 — outbound-only connector. Zero dependencies (Node >= 18).3// The agent itself opens NO listening port. It accepts only fixed job kinds (echo, collect-info, app.deploy/stop/start/restart/remove/activate); there is no arbitrary-shell job.4// Deployed applications run as detached processes of the agent's own unprivileged user and keep running if the agent stops or the control plane is unreachable.5// enroll --url <https://host[:port]> --token <zce_...> [--pin <sha256 fingerprint>]6// run [--once] heartbeat loop status verify --file F --sig S --pubkey P7import https from "node:https"; import tls from "node:tls"; import net from "node:net"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import crypto from "node:crypto";8const VERSION = "0.3.1"; const HOME = process.env.ZOO_AGENT_HOME || path.join(os.homedir(), ".config/zoo-cloud-agent"); const CFG = path.join(HOME, "node.json");9const arg = (n, d) => { const i = process.argv.indexOf("--" + n); return i > 0 ? process.argv[i + 1] : d; };10const normFp = s => String(s).replace(/^sha256:/i, "").replace(/:/g, "").toUpperCase();11// With --pin the TLS handshake is completed FIRST (self-signed certificates fail normal verification, so Node would skip checkServerIdentity),12// the certificate's SHA-256 fingerprint is compared, and only then is that already-verified socket used for the HTTP request. A mismatch aborts13// before a single byte of the request (and therefore the token) is sent.14function pinnedSocket(u, pin) {15 return new Promise((resolve, reject) => {16 const s = tls.connect({ host: u.hostname, port: Number(u.port || 443), servername: net.isIP(u.hostname) ? undefined : u.hostname, rejectUnauthorized: false });17 s.setTimeout(15000, () => s.destroy(new Error("timeout"))); s.once("error", reject);18 s.once("secureConnect", () => {19 const pc = s.getPeerCertificate(); const caOk = s.authorized && !tls.checkServerIdentity(u.hostname, pc); // a pin ADDS trust for a self-signed endpoint; a certificate that already passes normal CA + hostname verification (e.g. after migrating to the trusted domain) is accepted too20 if (!caOk && normFp(pc.fingerprint256 || "") !== normFp(pin)) { s.destroy(); return reject(new Error("TLS pin mismatch: server certificate fingerprint differs from --pin")); }21 s.setTimeout(0); s.removeListener("error", reject); resolve(s);22 });23 });24}25async function call(base, pathname, body, { pin, auth } = {}) {26 const u = new URL(pathname, base); if (u.protocol !== "https:") throw new Error("refusing non-HTTPS gateway URL");27 const data = JSON.stringify(body ?? {}); const opts = { method: "POST", hostname: u.hostname, port: u.port || 443, path: u.pathname, headers: { "content-type": "application/json", "content-length": Buffer.byteLength(data), ...(auth ? { authorization: `Bearer ${auth}` } : {}) }, timeout: 15000 };28 if (pin) { const sock = await pinnedSocket(u, pin); const agent = new https.Agent({ keepAlive: false }); agent.createConnection = () => sock; opts.agent = agent; }29 return new Promise((resolve, reject) => {30 const r = https.request(opts, res => { let s = ""; res.on("data", c => s += c); res.on("end", () => { let j = {}; try { j = JSON.parse(s); } catch {} res.statusCode >= 200 && res.statusCode < 300 ? resolve(j) : reject(Object.assign(new Error(j.error || `HTTP ${res.statusCode}`), { status: res.statusCode })); }); });31 r.on("error", reject); r.on("timeout", () => r.destroy(new Error("timeout"))); r.end(data);32 });33}34const load = () => JSON.parse(fs.readFileSync(CFG, "utf8")); const save = c => { fs.mkdirSync(HOME, { recursive: true, mode: 0o700 }); fs.writeFileSync(CFG, JSON.stringify(c, null, 2), { mode: 0o600 }); };35const metrics = () => ({ load1: os.loadavg()[0], memFreeMb: Math.round(os.freemem() / 1048576), memTotalMb: Math.round(os.totalmem() / 1048576), uptimeS: Math.round(os.uptime()), caps: caps() });36// ---- application runtime (0.2.0). Only these job kinds exist; no arbitrary shell is accepted from the server. Everything runs as the agent's own unprivileged user.37import { spawn, spawnSync } from "node:child_process"; import http from "node:http";38const APPS = path.join(HOME, "apps"); const ID_OK = /^app_[0-9a-f]{8,32}$/;39const has = (c, a = ["--version"]) => { try { return spawnSync(c, a, { timeout: 4000 }).status === 0; } catch { return false; } };40const CADDY = process.env.ZOO_CADDY || "caddy"; const ADMIN = process.env.ZOO_CADDY_ADMIN || "127.0.0.1:2019";41const caps = () => ({ node: process.version, git: has("git"), npm: has("npm"), docker: has("docker"), caddy: has(CADDY, ["version"]) });42const appDir = id => { if (!ID_OK.test(String(id))) throw new Error("bad deployment id"); return path.join(APPS, id); };43const rjson = (f, d = null) => { try { return JSON.parse(fs.readFileSync(f, "utf8")); } catch { return d; } };44const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } };45const SERVER = `const http=require("http"),fs=require("fs"),path=require("path");const root=process.cwd()+"/site";const T={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".svg":"image/svg+xml",".txt":"text/plain"};46http.createServer((q,s)=>{let p=decodeURIComponent(new URL(q.url,"http://x").pathname);if(p.endsWith("/"))p+="index.html";const f=path.join(root,path.normalize(p));if(!f.startsWith(root)){s.writeHead(403);return s.end("forbidden")}47fs.readFile(f,(e,d)=>{if(e){s.writeHead(404);return s.end("not found")}s.writeHead(200,{"content-type":T[path.extname(f)]||"application/octet-stream","x-content-type-options":"nosniff"});s.end(d)})}).listen(Number(process.env.PORT),"0.0.0.0");`;48const esc = s => String(s).replace(/[&<>"]/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """ }[c]));49function stopApp(id) { const d = appDir(id), st = rjson(path.join(d, "state.json"), {}); if (st.pid && alive(st.pid)) { try { process.kill(-st.pid, "SIGTERM"); } catch { try { process.kill(st.pid, "SIGTERM"); } catch {} } for (let i = 0; i < 20 && alive(st.pid); i++) spawnSync("sleep", ["0.2"]); if (alive(st.pid)) { try { process.kill(-st.pid, "SIGKILL"); } catch {} } } fs.writeFileSync(path.join(d, "state.json"), JSON.stringify({ ...st, running: false, pid: 0 })); }50function startApp(id, rel) { // detached: the workload survives agent restarts and disconnection51 const d = appDir(id), rd = path.join(d, "releases", String(rel)), meta = rjson(path.join(rd, "release.json")); if (!meta) throw new Error(`release ${rel} not present on this server`);52 const out = fs.openSync(path.join(d, "app.log"), "a"); try { if (fs.statSync(path.join(d, "app.log")).size > 5_000_000) fs.truncateSync(path.join(d, "app.log"), 0); } catch {}53 const env = { PATH: process.env.PATH, HOME: process.env.HOME, NODE_ENV: "production", NODE_OPTIONS: `--max-old-space-size=${meta.kind === "git-node" ? 512 : 256}`, ...(meta.env ?? {}), PORT: String(meta.port) }; // soft memory cap (V8 heap) + 5 MB log cap; NOT a cgroup limit54 const [cmd, args, cwd] = meta.kind === "git-node" ? ["npm", ["start"], path.join(rd, "src")] : [process.execPath, [meta.kind === "static" ? "serve.cjs" : "server.js"], rd];55 const ch = spawn(cmd, args, { cwd, env, detached: true, stdio: ["ignore", out, out] }); ch.unref(); fs.writeFileSync(path.join(d, "state.json"), JSON.stringify({ release: rel, pid: ch.pid, port: meta.port, running: true, started: Date.now() }));56}57const probe = (port, ms) => new Promise(res => { const end = Date.now() + ms; const go = () => { const r = http.get({ host: "127.0.0.1", port, path: "/", timeout: 2000 }, x => { x.resume(); x.statusCode < 500 ? res(true) : retry(); }); r.on("error", retry); r.on("timeout", () => { r.destroy(); retry(); }); }; const retry = () => Date.now() < end ? setTimeout(go, 500) : res(false); go(); });58function prepare(id, p) { // writes a release directory from the validated payload59 const rd = path.join(appDir(id), "releases", String(p.release)); fs.mkdirSync(rd, { recursive: true, mode: 0o700 }); const env = p.params?.env ?? {}; const log = [];60 if (p.kind === "static") { fs.mkdirSync(path.join(rd, "site")); fs.writeFileSync(path.join(rd, "site/index.html"), `<!doctype html><meta charset="utf-8"><title>${esc(p.params.title ?? "")}</title>${p.params.html ?? ""}`); fs.writeFileSync(path.join(rd, "serve.cjs"), SERVER); }61 else if (p.kind === "node") fs.writeFileSync(path.join(rd, "server.js"), String(p.params.code ?? ""));62 else if (p.kind === "git-node") {63 const r = spawnSync("git", ["clone", "--depth", "1", "--branch", p.params.ref || "main", "--", p.params.repo, path.join(rd, "src")], { encoding: "utf8", timeout: 180000, env: { PATH: process.env.PATH, HOME: process.env.HOME, GIT_TERMINAL_PROMPT: "0" } }); log.push((r.stdout ?? "") + (r.stderr ?? "")); if (r.status !== 0) throw Object.assign(new Error("git clone failed"), { log });64 const n = spawnSync("npm", ["install", "--no-audit", "--no-fund", "--omit=dev"], { cwd: path.join(rd, "src"), encoding: "utf8", timeout: 600000 }); log.push((n.stdout ?? "") + (n.stderr ?? "")); if (n.status !== 0) throw Object.assign(new Error("npm install failed"), { log });65 } else throw new Error("unsupported application kind");66 fs.writeFileSync(path.join(rd, "release.json"), JSON.stringify({ kind: p.kind, port: p.port, env }), { mode: 0o600 }); return log.join("");67}68async function runApp(c, j) { // returns the result object; streams log text to the control plane as it goes69 const p = j.payload ?? {}; const id = p.deploymentId; const d = appDir(id); fs.mkdirSync(d, { recursive: true, mode: 0o700 });70 const secrets = Object.values(p.params?.env ?? {}).map(String).filter(v => v.length >= 4); const say = async t => { for (const s of secrets) t = t.split(s).join("***"); try { await call(c.url, `/gateway/api/jobs/${j.id}`, { log: t + "\n" }, { pin: c.pin, auth: c.credential }); } catch {} };71 const cur = () => rjson(path.join(d, "state.json"), {}); const prevRel = cur().running ? cur().release : (cur().release ?? 0);72 const attempt = async (rel, label) => { startApp(id, rel); await say(`${label}: starting release ${rel} on port ${p.port}`); const mine = cur().pid; let ok = await probe(p.port, p.kind === "git-node" ? 30000 : 10000); if (ok && !(mine && alive(mine))) { ok = false; await say("the application process exited (port already in use by another program?)"); } await say(`health check ${ok ? "passed" : "FAILED"}`); if (!ok) { await say("--- application log (tail) ---\n" + fs.readFileSync(path.join(d, "app.log"), "utf8").slice(-1500)); stopApp(id); } return ok; };73 try {74 if (j.kind === "app.deploy") {75 await say(`deploying ${p.name} (${p.kind}) release ${p.release}`); try { const l = prepare(id, p); if (l) await say(l.slice(-3000)); } catch (e) { if (e.log) await say(e.log.join("").slice(-3000)); fs.rmSync(path.join(d, "releases", String(p.release)), { recursive: true, force: true }); await say(`build failed: ${e.message}`); return { ok: false, health: "failed", error: e.message }; }76 stopApp(id); if (await attempt(p.release, "deploy")) { for (const r of fs.readdirSync(path.join(d, "releases")).map(Number).sort((a, b) => b - a).slice(3)) fs.rmSync(path.join(d, "releases", String(r)), { recursive: true, force: true }); await say("release is live"); return { ok: true, health: "ok", release: p.release }; }77 if (prevRel && fs.existsSync(path.join(d, "releases", String(prevRel)))) { await say(`rolling back to release ${prevRel}`); if (await attempt(prevRel, "rollback")) return { ok: false, health: "failed", revertedTo: prevRel, error: "new release failed its health check; previous release restored" }; }78 return { ok: false, health: "failed", error: "health check failed" };79 }80 if (j.kind === "app.activate") { stopApp(id); await say(`activating release ${p.release}`); if (await attempt(p.release, "activate")) return { ok: true, health: "ok", release: p.release }; if (prevRel && prevRel !== p.release && await attempt(prevRel, "revert")) return { ok: false, health: "failed", revertedTo: prevRel, error: "target release unhealthy; previous restored" }; return { ok: false, health: "failed" }; }81 if (j.kind === "app.stop") { stopApp(id); await say("stopped"); return { ok: true }; }82 if (j.kind === "app.start" || j.kind === "app.restart") { stopApp(id); const rel = cur().release ?? p.release; const ok = await attempt(rel, j.kind.slice(4)); return { ok, health: ok ? "ok" : "failed" }; }83 if (j.kind === "app.remove") { stopApp(id); fs.rmSync(d, { recursive: true, force: true }); await say("removed (files and process)"); return { ok: true }; }84 } catch (e) { await say(`error: ${e.message}`); return { ok: false, error: String(e.message).slice(0, 200) }; }85 return { error: "unsupported job kind" };86}8788// ---- reverse proxy (0.3.0): the agent renders and applies a Caddyfile for hostnames the control plane has VERIFIED. Caddy itself is installed/started by the server owner89// (it needs ports 80/443); the agent only writes its own config file, validates it, reloads, health-checks, and restores the previous config on any failure.90const PROXY = path.join(HOME, "proxy"); const HOST_OK = /^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;91function renderCaddyfile(sites) { // pure; mirrored by app/src/lib/proxy-core.mjs and compared in QA92 const out = [`{\n\tadmin ${ADMIN}\n}\n`]; for (const s of sites) {93 if (!HOST_OK.test(s.hostname)) throw new Error(`invalid hostname ${String(s.hostname).slice(0, 60)}`);94 if (s.redirectTo) { if (!HOST_OK.test(s.redirectTo)) throw new Error("invalid redirect target"); out.push(`${s.hostname} {\n\tredir https://${s.redirectTo}{uri} permanent\n}\n`); continue; }95 if (!Number.isInteger(s.port) || s.port < 20000 || s.port > 29999) throw new Error("upstream port must be a managed application port (20000-29999)");96 out.push(`${s.hostname} {\n\tencode gzip\n\theader X-Content-Type-Options nosniff\n\treverse_proxy 127.0.0.1:${s.port}\n}\n`);97 } return out.join("\n");98}99const run1 = (args, ms = 20000) => spawnSync(CADDY, args, { encoding: "utf8", timeout: ms });100const adminUp = () => new Promise(res => { const r = http.get({ host: ADMIN.split(":")[0], port: Number(ADMIN.split(":")[1]), path: "/config/", timeout: 2000 }, x => { x.resume(); res(x.statusCode === 200); }); r.on("error", () => res(false)); r.on("timeout", () => { r.destroy(); res(false); }); });101const tlsInfo = (host, port) => new Promise(res => { const s = tls.connect({ host: "127.0.0.1", port, servername: host, timeout: 5000 }, () => { const c = s.getPeerCertificate(); const out = { ok: s.authorized && !!c.valid_to, validTo: c.valid_to ? new Date(c.valid_to).toISOString() : null, reason: s.authorizationError ? String(s.authorizationError) : null }; s.end(); res(out); }); s.on("error", e => res({ ok: false, reason: String(e.code || e.message) })); s.on("timeout", () => { s.destroy(); res({ ok: false, reason: "timeout" }); }); });102async function runProxy(c, j) {103 const say = async t => { try { await call(c.url, `/gateway/api/jobs/${j.id}`, { log: t + "\n" }, { pin: c.pin, auth: c.credential }); } catch {} };104 const sites = Array.isArray(j.payload?.sites) ? j.payload.sites.slice(0, 100) : []; fs.mkdirSync(PROXY, { recursive: true, mode: 0o700 });105 for (const s of sites) if (!s.redirectTo) { const st = (() => { try { return appStates().find(a => a.id === s.deploymentId); } catch { return null; } })(); const meta = st ? rjson(path.join(APPS, st.id, "state.json"), {}) : {}; if (!st || meta.port !== s.port) { await say(`refused: ${s.hostname} points at port ${s.port}, which is not a managed application on this server`); return { ok: false, error: "upstream is not a managed application" }; } }106 let text; try { text = renderCaddyfile(sites); } catch (e) { await say("refused: " + e.message); return { ok: false, error: e.message }; }107 if (!has(CADDY, ["version"])) { await say("Caddy is not installed on this server (owner action: install Caddy, see the dashboard instructions)"); return { ok: false, error: "proxy not installed" }; }108 const cur = path.join(PROXY, "Caddyfile"), cand = path.join(PROXY, "Caddyfile.candidate"), prev = path.join(PROXY, "Caddyfile.prev"); fs.writeFileSync(cand, text, { mode: 0o600 });109 const v = run1(["validate", "--config", cand, "--adapter", "caddyfile"]); if (v.status !== 0) { await say("configuration REJECTED by validation; nothing was changed\n" + String(v.stderr).slice(-500)); return { ok: false, error: "validation failed" }; }110 await say("configuration valid"); if (!(await adminUp())) { await say("Caddy is installed but not running (owner action: start the caddy service)"); return { ok: false, error: "proxy not running" }; }111 if (fs.existsSync(cur)) fs.copyFileSync(cur, prev); fs.renameSync(cand, cur); const rl = run1(["reload", "--config", cur, "--adapter", "caddyfile", "--address", ADMIN]);112 const revert = async why => { if (fs.existsSync(prev)) { fs.copyFileSync(prev, cur); run1(["reload", "--config", cur, "--adapter", "caddyfile", "--address", ADMIN]); await say(`${why}; previous configuration restored`); } else await say(`${why}; no previous configuration to restore`); };113 if (rl.status !== 0) { await revert("reload failed: " + String(rl.stderr).slice(-300)); return { ok: false, error: "reload failed", reverted: true }; }114 await say("reloaded safely"); const httpsPort = Number(process.env.ZOO_PROXY_HTTPS_PORT || 443); const sitesOut = [];115 for (const s of sites) { if (s.redirectTo) { sitesOut.push({ hostname: s.hostname }); continue; } const upstream = await probe(s.port, 5000); if (!upstream) { await revert(`health check of ${s.hostname} -> :${s.port} failed`); return { ok: false, error: "upstream health check failed", reverted: true }; } const t = await tlsInfo(s.hostname, httpsPort); sitesOut.push({ hostname: s.hostname, upstream: true, tls: t.ok ? { ok: true, validTo: t.validTo } : { ok: false, reason: t.reason } }); await say(`${s.hostname}: upstream healthy; certificate ${t.ok ? "valid until " + t.validTo : "not yet issued (" + t.reason + ")"}`); }116 return { ok: true, sites: sitesOut };117}118// signed self-upgrade driven by the control plane: the package is fetched from the gateway origin and verified against the public key stored at ENROLLMENT (obtained out-of-band); nothing unsigned is ever installed119function getRaw(c, pathname) { const u = new URL(pathname, c.url); return new Promise(async (resolve, reject) => { const opts = { method: "GET", hostname: u.hostname, port: u.port || 443, path: u.pathname, timeout: 20000 }; if (c.pin) { try { const sock = await pinnedSocket(u, c.pin); const agent = new https.Agent({ keepAlive: false }); agent.createConnection = () => sock; opts.agent = agent; } catch (e) { return reject(e); } } https.get(opts, res => { const ch = []; res.on("data", x => ch.push(x)); res.on("end", () => res.statusCode === 200 ? resolve(Buffer.concat(ch)) : reject(new Error(`HTTP ${res.statusCode}`))); }).on("error", reject); }); }120async function upgradeSelf(c) {121 if (!c.pubkey) return { ok: false, error: "no signing public key stored at enrollment (re-enroll with --pubkey)" };122 try { const man = JSON.parse((await getRaw(c, "/packages/manifest.json")).toString()); const pk = man.packages?.[0]; if (!pk || !/^[\w.-]+$/.test(pk.file) || !/^[\w.-]+$/.test(pk.signature)) return { ok: false, error: "bad manifest" };123 const buf = await getRaw(c, "/packages/" + pk.file), sig = (await getRaw(c, "/packages/" + pk.signature)).toString().trim(); if (crypto.createHash("sha256").update(buf).digest("hex") !== pk.sha256) return { ok: false, error: "sha256 mismatch" };124 if (!crypto.verify(null, buf, crypto.createPublicKey({ key: Buffer.from(c.pubkey, "base64"), format: "der", type: "spki" }), Buffer.from(sig, "base64"))) return { ok: false, error: "signature INVALID; not upgrading" };125 const nv = /const VERSION = "([^"]+)"/.exec(buf.toString())?.[1]; const cmp = (a, b) => { const x = a.split(".").map(Number), y = b.split(".").map(Number); for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) - (y[i] ?? 0); return 0; };126 if (!nv || cmp(nv, VERSION) <= 0) return { ok: true, upToDate: true, version: VERSION }; const self = process.argv[1]; fs.copyFileSync(self, self + ".prev"); fs.writeFileSync(self + ".new", buf, { mode: 0o755 }); fs.renameSync(self + ".new", self); setTimeout(() => process.exit(0), 1500); return { ok: true, from: VERSION, to: nv, restart: "agent exits now; its supervisor (systemd/cron) starts the new version" };127 } catch (e) { return { ok: false, error: String(e.message).slice(0, 150) }; }128}129const appStates = () => { try { return fs.readdirSync(APPS).filter(n => ID_OK.test(n)).map(n => { const s = rjson(path.join(APPS, n, "state.json"), {}); return { id: n, release: s.release ?? 0, running: !!(s.running && s.pid && alive(s.pid)) }; }); } catch { return []; } };130131const cmd = process.argv[2];132if (cmd === "enroll") {133 const url = arg("url"), token = arg("token"), pin = arg("pin"), publicHost = arg("public-host"), pubkey = arg("pubkey"); if (!url || !token) { console.error("usage: enroll --url <https://host> --token <token> [--pin <fingerprint>]"); process.exit(2); }134 try { const r = await call(url, "/gateway/api/enroll", { token, hostname: os.hostname(), os: `${os.platform()} ${os.release()} ${os.arch()}`, agentVersion: VERSION, publicHost }, { pin }); save({ url: r.gatewayUrl && r.gatewayUrl.startsWith("https://") ? r.gatewayUrl : url, nodeId: r.nodeId, credential: r.credential, credentialAt: Date.now(), pin: pin ?? null, pubkey: pubkey ?? null }); console.log(`enrolled as ${r.nodeId}`); }135 catch (e) { console.error("enrollment failed:", e.message); process.exit(1); }136} else if (cmd === "run" || cmd === "status") {137 let c; try { c = load(); } catch { console.error("not enrolled (run: enroll ...)"); process.exit(2); }138 if (cmd === "status") { console.log(JSON.stringify({ nodeId: c.nodeId, url: c.url, pinned: !!c.pin, version: VERSION }, null, 2)); process.exit(0); }139 const once = process.argv.includes("--once"); let stop = false; for (const s of ["SIGINT", "SIGTERM"]) process.on(s, () => { stop = true; });140 do { let more = false;141 try {142 const r = await call(c.url, "/gateway/api/heartbeat", { agentVersion: VERSION, metrics: metrics(), apps: appStates() }, { pin: c.pin, auth: c.credential });143 // domain migration: adopt the gateway URL the (already authenticated, TLS-verified) server announces; the pin, if any, is kept144 if (r.gatewayUrl && r.gatewayUrl.startsWith("https://") && r.gatewayUrl !== c.url) { c.url = r.gatewayUrl; save(c); }145 more = (r.jobs ?? []).length > 0; for (const j of r.jobs ?? []) { const result = j.kind === "echo" ? { echo: String(j.payload?.text ?? "") } : j.kind === "collect-info" ? { hostname: os.hostname(), os: `${os.platform()} ${os.release()}`, cpus: os.cpus().length, ...metrics() } : String(j.kind).startsWith("app.") ? await runApp(c, j) : j.kind === "proxy.apply" ? await runProxy(c, j) : j.kind === "agent.rotate" ? await (async () => { const n = await call(c.url, "/gateway/api/rotate", {}, { pin: c.pin, auth: c.credential }); c.credential = n.credential; c.credentialAt = Date.now(); save(c); return { ok: true }; })() : j.kind === "agent.upgrade" ? await upgradeSelf(c) : { error: "unsupported job kind" }; await call(c.url, `/gateway/api/jobs/${j.id}`, { result }, { pin: c.pin, auth: c.credential }); }146 if (Date.now() - (c.credentialAt ?? 0) > 30 * 86400_000) { const n = await call(c.url, "/gateway/api/rotate", {}, { pin: c.pin, auth: c.credential }); c.credential = n.credential; c.credentialAt = Date.now(); save(c); }147 if (once) console.log("heartbeat ok");148 } catch (e) { console.error("heartbeat failed:", e.message); if (e.status === 403 || e.status === 401) { console.error("credential rejected (node revoked or unknown); stopping"); process.exit(3); } if (once) process.exit(1); }149 if (!once && !more) await new Promise(r => setTimeout(r, 15000));150 } while (!once && !stop);151} else if (cmd === "verify") { // verify a downloaded package: SHA-256 (from manifest) and detached Ed25519 signature against a public key obtained out-of-band152 const file = arg("file"), sig = arg("sig"), pub = arg("pubkey"); const buf = fs.readFileSync(file);153 const ok = crypto.verify(null, buf, crypto.createPublicKey({ key: Buffer.from(pub, "base64"), format: "der", type: "spki" }), Buffer.from(fs.readFileSync(sig, "utf8").trim(), "base64"));154 console.log(`sha256 ${crypto.createHash("sha256").update(buf).digest("hex")}\nsignature ${ok ? "VALID" : "INVALID"}`); process.exit(ok ? 0 : 1);155} else if (cmd === "rotate") { // rotate the node credential now; the old one stops working immediately156 const c = load(); const n = await call(c.url, "/gateway/api/rotate", {}, { pin: c.pin, auth: c.credential }); c.credential = n.credential; c.credentialAt = Date.now(); save(c); console.log("credential rotated");157} else if (cmd === "upgrade") { // verify a new agent file (SHA-256 + Ed25519 against a public key obtained out-of-band) and only then replace this file158 const file = arg("file"), sig = arg("sig"), pub = arg("pubkey"); const buf = fs.readFileSync(file); const ok = crypto.verify(null, buf, crypto.createPublicKey({ key: Buffer.from(pub, "base64"), format: "der", type: "spki" }), Buffer.from(fs.readFileSync(sig, "utf8").trim(), "base64"));159 if (!ok) { console.error("signature INVALID; not upgrading"); process.exit(1); } const nv = /const VERSION = "([^"]+)"/.exec(buf.toString())?.[1]; const cmp = (a, b) => { const x = a.split(".").map(Number), y = b.split(".").map(Number); for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) - (y[i] ?? 0); return 0; };160 if (!nv || cmp(nv, VERSION) <= 0) { console.error(`not newer (have ${VERSION}, offered ${nv})`); process.exit(1); } const self = process.argv[1]; fs.copyFileSync(self, self + ".prev"); fs.writeFileSync(self + ".new", buf, { mode: 0o755 }); fs.renameSync(self + ".new", self); console.log(`upgraded ${VERSION} -> ${nv} (previous kept as ${path.basename(self)}.prev; restart the agent)`);161} else if (cmd === "uninstall") { // revoke this node and delete local credentials; deployed applications are PRESERVED unless --remove-apps162 let c = null; try { c = load(); } catch {} if (c) { try { await call(c.url, "/gateway/api/bye", {}, { pin: c.pin, auth: c.credential }); console.log("node revoked on the control plane"); } catch (e) { console.error("could not reach the control plane (revoke it from the dashboard):", e.message); } }163 if (process.argv.includes("--remove-apps")) { for (const a of appStates()) stopApp(a.id); fs.rmSync(APPS, { recursive: true, force: true }); console.log("applications removed"); } else console.log(`applications preserved in ${APPS} (run again with --remove-apps to delete them)`);164 fs.rmSync(CFG, { force: true }); console.log("local credentials deleted");165} else if (cmd === "proxy-render") { console.log(renderCaddyfile(JSON.parse(fs.readFileSync(arg("sites"), "utf8")))); }166else { console.log(`Zloud Agent ${VERSION}\ncommands: enroll | run [--once] | status | verify | rotate | upgrade | uninstall | proxy-render [--remove-apps]`); }167
Conversation
PartialSign in to start AI sessions.
Task checklist
- Application shell deployed
- Persistent projects
- Agent runtime
- Sandboxed terminal
Execution activity
No agent sessions. Git HEAD fb22adb on master.
Approval requests
None pending.