| 19 | |
| 20 | // Manages a child process that acts as a replaying proxy to the underlying AI endpoints |
| 21 | export class CapiProxy { |
| 22 | private proxyUrl: string | undefined; |
| 23 | private startupInfo: ProxyStartupInfo | undefined; |
| 24 | |
| 25 | /** |
| 26 | * Returns the URL of the running proxy. Throws if the proxy has not been started. |
| 27 | */ |
| 28 | get url(): string { |
| 29 | if (!this.proxyUrl) { |
| 30 | throw new Error("CapiProxy has not been started; call start() first."); |
| 31 | } |
| 32 | return this.proxyUrl; |
| 33 | } |
| 34 | |
| 35 | async start(): Promise<string> { |
| 36 | const serverProcess = spawn("npx", ["tsx", HARNESS_SERVER_PATH], { |
| 37 | stdio: ["ignore", "pipe", "inherit"], |
| 38 | shell: true, |
| 39 | }); |
| 40 | |
| 41 | this.startupInfo = await new Promise<ProxyStartupInfo>((resolve, reject) => { |
| 42 | const stdout = serverProcess.stdout!; |
| 43 | const lines: string[] = []; |
| 44 | const lineReader = createInterface({ input: stdout }); |
| 45 | const cleanup = () => { |
| 46 | lineReader.off("line", onLine); |
| 47 | serverProcess.off("exit", onExit); |
| 48 | lineReader.close(); |
| 49 | }; |
| 50 | const onLine = (line: string) => { |
| 51 | lines.push(line); |
| 52 | try { |
| 53 | const info = tryParseStartupInfo(line); |
| 54 | if (!info) { |
| 55 | return; |
| 56 | } |
| 57 | cleanup(); |
| 58 | resolve(info); |
| 59 | } catch (error) { |
| 60 | cleanup(); |
| 61 | reject(error); |
| 62 | } |
| 63 | }; |
| 64 | const onExit = (code: number | null) => { |
| 65 | cleanup(); |
| 66 | reject( |
| 67 | new Error(`Proxy exited before startup with code ${code}: ${lines.join("\n")}`) |
| 68 | ); |
| 69 | }; |
| 70 | lineReader.on("line", onLine); |
| 71 | serverProcess.once("exit", onExit); |
| 72 | }); |
| 73 | this.proxyUrl = this.startupInfo.capiProxyUrl; |
| 74 | |
| 75 | return this.proxyUrl; |
| 76 | } |
| 77 | |
| 78 | getProxyEnv(): Record<string, string> { |