|
| 1 | +import { type ChildProcess, spawn } from "node:child_process"; |
| 2 | +import type { Writable } from "node:stream"; |
| 3 | +import { StringDecoder } from "node:string_decoder"; |
| 4 | +import { fileURLToPath } from "node:url"; |
| 5 | +import { |
| 6 | + RpcClient, |
| 7 | + type RpcClientOptions, |
| 8 | +} from "@earendil-works/pi-coding-agent"; |
| 9 | +import type { PosthogProviderOptions } from "@posthog/harness/extensions/posthog-provider/provider"; |
| 10 | +import { safePiEnvironment } from "./rpc-environment"; |
| 11 | + |
| 12 | +export type PiRpcClient = RpcClient; |
| 13 | + |
| 14 | +interface RpcClientInternals { |
| 15 | + process?: ChildProcess; |
| 16 | + stopReadingStdout?: () => void; |
| 17 | + stderr: string; |
| 18 | + exitError: Error | null; |
| 19 | + handleLine(line: string): void; |
| 20 | + createProcessExitError( |
| 21 | + code: number | null, |
| 22 | + signal: NodeJS.Signals | null, |
| 23 | + ): Error; |
| 24 | + rejectPendingRequests(error: Error): void; |
| 25 | +} |
| 26 | + |
| 27 | +function attachJsonlReader( |
| 28 | + stream: NodeJS.ReadableStream, |
| 29 | + onLine: (line: string) => void, |
| 30 | +): () => void { |
| 31 | + const decoder = new StringDecoder("utf8"); |
| 32 | + let buffer = ""; |
| 33 | + const onData = (chunk: Buffer | string) => { |
| 34 | + buffer += typeof chunk === "string" ? chunk : decoder.write(chunk); |
| 35 | + let newlineIndex = buffer.indexOf("\n"); |
| 36 | + while (newlineIndex !== -1) { |
| 37 | + const line = buffer.slice(0, newlineIndex); |
| 38 | + onLine(line.endsWith("\r") ? line.slice(0, -1) : line); |
| 39 | + buffer = buffer.slice(newlineIndex + 1); |
| 40 | + newlineIndex = buffer.indexOf("\n"); |
| 41 | + } |
| 42 | + }; |
| 43 | + stream.on("data", onData); |
| 44 | + return () => stream.off("data", onData); |
| 45 | +} |
| 46 | + |
| 47 | +class SecurePiRpcClient extends RpcClient { |
| 48 | + constructor( |
| 49 | + private readonly secureOptions: RpcClientOptions, |
| 50 | + private readonly providerOptions?: PosthogProviderOptions, |
| 51 | + ) { |
| 52 | + super(secureOptions); |
| 53 | + } |
| 54 | + |
| 55 | + override async start(): Promise<void> { |
| 56 | + const internals = this as unknown as RpcClientInternals; |
| 57 | + if (internals.process) { |
| 58 | + throw new Error("Pi RPC client is already started"); |
| 59 | + } |
| 60 | + |
| 61 | + internals.exitError = null; |
| 62 | + const args = ["--mode", "rpc"]; |
| 63 | + if (this.secureOptions.provider) { |
| 64 | + args.push("--provider", this.secureOptions.provider); |
| 65 | + } |
| 66 | + if (this.secureOptions.model) { |
| 67 | + args.push("--model", this.secureOptions.model); |
| 68 | + } |
| 69 | + if (this.secureOptions.args) { |
| 70 | + args.push(...this.secureOptions.args); |
| 71 | + } |
| 72 | + |
| 73 | + const child = spawn( |
| 74 | + process.execPath, |
| 75 | + [this.secureOptions.cliPath ?? "dist/cli.js", ...args], |
| 76 | + { |
| 77 | + cwd: this.secureOptions.cwd, |
| 78 | + env: safePiEnvironment(process.env), |
| 79 | + stdio: ["pipe", "pipe", "pipe", "pipe"], |
| 80 | + }, |
| 81 | + ); |
| 82 | + internals.process = child; |
| 83 | + |
| 84 | + child.stderr?.on("data", (data: Buffer) => { |
| 85 | + internals.stderr += data.toString(); |
| 86 | + process.stderr.write(data); |
| 87 | + }); |
| 88 | + child.once("exit", (code, signal) => { |
| 89 | + if (internals.process !== child) { |
| 90 | + return; |
| 91 | + } |
| 92 | + const error = internals.createProcessExitError(code, signal); |
| 93 | + internals.exitError = error; |
| 94 | + internals.rejectPendingRequests(error); |
| 95 | + }); |
| 96 | + child.once("error", (error) => { |
| 97 | + if (internals.process !== child) { |
| 98 | + return; |
| 99 | + } |
| 100 | + const processError = new Error( |
| 101 | + `Agent process error: ${error.message}. Stderr: ${internals.stderr}`, |
| 102 | + ); |
| 103 | + internals.exitError = processError; |
| 104 | + internals.rejectPendingRequests(processError); |
| 105 | + }); |
| 106 | + child.stdin?.on("error", (error) => { |
| 107 | + const stdinError = |
| 108 | + internals.exitError ?? |
| 109 | + new Error( |
| 110 | + `Agent process stdin error: ${error.message}. Stderr: ${internals.stderr}`, |
| 111 | + ); |
| 112 | + internals.exitError = stdinError; |
| 113 | + internals.rejectPendingRequests(stdinError); |
| 114 | + }); |
| 115 | + if (child.stdout) { |
| 116 | + internals.stopReadingStdout = attachJsonlReader(child.stdout, (line) => |
| 117 | + internals.handleLine(line), |
| 118 | + ); |
| 119 | + } |
| 120 | + |
| 121 | + const bootstrapPipe = child.stdio[3] as Writable | null; |
| 122 | + bootstrapPipe?.end( |
| 123 | + JSON.stringify({ providerOptions: this.providerOptions }), |
| 124 | + ); |
| 125 | + |
| 126 | + await new Promise((resolve) => setTimeout(resolve, 100)); |
| 127 | + if (child.exitCode !== null) { |
| 128 | + throw ( |
| 129 | + internals.exitError ?? |
| 130 | + internals.createProcessExitError(child.exitCode, child.signalCode) |
| 131 | + ); |
| 132 | + } |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +export type PiRpcClientOptions = Pick<RpcClientOptions, "cwd" | "model"> & { |
| 137 | + providerOptions?: PosthogProviderOptions; |
| 138 | +}; |
| 139 | + |
| 140 | +export function createPiRpcClient( |
| 141 | + options: PiRpcClientOptions = {}, |
| 142 | +): PiRpcClient { |
| 143 | + const { providerOptions, ...rpcOptions } = options; |
| 144 | + return new SecurePiRpcClient( |
| 145 | + { |
| 146 | + ...rpcOptions, |
| 147 | + cliPath: fileURLToPath(new URL("./rpc-host.js", import.meta.url)), |
| 148 | + provider: "posthog", |
| 149 | + }, |
| 150 | + providerOptions, |
| 151 | + ); |
| 152 | +} |
0 commit comments