| "use server";
|
|
|
| import { NextResponse } from "next/server";
|
| import fs from "fs/promises";
|
| import path from "path";
|
| import { requireCliToolsAuth } from "@/lib/api/requireCliToolsAuth";
|
| import {
|
| ensureCliConfigWriteAllowed,
|
| getCliPrimaryConfigPath,
|
| getCliRuntimeStatus,
|
| } from "@/shared/services/cliRuntime";
|
| import { createBackup } from "@/shared/services/backupService";
|
| import { saveCliToolLastConfigured, deleteCliToolLastConfigured } from "@/lib/db/cliToolState";
|
| import { cliModelConfigSchema } from "@/shared/validation/schemas";
|
| import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
|
| import { resolveApiKey } from "@/shared/services/apiKeyResolver";
|
|
|
| const getOpenClawSettingsPath = () => getCliPrimaryConfigPath("openclaw");
|
| const getOpenClawDir = () => path.dirname(getOpenClawSettingsPath());
|
|
|
|
|
| const readSettings = async () => {
|
| try {
|
| const settingsPath = getOpenClawSettingsPath();
|
| const content = await fs.readFile(settingsPath, "utf-8");
|
| return JSON.parse(content);
|
| } catch (error: any) {
|
| if (error.code === "ENOENT") return null;
|
| throw error;
|
| }
|
| };
|
|
|
|
|
| const hasOmniRouteConfig = (settings: any) => {
|
| if (!settings || !settings.models || !settings.models.providers) return false;
|
| return !!settings.models.providers["omniroute"];
|
| };
|
|
|
|
|
| export async function GET(request: Request) {
|
| const authError = await requireCliToolsAuth(request);
|
| if (authError) return authError;
|
|
|
| try {
|
| const runtime = await getCliRuntimeStatus("openclaw");
|
|
|
| if (!runtime.installed || !runtime.runnable) {
|
| return NextResponse.json({
|
| installed: runtime.installed,
|
| runnable: runtime.runnable,
|
| command: runtime.command,
|
| commandPath: runtime.commandPath,
|
| runtimeMode: runtime.runtimeMode,
|
| reason: runtime.reason,
|
| settings: null,
|
| message:
|
| runtime.installed && !runtime.runnable
|
| ? "Open Claw CLI is installed but not runnable"
|
| : "Open Claw CLI is not installed",
|
| });
|
| }
|
|
|
| const settings = await readSettings();
|
|
|
| return NextResponse.json({
|
| installed: runtime.installed,
|
| runnable: runtime.runnable,
|
| command: runtime.command,
|
| commandPath: runtime.commandPath,
|
| runtimeMode: runtime.runtimeMode,
|
| reason: runtime.reason,
|
| settings,
|
| hasOmniRoute: hasOmniRouteConfig(settings),
|
| settingsPath: getOpenClawSettingsPath(),
|
| });
|
| } catch (error) {
|
| console.log("Error checking openclaw settings:", error);
|
| return NextResponse.json({ error: "Failed to check openclaw settings" }, { status: 500 });
|
| }
|
| }
|
|
|
|
|
| export async function POST(request: Request) {
|
| const authError = await requireCliToolsAuth(request);
|
| if (authError) return authError;
|
|
|
| let rawBody;
|
| try {
|
| rawBody = await request.json();
|
| } catch {
|
| return NextResponse.json(
|
| {
|
| error: {
|
| message: "Invalid request",
|
| details: [{ field: "body", message: "Invalid JSON body" }],
|
| },
|
| },
|
| { status: 400 }
|
| );
|
| }
|
|
|
| try {
|
| const writeGuard = ensureCliConfigWriteAllowed();
|
| if (writeGuard) {
|
| return NextResponse.json({ error: writeGuard }, { status: 403 });
|
| }
|
|
|
|
|
| const keyId = typeof rawBody?.keyId === "string" ? rawBody.keyId.trim() : null;
|
|
|
| const validation = validateBody(cliModelConfigSchema, rawBody);
|
| if (isValidationFailure(validation)) {
|
| return NextResponse.json({ error: validation.error }, { status: 400 });
|
| }
|
| let { baseUrl, model } = validation.data;
|
| let apiKey = await resolveApiKey(keyId, validation.data.apiKey);
|
|
|
| const openclawDir = getOpenClawDir();
|
| const settingsPath = getOpenClawSettingsPath();
|
|
|
|
|
| await fs.mkdir(openclawDir, { recursive: true });
|
|
|
|
|
| await createBackup("openclaw", settingsPath);
|
|
|
|
|
| let settings: Record<string, any> = {};
|
| try {
|
| const existingSettings = await fs.readFile(settingsPath, "utf-8");
|
| settings = JSON.parse(existingSettings);
|
| } catch {
|
|
|
| }
|
|
|
|
|
| if (!settings.agents) settings.agents = {};
|
| if (!settings.agents.defaults) settings.agents.defaults = {};
|
| if (!settings.agents.defaults.model) settings.agents.defaults.model = {};
|
| if (!settings.models) settings.models = {};
|
| if (!settings.models.providers) settings.models.providers = {};
|
|
|
|
|
| const normalizedBaseUrl = baseUrl.endsWith("/v1") ? baseUrl : `${baseUrl}/v1`;
|
|
|
|
|
| settings.agents.defaults.model.primary = `omniroute/${model}`;
|
|
|
|
|
| settings.models.providers["omniroute"] = {
|
| baseUrl: normalizedBaseUrl,
|
| apiKey: apiKey || "your_api_key",
|
| api: "openai-completions",
|
| models: [
|
| {
|
| id: model,
|
| name: model.split("/").pop() || model,
|
| },
|
| ],
|
| };
|
|
|
|
|
| await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2));
|
|
|
|
|
| try {
|
| saveCliToolLastConfigured("openclaw");
|
| } catch {
|
|
|
| }
|
|
|
| return NextResponse.json({
|
| success: true,
|
| message: "Open Claw settings applied successfully!",
|
| settingsPath,
|
| });
|
| } catch (error) {
|
| console.log("Error updating openclaw settings:", error);
|
| return NextResponse.json({ error: "Failed to update openclaw settings" }, { status: 500 });
|
| }
|
| }
|
|
|
|
|
| export async function DELETE(request: Request) {
|
| const authError = await requireCliToolsAuth(request);
|
| if (authError) return authError;
|
|
|
| try {
|
| const writeGuard = ensureCliConfigWriteAllowed();
|
| if (writeGuard) {
|
| return NextResponse.json({ error: writeGuard }, { status: 403 });
|
| }
|
|
|
| const settingsPath = getOpenClawSettingsPath();
|
|
|
|
|
| await createBackup("openclaw", settingsPath);
|
|
|
|
|
| let settings: Record<string, any> = {};
|
| try {
|
| const existingSettings = await fs.readFile(settingsPath, "utf-8");
|
| settings = JSON.parse(existingSettings);
|
| } catch (error: any) {
|
| if (error.code === "ENOENT") {
|
| return NextResponse.json({
|
| success: true,
|
| message: "No settings file to reset",
|
| });
|
| }
|
| throw error;
|
| }
|
|
|
|
|
| if (settings.models && settings.models.providers) {
|
| delete settings.models.providers["omniroute"];
|
|
|
|
|
| if (Object.keys(settings.models.providers).length === 0) {
|
| delete settings.models.providers;
|
| }
|
| }
|
|
|
|
|
| if (settings.agents?.defaults?.model?.primary?.startsWith("omniroute/")) {
|
| delete settings.agents.defaults.model.primary;
|
| }
|
|
|
|
|
| await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2));
|
|
|
|
|
| try {
|
| deleteCliToolLastConfigured("openclaw");
|
| } catch {
|
|
|
| }
|
|
|
| return NextResponse.json({
|
| success: true,
|
| message: "OmniRoute settings removed successfully",
|
| });
|
| } catch (error) {
|
| console.log("Error resetting openclaw settings:", error);
|
| return NextResponse.json({ error: "Failed to reset openclaw settings" }, { status: 500 });
|
| }
|
| }
|
|
|