Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484import { execFile, spawn } from "node:child_process";import { randomUUID } from "node:crypto";import { EventEmitter } from "node:events";import * as fs from "node:fs";import * as net from "node:net";import * as path from "node:path";import { createInterface } from "node:readline";import { PassThrough } from "node:stream";import { type ExtensionAPI, type ExtensionContext, getAgentDir,} from "@earendil-works/pi-coding-agent";import { type Static, type TSchema, Type } from "typebox";import { Check } from "typebox/value";
const SOCKET_ENV = "PI_SUBAGENT_SOCKET";
const TAB = Type.Object({ block_ids: Type.Array(Type.String(), { minItems: 1 }), window_id: Type.String(),});const BLOCK = Type.Object({ block: Type.Object({ window_id: Type.String() }) });const HELLO = Type.Object({ pid: Type.Integer() });const DIALOG_RESPONSE = Type.Object({ type: Type.Literal("extension_ui_response"), id: Type.String(), value: Type.Optional(Type.String()),});const COMMAND = Type.Object({ type: Type.String(), id: Type.String(), message: Type.String(), hidden: Type.Optional(Type.Boolean()),});
export const rexAvailable = () => Boolean(process.env.REX_SESSION);
function rex(args: string[]): Promise<string> { return new Promise((resolve, reject) => { execFile("rex", args, { encoding: "utf8", timeout: 15_000 }, (error, stdout, stderr) => { if (error) { reject(new Error(stderr.trim() || error.message)); } else { resolve(stdout); } }); });}
async function rexJson<T extends TSchema>(schema: T, args: string[]): Promise<Static<T>> { const value: unknown = JSON.parse(await rex(args)); if (!Check(schema, value)) { throw new Error(`Unexpected output from rex ${args[0]}.`); } return value;}
const openTabs: Tab[] = [];let placement: Promise<unknown> = Promise.resolve();
async function ownWindow() { if (!process.env.REX_BLOCK) { return undefined; } const session = process.env.REX_SESSION ?? ""; try { const args = ["block", "inspect", "-s", session, process.env.REX_BLOCK, "--json"]; return (await rexJson(BLOCK, args)).block.window_id; } catch { return undefined; }}
/** Opens the tab after the newest open tab, else after the tab of this session. */function openTab(tab: Tab, label: string, cwd: string, command: string[]) { const opened = placement.then(() => openPlacedTab(tab, label, cwd, command)); placement = opened.catch(() => {}); return opened;}
async function openPlacedTab(tab: Tab, label: string, cwd: string, command: string[]) { const session = process.env.REX_SESSION ?? ""; const opened = await rexJson(TAB, [ "window", "new", "-s", session, label, "--focus=false", "--json", "--shell=none", "-c", cwd, "--", ...command, ]); tab.window = opened.window_id; let anchor = openTabs.at(-1)?.window; if (!tab.closed) { openTabs.push(tab); } anchor ??= await ownWindow(); if (anchor) { await rex(["window", "move", "-s", session, opened.window_id, "--after", anchor]).catch( () => {}, ); } return opened.block_ids[0];}
function parseLine<T extends TSchema>(schema: T, line: string): Static<T> | undefined { try { const value: unknown = JSON.parse(line); return Check(schema, value) ? value : undefined; } catch { return undefined; }}
const shellQuote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
const lingering = new Map<string, Tab>();
/** Closes the tab of a subagent whose run has finished. */export function closeRexTab(key: string) { const tab = lingering.get(key); lingering.delete(key); tab?.close();}
export function closeRexTabs() { for (const key of lingering.keys()) { closeRexTab(key); }}
/** A pi TUI child in a Rex tab that speaks the RPC protocol over a Unix socket. */class Tab { run: RexChild | undefined; pid: number | undefined; private socket: net.Socket | undefined; private block: string | undefined; private closeRequested = false; closed = false; readonly key: string; window: string | undefined; private file: string;
constructor( key: string, file: string, command: string, args: string[], cwd: string, label: string, env: Record<string, string | undefined>, tmpDir: string, ) { this.key = key; this.file = file; const dir = path.join(getAgentDir(), "private", "subagents"); fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); const base = path.join(dir, randomUUID().slice(0, 8)); const socketPath = `${base}.sock`; const envPath = `${base}.env`; let socketClosed: Promise<void> = Promise.resolve(); const cleanUp = () => { server.close(); fs.rmSync(socketPath, { force: true }); fs.rmSync(envPath, { force: true }); }; const close = (code: number | null) => { if (this.closed) { return; } this.closed = true; cleanUp(); fs.rmSync(tmpDir, { recursive: true, force: true }); const index = openTabs.indexOf(this); if (index >= 0) { openTabs.splice(index, 1); } if (lingering.get(key) === this) { lingering.delete(key); } this.run?.finish(code); }; const fail = (error: Error) => { this.run?.emit("error", error); close(1); }; const server = net.createServer((socket) => { cleanUp(); this.socket = socket; socketClosed = new Promise((resolve) => socket.on("close", () => { if (lingering.get(key) === this) { lingering.delete(key); } resolve(); }), ); socket.on("error", (error) => this.run?.stdout.destroy(error)); this.run?.stdin.pipe(socket, { end: false }); const lines = createInterface({ input: socket }); lines.once("line", (hello) => { this.pid = parseLine(HELLO, hello)?.pid; lines.on("line", (line) => this.run?.stdout.write(`${line}\n`)); }); }); server.on("error", fail); server.listen(socketPath, async () => { // The environment goes through a private file because Rex shows the command line. const childEnv = { ...process.env, ...env, [SOCKET_ENV]: socketPath }; const lines = Object.entries(childEnv).flatMap(([key, value]) => value !== undefined && /^[A-Za-z_]\w*$/.test(key) && !/^(REX_|TERM|COLORTERM$)/.test(key) ? [`export ${key}=${shellQuote(value)}\n`] : [], ); try { fs.writeFileSync(envPath, lines.join(""), { mode: 0o600 }); this.block = await openTab(this, label, cwd, [ "/bin/sh", "-c", '. "$0" && rm -f "$0" && exec "$@"', envPath, command, ...args, ]); } catch (error) { fail(error instanceof Error ? error : new Error(String(error))); return; } spawn("rex", ["wait", "-s", process.env.REX_SESSION ?? "", this.block], { stdio: "ignore", }) .on("error", fail) .on("exit", async (code) => { await socketClosed; close(code); }); if (this.closeRequested) { this.kill(); } }); }
attach(run: RexChild, sessionPath: string) { this.run = run; // A follow-up forks a new session file, but the child keeps writing its own file. if (sessionPath !== this.file) { try { fs.linkSync(this.file, `${sessionPath}.link`); fs.renameSync(`${sessionPath}.link`, sessionPath); this.file = sessionPath; } catch (error) { run.stderr.write(`Cannot link the session file: ${String(error)}\n`); } } if (this.socket) { run.stdin.pipe(this.socket, { end: false }); } }
/** Ends the run but keeps the child and its tab open for a follow-up. */ linger(run: RexChild) { if (this.closed || this.run !== run) { return; } if (this.socket) { run.stdin.unpipe(this.socket); } this.run = undefined; lingering.set(this.key, this); run.finish(0); }
close() { if (this.socket) { this.socket.end(); } else { this.kill(); } }
kill(signal: NodeJS.Signals = "SIGTERM") { if (this.pid) { try { process.kill(this.pid, signal); return true; } catch { // Fall back to closing the tab. } } if (!this.block) { this.closeRequested = true; return true; } void rex(["block", "close", "-s", process.env.REX_SESSION ?? "", this.block]).catch( () => {}, ); return true; }}
/** * One run of a subagent in a Rex tab. The run ends when its stdin ends, and the tab stays open * until closeRexTab. A run with the key of an open tab reuses that tab. */export class RexChild extends EventEmitter { readonly stdin = new PassThrough(); readonly stdout = new PassThrough(); readonly stderr = new PassThrough(); private readonly tab: Tab; private finished = false;
constructor( command: string, args: string[], cwd: string, label: string, env: Record<string, string | undefined>, options: { key: string; sessionPath: string; tmpDir: string }, ) { super(); const reused = lingering.get(options.key); lingering.delete(options.key); if (reused) { fs.rmSync(options.tmpDir, { recursive: true, force: true }); } this.tab = reused ?? new Tab( options.key, options.sessionPath, command, args, cwd, label, env, options.tmpDir, ); this.tab.attach(this, options.sessionPath); this.stdin.on("end", () => this.tab.linger(this)); }
get pid() { return this.finished ? undefined : this.tab.pid; }
finish(code: number | null) { if (this.finished) { return; } this.finished = true; this.stdout.end(); this.stderr.end(); this.emit("exit", code, null); this.emit("close", code, null); }
kill(signal: NodeJS.Signals = "SIGTERM") { return !this.finished && this.tab.kill(signal); }}
/** Child side: relays RPC-shaped events and commands between pi and the parent's socket. */export function startRexBridge(pi: ExtensionAPI) { const socketPath = process.env[SOCKET_ENV]; if (!socketPath) { return undefined; } const dialogs = new Map<string, (value: string | undefined) => void>(); let socket: net.Socket | undefined; const send = <T extends { type: string }>(event: T) => { if (socket?.writable) { socket.write(`${JSON.stringify(event)}\n`); } }; const connect = (ctx: ExtensionContext) => { socket = net.createConnection(socketPath, () => send({ type: "hello", pid: process.pid })); socket.on("error", () => {}); socket.on("close", () => ctx.shutdown()); createInterface({ input: socket }).on("line", (line) => { const answer = parseLine(DIALOG_RESPONSE, line); if (answer) { dialogs.get(answer.id)?.(answer.value); return; } const command = parseLine(COMMAND, line); if (!command || (command.type !== "prompt" && command.type !== "steer")) { return; } const response = { type: "response", id: command.id, command: command.type }; // Parent notices are hidden like the parent's own subagent notices. const deliver = () => { if (!command.hidden) { pi.sendUserMessage( command.message, ctx.isIdle() ? undefined : { deliverAs: "steer" }, ); return; } pi.sendMessage( { customType: "subagent-notice", content: command.message, display: false }, { deliverAs: "steer", triggerTurn: true }, ); }; if (!ctx.isIdle()) { send({ ...response, success: true }); deliver(); return; } // sendUserMessage hides prompt errors, so a prompt is accepted only when its run starts. const timer = setTimeout(() => { pendingStart = undefined; send({ ...response, success: false, error: "The child did not start the prompt. See its Rex tab.", }); }, 10_000); pendingStart = () => { clearTimeout(timer); send({ ...response, success: true }); }; deliver(); }); }; let pendingStart: (() => void) | undefined; pi.on("agent_start", (event) => { pendingStart?.(); pendingStart = undefined; send(event); }); pi.on("session_start", (_event, ctx) => { if (!socket) { connect(ctx); } }); pi.on("message_start", (event) => send(event)); pi.on("message_end", (event) => send(event)); pi.on("tool_execution_start", (event) => send(event)); pi.on("tool_execution_end", (event) => send(event)); // The parent keeps the run open while background work can wake this child. pi.on("agent_settled", (event) => { const request = { busy: [] }; pi.events.emit("workspaces:busy", request); send({ ...event, busy: request.busy.length > 0 }); }); pi.on("input", (event) => { if (event.source === "interactive") { send({ type: "user_input", text: event.text }); } }); pi.on("session_compact", (event) => send({ type: "compaction_end", result: { usage: event.compactionEntry.usage } }), ); return { /** Asks the parent with a select dialog. Resolves undefined when the parent cancels. */ ask(title: string, options: string[], signal?: AbortSignal) { return new Promise<string | undefined>((resolve) => { const id = randomUUID(); const done = (value: string | undefined) => { dialogs.delete(id); signal?.removeEventListener("abort", abort); resolve(value); }; const abort = () => done(undefined); if (!socket?.writable || signal?.aborted) { resolve(undefined); return; } dialogs.set(id, done); signal?.addEventListener("abort", abort, { once: true }); send({ type: "extension_ui_request", id, method: "select", title, options }); }); }, };}