import { NextResponse } from "next/server"; import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs"; import { join, dirname } from "path"; import { getAgentDir } from "@earendil-works/pi-coding-agent"; import { invalidateModelsCache } from "@/lib/models-cache"; export const dynamic = "force-dynamic"; function getModelsPath(): string { return join(getAgentDir(), "models.json"); } function readModelsJson(): Record { const path = getModelsPath(); if (!existsSync(path)) return { providers: {} }; try { return JSON.parse(readFileSync(path, "utf8")) as Record; } catch { return { providers: {} }; } } function writeModelsJson(data: Record): void { const path = getModelsPath(); const dir = dirname(path); if (!existsSync(dir)) mkdirSync(dir, { recursive: true }); writeFileSync(path, JSON.stringify(data, null, 2), "utf8"); } export async function GET() { return NextResponse.json(readModelsJson()); } export async function PUT(req: Request) { try { const body = await req.json() as Record; writeModelsJson(body); invalidateModelsCache(); return NextResponse.json({ success: true }); } catch (error) { return NextResponse.json({ error: String(error) }, { status: 500 }); } }