repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/llmiterate/rpc.ts

Raw
File outline
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import * as fs from "node:fs";
import * as path from "node:path";
import type { RpcEvent } from "./types";

const RPC_KILL_GRACE_MS = 5_000;
export const LLMITERATE_WORKER_ENV = "LLMITERATE_WORKER";
export const WORKER_SYSTEM_PROMPT = [
	"You are llmiterate, a background Pi worker launched from a file-save marker.",
	"Fulfill only the marker request.",
	"Edit files directly with tools.",
	"Do not ask for confirmation.",
	"Keep assistant text concise; source edits are the primary output.",
].join("\n");
const RESPONSE_EVENT = "response";
const AGENT_END_EVENT = "agent_end";
const CMD_NEW_SESSION = "new_session";
const CMD_SET_SESSION_NAME = "set_session_name";
const CMD_PROMPT = "prompt";
const CMD_ABORT = "abort";

interface PendingCommand {
	command: string;
	resolve(response: unknown): void;
	reject(error: Error): void;
}

interface PiInvocation {
	command: string;
	args: string[];
}

interface RpcCommandPayload {
	type: string;
	[key: string]: unknown;
}

interface RpcResponse extends RpcWireEvent {
	type: "response";
	id?: unknown;
	success?: unknown;
	error?: unknown;
	data?: unknown;
}

interface RpcWireEvent {
	type: string;
	[key: string]: unknown;
}

export interface RpcWorkerOptions {
	cwd: string;
	sessionDir: string;
	onEvent(event: RpcEvent): void;
	invocation?: PiInvocation;
	model?: string;
	thinking?: string;
	timeoutMs?: number;
	appendSystemPrompt?: string;
	offline?: boolean;
	env?: NodeJS.ProcessEnv;
}

export class PiRpcWorker {
	private proc?: ChildProcessWithoutNullStreams;
	private stdoutBuffer = "";
	private stderr = "";
	private nextId = 1;
	private runningPrompt = false;
	private readonly pending = new Map<string, PendingCommand>();
	private currentPrompt?: { resolve(): void; reject(error: Error): void };

	constructor(private readonly options: RpcWorkerOptions) {}

	async runPrompt(prompt: string, sessionName: string): Promise<void> {
		if (this.runningPrompt)
			throw new Error("RPC worker already has an active prompt");

		this.runningPrompt = true;
		try {
			await this.command({ type: CMD_NEW_SESSION });
			await this.command({ type: CMD_SET_SESSION_NAME, name: sessionName });

			const done = new Promise<void>((resolve, reject) => {
				this.currentPrompt = { resolve, reject };
			});
			await this.command({ type: CMD_PROMPT, message: prompt });
			await withTimeout(done, this.options.timeoutMs, () => {
				this.abort();
				return new Error(
					`RPC worker timed out after ${this.options.timeoutMs}ms`,
				);
			});
		} finally {
			this.runningPrompt = false;
			this.currentPrompt = undefined;
		}
	}

	abort(): void {
		if (!this.proc || this.proc.killed) return;
		void this.command({ type: CMD_ABORT }).catch(() => {});
	}

	dispose(): void {
		const proc = this.proc;
		this.proc = undefined;
		this.rejectAll(new Error("RPC worker disposed"));
		if (!proc || proc.killed) return;

		let exited = false;
		proc.once("exit", () => {
			exited = true;
		});
		proc.kill("SIGTERM");
		setTimeout(() => {
			if (!exited) proc.kill("SIGKILL");
		}, RPC_KILL_GRACE_MS).unref?.();
	}

	private ensureStarted(): void {
		if (this.proc && !this.proc.killed) return;

		fs.mkdirSync(this.options.sessionDir, { recursive: true });
		const invocation =
			this.options.invocation ?? getPiInvocation(workerArgs(this.options));

		this.stderr = "";
		this.proc = spawn(invocation.command, invocation.args, {
			cwd: this.options.cwd,
			env: {
				...process.env,
				...this.options.env,
				[LLMITERATE_WORKER_ENV]: "1",
			},
			shell: false,
			stdio: ["pipe", "pipe", "pipe"],
		});

		this.proc.stdout.on("data", (data) => this.handleStdout(data.toString()));
		this.proc.stderr.on("data", (data) => {
			this.stderr += data.toString();
		});
		this.proc.on("error", (error) => this.rejectAll(error));
		this.proc.on("close", (code) => {
			const message =
				this.stderr.trim() ||
				`RPC worker exited with code ${code ?? "unknown"}`;
			this.proc = undefined;
			this.rejectAll(new Error(message));
		});
	}

