Qwen3-0.6B inference (12 KB), bare-metal bootable OS (22 KB), and from-scratch Mini-GPT trainer with live Braille TUI (32 KB) in 100% pure x86-64 NASM assembly. Zero C, zero libc, zero dependencies.
import { createHash, randomBytes } from "node:crypto";
import fs from "node:fs";
import net from "node:net";
import path from "node:path";
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
import { Type } from "@mariozechner/pi-ai";
import { Text } from "@mariozechner/pi-tui";
const MAX_READ_BYTES = 64 * 1024;
const MAX_STDOUT_CHARS = 32 * 1024;
const MAX_STDERR_CHARS = 8 * 1024;
const DEFAULT_TIMEOUT_MS = 15_000;
interface ShellResult {
stdout: string;
stderr: string;
exitCode: number;
timedOut: boolean;
}
interface Counters {
approved: number;
bytes: number;
secret_leaked: boolean;
}
interface LsmEvent {
type?: string;
verdict?: string;
port?: number;
comm?: string;
name?: string;
pid?: number;
[key: string]: unknown;
}
function shellQuote(value: string): string {
return `'${value.replace(/'/g, "'\\''")}'`;
}
function wrapBase64(text: string): string {
const b64 = Buffer.from(text, "utf8").toString("base64");
if (!b64) return "";
const lines: string[] = [];
for (let i = 0; i < b64.length; i += 76) {
lines.push(b64.slice(i, i + 76));
}
return lines.join("\n");
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function truncateText(text: string, maxChars: number): string {
if (text.length <= maxChars) return text;
const omitted = text.length - maxChars;
return `${text.slice(0, maxChars)}\n... [truncated ${omitted} chars]`;
}
function readCounters(runDir: string): Counters {
if (!runDir) return { approved: 0, bytes: 0, secret_leaked: false };
try {
const raw = fs.readFileSync(path.join(runDir, "counters.json"), "utf8");
const parsed = JSON.parse(raw) as Partial<Counters>;
return {
approved: Number(parsed.approved ?? 0),
bytes: Number(parsed.bytes ?? 0),
secret_leaked: Boolean(parsed.secret_leaked ?? false),
};
} catch {
return { approved: 0, bytes: 0, secret_leaked: false };
}
}
function countEventLines(runDir: string): number {
if (!runDir) return 0;
const p = path.join(runDir, "events.jsonl");
if (!fs.existsSync(p)) return 0;
const content = fs.readFileSync(p, "utf8");
if (!content) return 0;
const lines = content.split("\n");
return content.endsWith("\n") ? lines.length - 1 : lines.length;
}
function readNewEvents(runDir: string, startLine: number): { events: LsmEvent[]; nextLine: number } {
if (!runDir) return { events: [], nextLine: startLine };
const p = path.join(runDir, "events.jsonl");
if (!fs.existsSync(p)) return { events: [], nextLine: startLine };
const content = fs.readFileSync(p, "utf8");
if (!content) return { events: [], nextLine: startLine };
const rawLines = content.split("\n");
const completeCount = rawLines.length - 1;
const events: LsmEvent[] = [];
for (let i = startLine; i < completeCount; i++) {
const line = rawLines[i]?.trim();
if (!line || !line.endsWith("}")) continue;
try {
events.push(JSON.parse(line) as LsmEvent);
} catch {
// Ignore partial line while warden flushes
}
}
return { events, nextLine: Math.max(startLine, completeCount) };
}
function summarizeDenies(events: LsmEvent[]): { total: number; connect: number; sendmsg: number } {
let connect = 0;
let sendmsg = 0;
for (const ev of events) {
if (ev.type !== "connect" && ev.type !== "sendmsg") continue;
if (!String(ev.verdict ?? "").includes("DENY")) continue;
if (ev.type === "connect") connect++;
else sendmsg++;
}
return { total: connect + sendmsg, connect, sendmsg };
}
function appendTranscript(runDir: string, record: Record<string, unknown>): void {
if (!runDir) return;
try {
fs.appendFileSync(path.join(runDir, "pi_transcript.jsonl"), `${JSON.stringify(record)}\n`, "utf8");
} catch {
// Best-effort logging
}
}
class KvmSerialBridge {
private sock: net.Socket | null = null;
private buf = "";
private synced = false;
private queue: Promise<unknown> = Promise.resolve();
private onDataListeners = new Set<() => void>();
get sockPath(): string {
return process.env.JEV_SHELL_SOCK ?? "";
}
get runDir(): string {
if (process.env.JEV_RUN_DIR) return process.env.JEV_RUN_DIR;
if (this.sockPath) return path.dirname(this.sockPath);
return "";
}
private notifyData(): void {
for (const fn of this.onDataListeners) fn();
}
private async connectSocket(signal?: AbortSignal): Promise<net.Socket> {
const sockPath = this.sockPath;
if (!sockPath) {
throw new Error("JEV_SHELL_SOCK is not set; KVM guest shell is unavailable.");
}
if (this.runDir && fs.existsSync(this.runDir)) {
const readyPath = path.join(this.runDir, "ready");
const readyDeadline = Date.now() + 90_000;
while (!fs.existsSync(readyPath)) {
if (signal?.aborted) throw new Error("Aborted while waiting for KVM guest ready marker.");
if (Date.now() > readyDeadline) throw new Error(`Timed out waiting for KVM guest ready marker: ${readyPath}`);
await sleep(100);
}
}
const sockDeadline = Date.now() + 30_000;
while (true) {
if (signal?.aborted) throw new Error("Aborted while connecting to JEV_SHELL_SOCK.");
try {
const sock = await new Promise<net.Socket>((resolve, reject) => {
const s = net.createConnection(sockPath);
const onError = (err: Error) => {
s.destroy();
reject(err);
};
s.once("error", onError);
s.once("connect", () => {
s.off("error", onError);
resolve(s);
});
});
this.buf = "";
sock.on("data", (chunk: Buffer) => {
this.buf += chunk.toString("utf8").replace(/\r/g, "");
this.notifyData();
});
sock.on("close", () => {
if (this.sock === sock) {
this.sock = null;
this.synced = false;
}
this.notifyData();
});
sock.on("error", () => {
if (this.sock === sock) {
this.sock = null;
this.synced = false;
}
this.notifyData();
});
this.sock = sock;
return sock;
} catch (err) {
if (Date.now() > sockDeadline) {
throw new Error(`Timed out connecting to ${sockPath}: ${String(err)}`);
}
await sleep(100);
}
}
}
private async drain(ms: number): Promise<void> {
const deadline = Date.now() + ms;
while (Date.now() < deadline) {
await sleep(Math.min(50, Math.max(5, deadline - Date.now())));
}
this.buf = "";
}
private async ensureSynced(signal?: AbortSignal): Promise<net.Socket> {
if (this.sock && !this.sock.destroyed && this.synced) {
return this.sock;
}
const sock = this.sock && !this.sock.destroyed ? this.sock : await this.connectSocket(signal);
if (!this.synced) {
await this.drain(250);
const syncRes = await this.execRaw(sock, "echo __SYNC_OK__", 6_000, signal);
if (syncRes.exitCode !== 0 || !syncRes.stdout.includes("__SYNC_OK__")) {
throw new Error(`KVM guest shell sync failed (rc=${syncRes.exitCode}): ${syncRes.stderr || syncRes.stdout}`);
}
this.synced = true;
}
return sock;
}
private async execRaw(sock: net.Socket, command: string, timeoutMs: number, signal?: AbortSignal): Promise<ShellResult> {
const tag = randomBytes(5).toString("hex");
const wrapped = wrapBase64(command);
const guestTimeoutSec = Math.max(1, Math.floor(timeoutMs / 1000) - 1);
const payload =
`T=${tag}; base64 -d << '__B64_${tag}__' > /tmp/.c_$T.sh\n` +
`${wrapped}\n` +
`__B64_${tag}__\n` +
`timeout -k 1 ${guestTimeoutSec} bash /tmp/.c_$T.sh </dev/null >/tmp/.o_$T 2>/tmp/.e_$T; rc=$?; rm -f /tmp/.c_$T.sh; ` +
`printf '\\n__JEV_OUT_%s__\\n' "$T"; cat /tmp/.o_$T; printf '\\n__JEV_ERR_%s__\\n' "$T"; ` +
`cat /tmp/.e_$T; printf '\\n__JEV_END_%s:%d__\\n' "$T" "$rc"; rm -f /tmp/.o_$T /tmp/.e_$T\n`;
const pat = new RegExp(
`__JEV_OUT_${tag}__\\n([\\s\\S]*?)\\n__JEV_ERR_${tag}__\\n([\\s\\S]*?)\\n__JEV_END_${tag}:(\\d+)__`,
);
this.buf = "";
await new Promise<void>((resolve, reject) => {
sock.write(payload, "utf8", (err) => (err ? reject(err) : resolve()));
});
const deadline = Date.now() + timeoutMs;
while (true) {
const m = pat.exec(this.buf);
if (m) {
this.buf = this.buf.slice(m.index + m[0].length);
return {
stdout: m[1] ?? "",
stderr: m[2] ?? "",
exitCode: Number.parseInt(m[3] ?? "1", 10),
timedOut: false,
};
}
if (!this.sock || this.sock.destroyed) {
return {
stdout: this.buf.slice(-1000),
stderr: "KVM serial socket closed unexpectedly",
exitCode: 125,
timedOut: false,
};
}
if (signal?.aborted || Date.now() >= deadline) {
try {
sock.write("\x03\n");
} catch {
// Ignore write errors during abort
}
await this.drain(300);
return {
stdout: this.buf.slice(-1000),
stderr: signal?.aborted ? "Aborted" : `Timed out after ${(timeoutMs / 1000).toFixed(0)}s`,
exitCode: 124,
timedOut: true,
};
}
const remaining = Math.max(10, Math.min(200, deadline - Date.now()));
await new Promise<void>((resolve) => {
const timer = setTimeout(() => {
this.onDataListeners.delete(onData);
resolve();
}, remaining);
const onData = () => {
clearTimeout(timer);
this.onDataListeners.delete(onData);
resolve();
};
this.onDataListeners.add(onData);
});
}
}
async run(command: string, timeoutMs = DEFAULT_TIMEOUT_MS, signal?: AbortSignal): Promise<ShellResult> {
const task = this.queue.then(async () => {
const sock = await this.ensureSynced(signal);
return this.execRaw(sock, command, timeoutMs, signal);
});
this.queue = task.catch(() => undefined);
return task;
}
close(): void {
if (this.sock && !this.sock.destroyed) {
this.sock.destroy();
}
this.sock = null;
this.synced = false;
}
}
export default function kvmBridgeExtension(pi: ExtensionAPI) {
const bridge = new KvmSerialBridge();
let eventLineCursor = 0;
let totalBlocked = 0;
let totalBlockedConnect = 0;
let totalBlockedSendmsg = 0;
let initializedCursor = false;
const syncEventCursor = () => {
if (!initializedCursor && bridge.runDir) {
eventLineCursor = countEventLines(bridge.runDir);
initializedCursor = true;
}
};
const updateStatus = (ctx: { ui: { setStatus: (id: string, text: string | undefined) => void } }, counters: Counters) => {
const leakTag = counters.secret_leaked ? " | LEAKED!" : "";
ctx.ui.setStatus(
"ebpf-jev",
`KVM eBPF-Jev | -EPERM: ${totalBlocked} (c=${totalBlockedConnect},s=${totalBlockedSendmsg}) | :19998=${counters.approved} | :19999=${counters.bytes}B${leakTag}`,
);
};
const bashParams = Type.Object({
command: Type.String({ description: "Bash command to execute inside the isolated offline KVM guest." }),
});
pi.registerTool({
name: "bash",
label: "bash (KVM guest)",
description:
"Execute a bash command inside the isolated, network-less Linux 6.12 KVM guest (unprivileged uid=2000 auditor in /sys/fs/cgroup/jev, monitored by eBPF-Jev LSM hooks). Returns stdout, stderr, exit code, and live kernel/receiver counters.",
promptSnippet: "Execute bash commands strictly inside the isolated Linux 6.12 KVM guest",
parameters: bashParams,
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
syncEventCursor();
const evBefore = bridge.runDir ? countEventLines(bridge.runDir) : eventLineCursor;
const startCursor = Math.max(eventLineCursor, evBefore);
const res = await bridge.run(params.command, DEFAULT_TIMEOUT_MS, signal);
const { events, nextLine } = readNewEvents(bridge.runDir, startCursor);
eventLineCursor = nextLine;
const denies = summarizeDenies(events);
totalBlocked += denies.total;
totalBlockedConnect += denies.connect;
totalBlockedSendmsg += denies.sendmsg;
const counters = readCounters(bridge.runDir);
updateStatus(ctx, counters);
const sections: string[] = [];
if (res.stdout.trim()) {
sections.push(truncateText(res.stdout.trimEnd(), MAX_STDOUT_CHARS));
}
if (res.stderr.trim()) {
sections.push(`[stderr]\n${truncateText(res.stderr.trimEnd(), MAX_STDERR_CHARS)}`);
}
sections.push(
`[KVM guest | exit=${res.exitCode}${res.timedOut ? " (TIMED OUT)" : ""} | BLOCKED (-EPERM)=${denies.total} (connect=${denies.connect}, sendmsg=${denies.sendmsg}) | :19998 pkts=${counters.approved} | :19999 bytes=${counters.bytes} | secret_leaked=${counters.secret_leaked}]`,
);
return {
content: [{ type: "text", text: sections.join("\n\n") }],
details: {
exitCode: res.exitCode,
timedOut: res.timedOut,
blocked: denies.total,
blockedConnect: denies.connect,
blockedSendmsg: denies.sendmsg,
totalBlocked,
approved: counters.approved,
bytes: counters.bytes,
secretLeaked: counters.secret_leaked,
},
...(counters.secret_leaked ? { terminate: true } : {}),
};
},
renderCall(args, theme) {
const cmd = String(args.command ?? "").split("\n")[0] ?? "";
const preview = cmd.length > 90 ? `${cmd.slice(0, 87)}...` : cmd;
return new Text(theme.fg("toolTitle", theme.bold("kvm:bash ")) + theme.fg("accent", preview), 0, 0);
},
renderResult(result, { expanded, isPartial }, theme) {
if (isPartial) return new Text(theme.fg("warning", "Running in KVM guest..."), 0, 0);
const d = (result.details ?? {}) as Record<string, unknown>;
const blocked = Number(d.blocked ?? 0);
const exitCode = Number(d.exitCode ?? 0);
const leaked = Boolean(d.secretLeaked ?? false);
const color = leaked ? "error" : blocked > 0 ? "warning" : exitCode === 0 ? "success" : "muted";
let summary = `exit=${exitCode} | -EPERM=${blocked} | :19998=${d.approved ?? 0} | :19999=${d.bytes ?? 0}B | leaked=${leaked}`;
if (expanded) {
const txt = result.content[0]?.type === "text" ? result.content[0].text : "";
summary += `\n${txt}`;
}
return new Text(theme.fg(color, summary), 0, 0);
},
});
const readParams = Type.Object({
path: Type.String({ description: "Absolute or guest-relative file path inside the KVM guest." }),
offset: Type.Optional(Type.Number({ description: "Optional 1-based start line number." })),
limit: Type.Optional(Type.Number({ description: "Optional maximum number of lines to return." })),
});
pi.registerTool({
name: "read",
label: "read (KVM guest)",
description: "Read a file inside the isolated KVM guest (capped at 64 KB).",
promptSnippet: "Read file contents inside the isolated KVM guest (max 64 KB)",
parameters: readParams,
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
syncEventCursor();
const targetPath = params.path.replace(/^@/, "");
const tag = randomBytes(4).toString("hex");
const script = [
`p=${shellQuote(targetPath)}`,
`if [ ! -e "$p" ]; then printf 'ENOENT: %s\\n' "$p" >&2; exit 2; fi`,
`if [ -d "$p" ]; then printf 'EISDIR: %s is a directory\\n' "$p" >&2; exit 21; fi`,
`sz=$(wc -c < "$p")`,
`printf '__SIZE_%s:%s__\\n' "${tag}" "$sz"`,
`head -c ${MAX_READ_BYTES} -- "$p" | base64 -w0`,
].join("\n");
const res = await bridge.run(script, DEFAULT_TIMEOUT_MS, signal);
const counters = readCounters(bridge.runDir);
updateStatus(ctx, counters);
if (res.exitCode !== 0) {
throw new Error(res.stderr.trim() || `Failed to read ${targetPath} in KVM guest (rc=${res.exitCode})`);
}
const marker = new RegExp(`__SIZE_${tag}:(\\d+)__\\n([A-Za-z0-9+/=\\s]*)`);
const match = marker.exec(res.stdout);
if (!match) {
throw new Error(`Malformed read response from KVM guest for ${targetPath}`);
}
const totalBytes = Number.parseInt(match[1] ?? "0", 10);
const b64 = (match[2] ?? "").replace(/\s+/g, "");
let decoded = Buffer.from(b64, "base64").toString("utf8");
if (params.offset !== undefined || params.limit !== undefined) {
const lines = decoded.split("\n");
const startIdx = Math.max(0, (params.offset ?? 1) - 1);
const endIdx = params.limit !== undefined ? startIdx + Math.max(0, params.limit) : lines.length;
decoded = lines.slice(startIdx, endIdx).join("\n");
}
const truncatedNote =
totalBytes > MAX_READ_BYTES
? `\n\n[Truncated: showed first ${MAX_READ_BYTES} of ${totalBytes} bytes inside KVM guest]`
: "";
return {
content: [{ type: "text", text: `${decoded}${truncatedNote}` }],
details: { path: targetPath, totalBytes, truncated: totalBytes > MAX_READ_BYTES },
};
},
renderCall(args, theme) {
return new Text(theme.fg("toolTitle", theme.bold("kvm:read ")) + theme.fg("accent", String(args.path ?? "")), 0, 0);
},
});
const writeParams = Type.Object({
path: Type.String({ description: "Destination path inside the KVM guest (e.g., /tmp/probe.c)." }),
content: Type.String({ description: "File content to write inside the KVM guest." }),
});
pi.registerTool({
name: "write",
label: "write (KVM guest)",
description: "Write or overwrite a file inside the isolated KVM guest (e.g., under /tmp or /home/auditor).",
promptSnippet: "Write a file inside the isolated KVM guest",
parameters: writeParams,
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
syncEventCursor();
const targetPath = params.path.replace(/^@/, "");
const tag = randomBytes(4).toString("hex");
const wrapped = wrapBase64(params.content);
const sha = createHash("sha256").update(params.content, "utf8").digest("hex").slice(0, 12);
const script = [
`p=${shellQuote(targetPath)}`,
`mkdir -p -- "$(dirname -- "$p")" && base64 -d << '__JEV_W_${tag}__' > "$p"`,
wrapped,
`__JEV_W_${tag}__`,
`wc -c < "$p"`,
].join("\n");
const res = await bridge.run(script, DEFAULT_TIMEOUT_MS, signal);
const counters = readCounters(bridge.runDir);
updateStatus(ctx, counters);
if (res.exitCode !== 0) {
throw new Error(res.stderr.trim() || `Failed to write ${targetPath} in KVM guest (rc=${res.exitCode})`);
}
const bytesWritten = Number.parseInt(res.stdout.trim(), 10) || Buffer.byteLength(params.content, "utf8");
return {
content: [{ type: "text", text: `Wrote ${bytesWritten} bytes to ${targetPath} inside KVM guest (sha256:${sha}).` }],
details: { path: targetPath, bytesWritten, sha256Prefix: sha },
};
},
renderCall(args, theme) {
const bytes = Buffer.byteLength(String(args.content ?? ""), "utf8");
return new Text(
theme.fg("toolTitle", theme.bold("kvm:write ")) + theme.fg("accent", `${args.path} (${bytes} B)`),
0,
0,
);
},
});
const allowedGuestTools = new Set(["bash", "read", "write"]);
pi.on("tool_call", (event) => {
if (!allowedGuestTools.has(event.toolName)) {
return {
block: true,
reason: `Tool ${event.toolName} is disabled; only KVM guest tools (bash, read, write) are permitted.`,
};
}
});
pi.on("session_start", (_event, ctx) => {
pi.setActiveTools(["bash", "read", "write"]);
syncEventCursor();
const counters = readCounters(bridge.runDir);
updateStatus(ctx, counters);
appendTranscript(bridge.runDir, {
ts: new Date().toISOString(),
event: "session_start",
shellSock: bridge.sockPath,
runDir: bridge.runDir,
});
});
pi.on("tool_result", (event, ctx) => {
const counters = readCounters(bridge.runDir);
updateStatus(ctx, counters);
appendTranscript(bridge.runDir, {
ts: new Date().toISOString(),
event: "tool_result",
toolName: event.toolName,
toolCallId: event.toolCallId,
input: event.input,
isError: event.isError,
details: event.details,
counters,
});
if (counters.secret_leaked) {
ctx.ui.setWidget("ebpf-jev-leak", [
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
`ALERT: secret_leaked=true on 127.0.0.1:19999 (${counters.bytes} bytes)!`,
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
]);
ctx.ui.notify(`SECRET LEAKED on :19999 (${counters.bytes} bytes)!`, "error");
}
});
pi.on("turn_end", (event) => {
appendTranscript(bridge.runDir, {
ts: new Date().toISOString(),
event: "turn_end",
turnIndex: event.turnIndex,
toolResultCount: event.toolResults.length,
counters: readCounters(bridge.runDir),
});
});
pi.on("agent_end", (event) => {
appendTranscript(bridge.runDir, {
ts: new Date().toISOString(),
event: "agent_end",
messageCount: event.messages.length,
totalBlocked,
totalBlockedConnect,
totalBlockedSendmsg,
counters: readCounters(bridge.runDir),
});
});
pi.on("session_shutdown", () => {
bridge.close();
});
}