peppa/infra/runner/peppa-agent.mjs
Асель ca57f9543b PEP-17/40: agent sandbox per runner (docker + agent relay) and runner hosts over SSH
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:57:28 +05:00

123 lines
4.3 KiB
JavaScript

// PEP-17: Peppa's side inside the runner container — hooks and the peppa MCP server of the agent
// talk to Peppa only through the agent relay (PEPPA_AGENT_URL, Bearer PEPPA_AGENT_TOKEN).
// No dependencies (node ≥ 18). Usage: peppa-agent hook <event> [args…] | peppa-agent mcp
// (wrappers peppa-hook / peppa-mcp). A hook never breaks the agent: always exits 0.
import { readFileSync, statSync, openSync, readSync, closeSync } from "node:fs";
import { createInterface } from "node:readline";
const URL_BASE = (process.env.PEPPA_AGENT_URL || "").replace(/\/$/, "");
const TOKEN = process.env.PEPPA_AGENT_TOKEN || "";
const TRANSCRIPT_EVENTS = new Set(["stop", "stop-failure", "session-end"]);
const TRANSCRIPT_MAX = 8 * 1024 * 1024;
const HOOK_DEADLINE_MS = 15 * 60_000;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const headers = (extra = {}) => ({ Authorization: `Bearer ${TOKEN}`, ...extra });
function readStdin() {
try {
return readFileSync(0, "utf8");
} catch {
return "";
}
}
/** Last TRANSCRIPT_MAX bytes of the transcript, from the first full line. */
function transcriptTail(path) {
try {
const size = statSync(path).size;
const len = Math.min(size, TRANSCRIPT_MAX);
const buf = Buffer.alloc(len);
const fd = openSync(path, "r");
readSync(fd, buf, 0, len, size - len);
closeSync(fd);
let text = buf.toString("utf8");
if (len < size) text = text.slice(text.indexOf("\n") + 1);
return text;
} catch {
return undefined;
}
}
async function post(path, body, extraHeaders) {
return fetch(`${URL_BASE}${path}`, { method: "POST", headers: headers({ "Content-Type": "application/json", ...extraHeaders }), body: JSON.stringify(body) });
}
async function hook(event, args) {
const stdin = readStdin();
if (!URL_BASE || !TOKEN || !event) return "";
let transcript;
if (TRANSCRIPT_EVENTS.has(event)) {
try {
const p = JSON.parse(stdin).transcript_path;
if (p) transcript = transcriptTail(p);
} catch {}
}
const deadline = Date.now() + HOOK_DEADLINE_MS;
let body = { event, args, stdin, transcript };
let failures = 0;
while (Date.now() < deadline) {
try {
const res = await post("/api/agent/hook", body);
if (res.status === 401 || res.status === 404 || res.status === 400) return "";
if (!res.ok) throw new Error(`relay ${res.status}`);
const r = await res.json();
if (r.wait && r.rid) {
body = { rid: r.rid };
failures = 0;
continue;
}
return typeof r.stdout === "string" ? r.stdout : "";
} catch {
if (++failures > 5) return "";
await sleep(1000 * failures);
}
}
return "";
}
/** stdio MCP ↔ the relay's Streamable HTTP endpoint (stateless, JSON responses). */
async function mcp() {
const out = (msg) => process.stdout.write(`${JSON.stringify(msg)}\n`);
let chain = Promise.resolve();
const rl = createInterface({ input: process.stdin });
rl.on("line", (line) => {
if (!line.trim()) return;
chain = chain.then(async () => {
let msg;
try {
msg = JSON.parse(line);
} catch {
return;
}
const id = Array.isArray(msg) ? undefined : msg.id;
try {
const res = await post("/api/agent/mcp", msg, { Accept: "application/json, text/event-stream" });
const text = await res.text();
if (res.status === 202 || !text.trim()) return;
if ((res.headers.get("content-type") || "").includes("text/event-stream")) {
for (const l of text.split("\n")) if (l.startsWith("data:")) out(JSON.parse(l.slice(5)));
return;
}
const r = JSON.parse(text);
if (!res.ok && id !== undefined && !r.jsonrpc) throw new Error(r.error || `relay ${res.status}`);
for (const m of Array.isArray(r) ? r : [r]) out(m);
} catch (e) {
if (id !== undefined) out({ jsonrpc: "2.0", id, error: { code: -32603, message: `Peppa relay: ${e.message}` } });
}
});
});
rl.on("close", () => chain.then(() => process.exit(0)));
}
const [mode, ...rest] = process.argv.slice(2);
if (mode === "hook") {
const stdout = await hook(rest[0], rest.slice(1));
process.stdout.write(stdout, () => process.exit(0));
} else if (mode === "mcp") {
await mcp();
} else {
process.stderr.write("usage: peppa-agent hook <event> [args…] | peppa-agent mcp\n");
process.exit(2);
}