	private command(payload: RpcCommandPayload): Promise<unknown> {
		this.ensureStarted();
		if (!this.proc?.stdin.writable)
			return Promise.reject(new Error("RPC worker stdin closed"));

		const id = `llmiterate-${this.nextId++}`;
		const line = JSON.stringify({ id, ...payload }) + "\n";

		return new Promise((resolve, reject) => {
			this.pending.set(id, { command: payload.type, resolve, reject });
			this.proc!.stdin.write(line, (error) => {
				if (!error) return;
				this.pending.delete(id);
				reject(error);
			});
		});
	}

	private handleStdout(chunk: string): void {
		this.stdoutBuffer += chunk;
		const lines = this.stdoutBuffer.split("\n");
		this.stdoutBuffer = lines.pop() ?? "";
		for (const line of lines) this.handleLine(line);
	}

	private handleLine(line: string): void {
		if (!line.trim()) return;

		let event: RpcWireEvent;
		try {
			event = parseRpcObject(line);
		} catch (error) {
			this.failProtocol(errorMessage(error));
			return;
		}

		if (isRpcResponse(event)) {
			this.handleResponse(event);
			return;
		}

		this.options.onEvent(event as RpcEvent);
		if (event.type === AGENT_END_EVENT) this.currentPrompt?.resolve();
	}

	private handleResponse(response: RpcResponse): void {
		const id = typeof response.id === "string" ? response.id : undefined;
		if (!id) return;

		const pending = this.pending.get(id);
		if (!pending) return;
		this.pending.delete(id);

		if (response.success === false) {
			const reason = response.error ?? `${pending.command} failed`;
			pending.reject(new Error(String(reason)));
			return;
		}
		pending.resolve(response.data ?? response);
	}

	private failProtocol(message: string): void {
		this.proc?.kill("SIGTERM");
		this.rejectAll(new Error(message));
	}

	private rejectAll(error: Error): void {
		for (const pending of this.pending.values()) pending.reject(error);
		this.pending.clear();
		this.currentPrompt?.reject(error);
		this.currentPrompt = undefined;
		this.runningPrompt = false;
	}
}

function parseRpcObject(line: string): RpcWireEvent {
	const parsed = JSON.parse(line);
	if (!isObject(parsed) || typeof parsed.type !== "string")
		throw new Error(`invalid RPC event: ${line}`);
	return { ...parsed, type: parsed.type };
}

function isRpcResponse(event: RpcWireEvent): event is RpcResponse {
	return event.type === RESPONSE_EVENT;
}

function errorMessage(error: unknown): string {
	return error instanceof Error ? error.message : String(error);
}

function isObject(value: unknown): value is Record<string, unknown> {
	return typeof value === "object" && value !== null && !Array.isArray(value);
}

function withTimeout<T>(
	promise: Promise<T>,
	timeoutMs: number | undefined,
	makeError: () => Error,
): Promise<T> {
	if (!timeoutMs) return promise;
	return new Promise((resolve, reject) => {
		const timer = setTimeout(() => reject(makeError()), timeoutMs);
		promise.then(
			(value) => {
				clearTimeout(timer);
				resolve(value);
			},
			(error) => {
				clearTimeout(timer);
				reject(error);
			},
		);
	});
}

export function workerArgs(
	options: Pick<
		RpcWorkerOptions,
		"sessionDir" | "model" | "thinking" | "appendSystemPrompt" | "offline"
	>,
): string[] {
	const args = ["--mode", "rpc"];
	if (options.offline !== false) args.push("--offline");
	args.push("--session-dir", options.sessionDir);
	args.push(
		"--append-system-prompt",
		options.appendSystemPrompt ?? WORKER_SYSTEM_PROMPT,
	);
	if (options.model) args.push("--model", options.model);
	if (options.thinking) args.push("--thinking", options.thinking);
	return args;
}

function getPiInvocation(args: string[]): PiInvocation {
	const currentScript = process.argv[1];
	const isBunVirtualScript = currentScript?.startsWith("/$bunfs/root/");
	if (currentScript && !isBunVirtualScript && fs.existsSync(currentScript)) {
		return { command: process.execPath, args: [currentScript, ...args] };
	}

	const execName = path.basename(process.execPath).toLowerCase();
	const isGenericRuntime = /^(node|bun)(\.exe)?$/.test(execName);
	return isGenericRuntime
		? { command: "pi", args }
		: { command: process.execPath, args };
}