|
| 1 | +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; |
| 2 | +import { tmpdir } from "node:os"; |
| 3 | +import { dirname, join } from "node:path"; |
| 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 | + |
| 11 | +export type PiRpcClient = RpcClient; |
| 12 | + |
| 13 | +interface RpcClientOptionsAccess { |
| 14 | + options: RpcClientOptions; |
| 15 | +} |
| 16 | + |
| 17 | +export type PiRpcClientOptions = Pick<RpcClientOptions, "cwd" | "model"> & { |
| 18 | + providerOptions?: PosthogProviderOptions; |
| 19 | +}; |
| 20 | + |
| 21 | +export function createPiRpcClient( |
| 22 | + options: PiRpcClientOptions = {}, |
| 23 | +): PiRpcClient { |
| 24 | + const { providerOptions, ...rpcOptions } = options; |
| 25 | + const client = new RpcClient({ |
| 26 | + ...rpcOptions, |
| 27 | + cliPath: fileURLToPath(new URL("./rpc-host.js", import.meta.url)), |
| 28 | + provider: "posthog", |
| 29 | + }); |
| 30 | + const start = client.start.bind(client); |
| 31 | + const clientOptions = (client as unknown as RpcClientOptionsAccess).options; |
| 32 | + const baseArgs = clientOptions.args ?? []; |
| 33 | + |
| 34 | + client.start = async () => { |
| 35 | + const directory = mkdtempSync(join(tmpdir(), "posthog-pi-bootstrap-")); |
| 36 | + const bootstrapFile = join(directory, "bootstrap.json"); |
| 37 | + writeFileSync(bootstrapFile, JSON.stringify({ providerOptions }), { |
| 38 | + mode: 0o600, |
| 39 | + }); |
| 40 | + clientOptions.args = [ |
| 41 | + ...baseArgs, |
| 42 | + "--posthog-bootstrap-file", |
| 43 | + bootstrapFile, |
| 44 | + ]; |
| 45 | + |
| 46 | + try { |
| 47 | + await start(); |
| 48 | + } catch (error) { |
| 49 | + rmSync(dirname(bootstrapFile), { force: true, recursive: true }); |
| 50 | + throw error; |
| 51 | + } |
| 52 | + }; |
| 53 | + |
| 54 | + return client; |
| 55 | +} |
0 commit comments