/** * @license * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ import { existsSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import type { GeminiAskOptions, GeminiChatResponse } from "./types.ts"; export class GeminiPythonClient { private pythonPath: string | null = null; constructor(customPythonPath?: string) { if (customPythonPath && existsSync(customPythonPath)) { this.pythonPath = customPythonPath; } else { this.pythonPath = this.resolvePython(); } } resolvePython(): string | null { const candidates = [ join(homedir(), "aphrody", "py", ".venv", "Scripts", "python.exe"), join(homedir(), "aphrody", "py", ".venv", "bin", "python"), "python.exe", "python", "python3" ]; for (const c of candidates) { try { const proc = Bun.spawnSync([c, "--version"]); if (proc.exitCode === 0) { return c; } } catch { // try next } } return null; } isAvailable(): boolean { return this.pythonPath !== null; } getPythonPath(): string | null { return this.pythonPath; } async runScript(script: string, args: string[] = []): Promise<{ stdout: string; stderr: string; exitCode: number }> { if (!this.pythonPath) { throw new Error("No Python interpreter found in environment or aphrody/py/.venv"); } const proc = Bun.spawn([this.pythonPath, "-c", script, ...args], { env: { ...process.env, PYTHONIOENCODING: "utf-8" }, stdout: "pipe", stderr: "pipe", }); const [stdout, stderr] = await Promise.all([ new Response(proc.stdout).text(), new Response(proc.stderr).text(), ]); const exitCode = await proc.exited; return { stdout: stdout.trim(), stderr: stderr.trim(), exitCode }; } async ask(prompt: string, opts: GeminiAskOptions = {}): Promise { if (!this.pythonPath) { throw new Error("No Python interpreter found. Ensure aphrody/py/.venv exists or python is in PATH."); } const model = opts.model ?? "gemini-2.5-flash"; // Python runner script using google-genai or fallback const script = ` import sys import json import os prompt = sys.argv[1] model_name = sys.argv[2] api_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY") try: if api_key: from google import genai client = genai.Client(api_key=api_key) response = client.models.generate_content( model=model_name, contents=prompt, ) print(json.dumps({"status": "ok", "text": response.text})) else: # Check if antigravity or aphrody python module is available try: from aphrody import __version__ as aphrody_ver print(json.dumps({"status": "ok", "text": f"[Aphrody Python v{aphrody_ver}] Connected. Provide GEMINI_API_KEY for genai direct or use bxc rust/web engine."})) except ImportError: print(json.dumps({"status": "error", "error": "No GEMINI_API_KEY found and aphrody module not configured for cookie auth in python."})) except Exception as e: print(json.dumps({"status": "error", "error": str(e)})) `; const res = await this.runScript(script, [prompt, model]); if (res.exitCode !== 0) { throw new Error(`Python execution failed (exit ${res.exitCode}): ${res.stderr || res.stdout}`); } try { const data = JSON.parse(res.stdout); if (data.status === "error") { throw new Error(data.error); } return { text: data.text, engine: "python", model, raw: data, }; } catch { throw new Error(`Failed to parse Python response: ${res.stdout} (stderr: ${res.stderr})`); } } }