|
| 1 | +import { execFileSync } from "node:child_process"; |
| 2 | +import type { IncomingMessage, ServerResponse } from "node:http"; |
| 3 | +import { Readable } from "node:stream"; |
| 4 | + |
| 5 | +import { json, toWebRequest } from "./helpers.js"; |
| 6 | + |
| 7 | +export interface PiAIRuntime { |
| 8 | + endpoints: Record<string, (req: Request) => Promise<Response>>; |
| 9 | + dispose: () => void; |
| 10 | +} |
| 11 | + |
| 12 | +interface CreatePiAIRuntimeOptions { |
| 13 | + cwd?: string; |
| 14 | + getCwd?: () => string; |
| 15 | +} |
| 16 | + |
| 17 | +function whichCmd(cmd: string): string | null { |
| 18 | + try { |
| 19 | + const bin = process.platform === "win32" ? "where" : "which"; |
| 20 | + const output = execFileSync(bin, [cmd], { |
| 21 | + encoding: "utf-8", |
| 22 | + stdio: ["pipe", "pipe", "pipe"], |
| 23 | + }); |
| 24 | + return output |
| 25 | + .split(/\r?\n/) |
| 26 | + .map((line) => line.trim()) |
| 27 | + .find(Boolean) ?? null; |
| 28 | + } catch { |
| 29 | + return null; |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +export async function createPiAIRuntime(options: CreatePiAIRuntimeOptions = {}): Promise<PiAIRuntime | null> { |
| 34 | + try { |
| 35 | + const ai = await import("../generated/ai/index.js"); |
| 36 | + const cwd = options.cwd ?? process.cwd(); |
| 37 | + const registry = new ai.ProviderRegistry(); |
| 38 | + const sessionManager = new ai.SessionManager(); |
| 39 | + const modelDiscovery: Promise<void>[] = []; |
| 40 | + |
| 41 | + try { |
| 42 | + await import("../generated/ai/providers/claude-agent-sdk.js"); |
| 43 | + const claudePath = whichCmd("claude"); |
| 44 | + const provider = await ai.createProvider({ |
| 45 | + type: "claude-agent-sdk", |
| 46 | + cwd, |
| 47 | + ...(claudePath && { claudeExecutablePath: claudePath }), |
| 48 | + }); |
| 49 | + registry.register(provider); |
| 50 | + } catch { |
| 51 | + // Claude SDK not available. |
| 52 | + } |
| 53 | + |
| 54 | + try { |
| 55 | + await import("../generated/ai/providers/codex-sdk.js"); |
| 56 | + await import("@openai/codex-sdk"); |
| 57 | + const codexPath = whichCmd("codex"); |
| 58 | + const provider = await ai.createProvider({ |
| 59 | + type: "codex-sdk", |
| 60 | + cwd, |
| 61 | + ...(codexPath && { codexExecutablePath: codexPath }), |
| 62 | + }); |
| 63 | + registry.register(provider); |
| 64 | + } catch { |
| 65 | + // Codex SDK not available. |
| 66 | + } |
| 67 | + |
| 68 | + try { |
| 69 | + await import("../generated/ai/providers/pi-sdk-node.js"); |
| 70 | + const piPath = whichCmd("pi"); |
| 71 | + if (piPath) { |
| 72 | + const provider = await ai.createProvider({ |
| 73 | + type: "pi-sdk", |
| 74 | + cwd, |
| 75 | + piExecutablePath: piPath, |
| 76 | + } as any); |
| 77 | + if (provider && "fetchModels" in provider) { |
| 78 | + modelDiscovery.push( |
| 79 | + (provider as { fetchModels: () => Promise<void> }) |
| 80 | + .fetchModels() |
| 81 | + .catch(() => {}), |
| 82 | + ); |
| 83 | + } |
| 84 | + registry.register(provider); |
| 85 | + } |
| 86 | + } catch { |
| 87 | + // Pi not available. |
| 88 | + } |
| 89 | + |
| 90 | + try { |
| 91 | + await import("../generated/ai/providers/opencode-sdk.js"); |
| 92 | + const opencodePath = whichCmd("opencode"); |
| 93 | + if (opencodePath) { |
| 94 | + const provider = await ai.createProvider({ |
| 95 | + type: "opencode-sdk", |
| 96 | + cwd, |
| 97 | + }); |
| 98 | + if (provider && "fetchModels" in provider) { |
| 99 | + modelDiscovery.push( |
| 100 | + (provider as { fetchModels: () => Promise<void> }) |
| 101 | + .fetchModels() |
| 102 | + .catch(() => {}), |
| 103 | + ); |
| 104 | + } |
| 105 | + registry.register(provider); |
| 106 | + } |
| 107 | + } catch { |
| 108 | + // OpenCode not available. |
| 109 | + } |
| 110 | + |
| 111 | + return { |
| 112 | + endpoints: ai.createAIEndpoints({ |
| 113 | + registry, |
| 114 | + sessionManager, |
| 115 | + getCwd: options.getCwd, |
| 116 | + beforeCapabilities: async () => { |
| 117 | + await Promise.allSettled(modelDiscovery); |
| 118 | + }, |
| 119 | + }), |
| 120 | + dispose: () => { |
| 121 | + sessionManager.disposeAll(); |
| 122 | + registry.disposeAll(); |
| 123 | + }, |
| 124 | + }; |
| 125 | + } catch { |
| 126 | + return null; |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +export async function handlePiAIRequest( |
| 131 | + req: IncomingMessage, |
| 132 | + res: ServerResponse, |
| 133 | + url: URL, |
| 134 | + runtime: PiAIRuntime | null, |
| 135 | +): Promise<boolean> { |
| 136 | + if (!url.pathname.startsWith("/api/ai/")) return false; |
| 137 | + |
| 138 | + if (!runtime) { |
| 139 | + if (url.pathname === "/api/ai/capabilities" && req.method === "GET") { |
| 140 | + json(res, { available: false, providers: [] }); |
| 141 | + return true; |
| 142 | + } |
| 143 | + json(res, { error: "AI backend not available" }, 503); |
| 144 | + return true; |
| 145 | + } |
| 146 | + |
| 147 | + const handler = runtime.endpoints[url.pathname]; |
| 148 | + if (!handler) { |
| 149 | + json(res, { error: "Not found" }, 404); |
| 150 | + return true; |
| 151 | + } |
| 152 | + |
| 153 | + try { |
| 154 | + const webReq = toWebRequest(req); |
| 155 | + const webRes = await handler(webReq); |
| 156 | + const headers: Record<string, string> = {}; |
| 157 | + webRes.headers.forEach((value, key) => { |
| 158 | + headers[key] = value; |
| 159 | + }); |
| 160 | + res.writeHead(webRes.status, headers); |
| 161 | + if (webRes.body) { |
| 162 | + Readable.fromWeb(webRes.body as any).pipe(res); |
| 163 | + } else { |
| 164 | + res.end(); |
| 165 | + } |
| 166 | + } catch (err) { |
| 167 | + json(res, { error: err instanceof Error ? err.message : "AI endpoint error" }, 500); |
| 168 | + } |
| 169 | + |
| 170 | + return true; |
| 171 | +} |
0 commit comments