File size: 10,084 Bytes
88c4c60 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | "use server";
import { NextResponse } from "next/server";
import { exec } from "child_process";
import { promisify } from "util";
import fs from "fs/promises";
import path from "path";
import os from "os";
const execAsync = promisify(exec);
// OpenClaw 2026.5.x writes agents[].model as either a plain string
// (legacy) or as an object `{ primary, fallbacks }`. Normalize to the
// string id so downstream consumers can call `.startsWith()` safely.
const resolveAgentModel = (m) => {
if (typeof m === "string") return m;
if (m && typeof m === "object") return m.primary ?? "";
return "";
};
const getOpenClawDir = () => path.join(os.homedir(), ".openclaw");
const getOpenClawSettingsPath = () => path.join(getOpenClawDir(), "openclaw.json");
// Check if openclaw CLI is installed (via which/where or config file exists)
const checkOpenClawInstalled = async () => {
try {
const isWindows = os.platform() === "win32";
const command = isWindows ? "where openclaw" : "which openclaw";
// On Windows, inject %APPDATA%\npm into PATH so npm global packages are found
const env = isWindows
? { ...process.env, PATH: `${process.env.APPDATA}\\npm;${process.env.PATH}` }
: process.env;
await execAsync(command, { windowsHide: true, env });
return true;
} catch {
try {
await fs.access(getOpenClawSettingsPath());
return true;
} catch {
return false;
}
}
};
// Read current settings.json
const readSettings = async () => {
try {
const settingsPath = getOpenClawSettingsPath();
const content = await fs.readFile(settingsPath, "utf-8");
return JSON.parse(content);
} catch (error) {
if (error.code === "ENOENT") return null;
throw error;
}
};
// Check if settings has 9Router config
const has9RouterConfig = (settings) => {
if (!settings || !settings.models || !settings.models.providers) return false;
return !!settings.models.providers["9router"];
};
// Read per-agent models.json and return current model id (without "9router/" prefix)
const readAgentModel = async (agentDir) => {
try {
const modelsPath = path.join(agentDir, "models.json");
const content = await fs.readFile(modelsPath, "utf-8");
const data = JSON.parse(content);
const models = data?.providers?.["9router"]?.models;
return models?.[0]?.id || null;
} catch {
return null;
}
};
// GET - Check openclaw CLI and read current settings
export async function GET() {
try {
const isInstalled = await checkOpenClawInstalled();
if (!isInstalled) {
return NextResponse.json({
installed: false,
settings: null,
message: "Open Claw CLI is not installed",
});
}
const settings = await readSettings();
// Enrich agents list with current per-agent model from models.json.
// Coerce agent.model to its string id when OpenClaw stores it as
// `{ primary, fallbacks }` so downstream `.startsWith()` calls work.
const agentList = settings?.agents?.list || [];
const enrichedAgents = await Promise.all(
agentList.map(async (agent) => {
const agentModel = agent.agentDir ? await readAgentModel(agent.agentDir) : null;
return { ...agent, model: resolveAgentModel(agent.model), currentModel: agentModel };
})
);
return NextResponse.json({
installed: true,
settings,
agents: enrichedAgents,
has9Router: has9RouterConfig(settings),
settingsPath: getOpenClawSettingsPath(),
});
} catch (error) {
console.log("Error checking openclaw settings:", error);
return NextResponse.json({ error: "Failed to check openclaw settings" }, { status: 500 });
}
}
// Write per-agent models.json
const writeAgentModels = async (agentDir, model, baseUrl, apiKey) => {
await fs.mkdir(agentDir, { recursive: true });
const modelsPath = path.join(agentDir, "models.json");
let existing = {};
try {
const content = await fs.readFile(modelsPath, "utf-8");
existing = JSON.parse(content);
} catch { /* No existing */ }
if (!existing.providers) existing.providers = {};
existing.providers["9router"] = {
baseUrl,
apiKey: apiKey || "your_api_key",
api: "openai-completions",
models: [{ id: model, name: model.split("/").pop() || model }],
};
await fs.writeFile(modelsPath, JSON.stringify(existing, null, 2));
};
// POST - Update 9Router settings (merge with existing settings)
export async function POST(request) {
try {
// agentModels: { [agentId]: modelId } for per-agent override
const { baseUrl, apiKey, model, agentModels = {} } = await request.json();
if (!baseUrl || !model) {
return NextResponse.json({ error: "baseUrl and model are required" }, { status: 400 });
}
const openclawDir = getOpenClawDir();
const settingsPath = getOpenClawSettingsPath();
await fs.mkdir(openclawDir, { recursive: true });
let settings = {};
try {
const existingSettings = await fs.readFile(settingsPath, "utf-8");
settings = JSON.parse(existingSettings);
} catch { /* No existing settings */ }
if (!settings.agents) settings.agents = {};
if (!settings.agents.defaults) settings.agents.defaults = {};
if (!settings.agents.defaults.model) settings.agents.defaults.model = {};
if (!settings.agents.defaults.models) settings.agents.defaults.models = {};
if (!settings.models) settings.models = {};
if (!settings.models.providers) settings.models.providers = {};
const normalizedBaseUrl = baseUrl.endsWith("/v1") ? baseUrl : `${baseUrl}/v1`;
const fullModelId = `9router/${model}`;
// Remove all old 9router/* entries from agents.defaults.models
Object.keys(settings.agents.defaults.models)
.filter((k) => k.startsWith("9router/"))
.forEach((k) => { delete settings.agents.defaults.models[k]; });
// Update default model
settings.agents.defaults.model.primary = fullModelId;
// Collect all unique models (default + per-agent)
const allModelIds = new Set([model]);
Object.values(agentModels).forEach((m) => { if (m) allModelIds.add(m); });
// Add fresh 9router models to allowlist
allModelIds.forEach((m) => {
settings.agents.defaults.models[`9router/${m}`] = {};
});
// Remove old 9router model from each agent in agents.list. The
// model field may be a plain string or `{ primary, fallbacks }`.
if (settings.agents.list) {
settings.agents.list = settings.agents.list.map((agent) => {
if (resolveAgentModel(agent.model).startsWith("9router/")) {
const { model: _, ...rest } = agent;
return rest;
}
return agent;
});
}
// Update models.providers.9router with all models
settings.models.providers["9router"] = {
baseUrl: normalizedBaseUrl,
apiKey: apiKey || "your_api_key",
api: "openai-completions",
models: [...allModelIds].map((m) => ({ id: m, name: m.split("/").pop() || m })),
};
// Set per-agent model in agents.list and write models.json
if (settings.agents.list) {
settings.agents.list = settings.agents.list.map((agent) => {
const agentModel = agentModels[agent.id];
if (agentModel) return { ...agent, model: `9router/${agentModel}` };
return agent;
});
// Write per-agent models.json for agents with agentDir
await Promise.all(
settings.agents.list.map(async (agent) => {
if (!agent.agentDir) return;
const agentModel = agentModels[agent.id];
const modelToWrite = agentModel || model; // fallback to default
await writeAgentModels(agent.agentDir, modelToWrite, normalizedBaseUrl, apiKey);
})
);
}
await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2));
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 });
}
}
// DELETE - Remove 9Router settings only (keep other settings)
export async function DELETE() {
try {
const settingsPath = getOpenClawSettingsPath();
// Read existing settings
let settings = {};
try {
const existingSettings = await fs.readFile(settingsPath, "utf-8");
settings = JSON.parse(existingSettings);
} catch (error) {
if (error.code === "ENOENT") {
return NextResponse.json({
success: true,
message: "No settings file to reset",
});
}
throw error;
}
// Remove 9Router from models.providers
if (settings.models && settings.models.providers) {
delete settings.models.providers["9router"];
// Remove providers object if empty
if (Object.keys(settings.models.providers).length === 0) {
delete settings.models.providers;
}
}
// Remove 9router models from agents.defaults.models allowlist
if (settings.agents?.defaults?.models) {
const keysToRemove = Object.keys(settings.agents.defaults.models).filter((k) => k.startsWith("9router/"));
for (const key of keysToRemove) {
delete settings.agents.defaults.models[key];
}
if (Object.keys(settings.agents.defaults.models).length === 0) {
delete settings.agents.defaults.models;
}
}
// Reset agents.defaults.model.primary if it uses 9router
if (settings.agents?.defaults?.model?.primary?.startsWith("9router/")) {
delete settings.agents.defaults.model.primary;
}
// Write updated settings
await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2));
return NextResponse.json({
success: true,
message: "9Router settings removed successfully",
});
} catch (error) {
console.log("Error resetting openclaw settings:", error);
return NextResponse.json({ error: "Failed to reset openclaw settings" }, { status: 500 });
}
}
|