Release / release (push) Successful in 3m0s
Scopes deployments:read/write and benchmarks:read/run; /api/v1 endpoints for runtimes, deployments (create with dry run, edit, start, stop, delete own ones), benchmark runs, A/B, sweeps and comparisons; ?wait= on all status endpoints. Guardrails: approval, agent deployments at once, one GPU job at a time, time limits, sweep variants, runtime and argument allowlists, host port range, memory/CPU caps, protected deployments with a VRAM check. Requested-by filters, approval bars, per-token activity log, scope editing, docs/agent/SKILL-tuning.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
171 lines
8.2 KiB
TypeScript
171 lines
8.2 KiB
TypeScript
import "server-only";
|
||
import { eq } from "drizzle-orm";
|
||
import { db } from "@/lib/db/client";
|
||
import { type HardwareOverrides, settings } from "@/lib/db/schema";
|
||
import { APPROVAL_MODES, type Guardrails, parseGuardrails } from "@/lib/agent-guardrails";
|
||
import { parseTuning, TUNING_KEY, type TuningGuardrails } from "@/lib/agent-tuning";
|
||
import { isLabelColor } from "@/lib/colors";
|
||
import { HARDWARE_OVERRIDES_KEY, HardwareOverrideError, parseOverrides, validateOverrides } from "@/lib/hardware";
|
||
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles";
|
||
import { MIN_SPEED_LIMIT, parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit";
|
||
import { DEFAULT_RECOMMENDED_ROLES, RECOMMENDABLE_ROLES } from "@/lib/recommend";
|
||
|
||
const FILE_ROLES_KEY = "labels.fileRoles";
|
||
export const FILE_ROLE_LABEL_MAX = 24;
|
||
|
||
type StoredRoles = Partial<Record<FileRole, { label?: string; color?: string }>>;
|
||
|
||
async function read<T>(key: string): Promise<T | null> {
|
||
try {
|
||
const row = await db().query.settings.findFirst({ where: eq(settings.key, key) });
|
||
return (row?.value as T) ?? null;
|
||
} catch {
|
||
return null; // table missing before the first migration
|
||
}
|
||
}
|
||
|
||
async function write(key: string, value: unknown) {
|
||
await db()
|
||
.insert(settings)
|
||
.values({ key, value })
|
||
.onConflictDoUpdate({ target: settings.key, set: { value, updatedAt: new Date() } });
|
||
}
|
||
|
||
/** Label text and color per file role: defaults merged with what was saved in Settings. */
|
||
export async function getFileRoleStyles(): Promise<FileRoleStyles> {
|
||
const stored = (await read<StoredRoles>(FILE_ROLES_KEY)) ?? {};
|
||
const out = {} as FileRoleStyles;
|
||
for (const role of FILE_ROLE_ORDER) {
|
||
const s = stored[role] ?? {};
|
||
out[role] = {
|
||
label: typeof s.label === "string" && s.label.trim() ? s.label.trim() : FILE_ROLES[role].label,
|
||
color: isLabelColor(s.color) ? s.color : FILE_ROLES[role].color,
|
||
};
|
||
}
|
||
return out;
|
||
}
|
||
|
||
export class SettingsError extends Error {
|
||
status = 400;
|
||
code = "invalid";
|
||
}
|
||
|
||
/** Save label/color overrides. Values equal to the default are not stored. */
|
||
export async function saveFileRoleStyles(input: Record<string, { label?: unknown; color?: unknown }>): Promise<FileRoleStyles> {
|
||
const stored: StoredRoles = {};
|
||
for (const [role, v] of Object.entries(input)) {
|
||
if (!(role in FILE_ROLES)) throw new SettingsError(`Unknown file label "${role}".`);
|
||
const def = FILE_ROLES[role as FileRole];
|
||
const entry: { label?: string; color?: string } = {};
|
||
if (v.label !== undefined) {
|
||
if (typeof v.label !== "string" || !v.label.trim() || v.label.trim().length > FILE_ROLE_LABEL_MAX) {
|
||
throw new SettingsError(`Label for "${role}" must be 1–${FILE_ROLE_LABEL_MAX} characters.`);
|
||
}
|
||
if (v.label.trim() !== def.label) entry.label = v.label.trim();
|
||
}
|
||
if (v.color !== undefined) {
|
||
if (!isLabelColor(v.color)) throw new SettingsError(`Unknown color "${String(v.color)}".`);
|
||
if (v.color !== def.color) entry.color = v.color;
|
||
}
|
||
if (entry.label || entry.color) stored[role as FileRole] = entry;
|
||
}
|
||
await write(FILE_ROLES_KEY, stored);
|
||
return getFileRoleStyles();
|
||
}
|
||
|
||
const RECOMMENDED_KEY = "downloads.recommendedRoles";
|
||
|
||
/** File kinds picked automatically along with model weights (Settings → Downloads). */
|
||
export async function getRecommendedRoles(): Promise<FileRole[]> {
|
||
const stored = await read<unknown>(RECOMMENDED_KEY);
|
||
if (!Array.isArray(stored)) return DEFAULT_RECOMMENDED_ROLES;
|
||
return RECOMMENDABLE_ROLES.filter((r) => stored.includes(r));
|
||
}
|
||
|
||
export async function saveRecommendedRoles(roles: string[]): Promise<FileRole[]> {
|
||
const unknown = roles.find((r) => !RECOMMENDABLE_ROLES.includes(r as FileRole));
|
||
if (unknown) throw new SettingsError(`"${unknown}" can't be recommended.`);
|
||
await write(RECOMMENDED_KEY, RECOMMENDABLE_ROLES.filter((r) => roles.includes(r)));
|
||
return getRecommendedRoles();
|
||
}
|
||
|
||
/** Download speed limit in bytes per second (Settings → Downloads), or null for no limit. */
|
||
export async function getDownloadSpeedLimit(): Promise<number | null> {
|
||
return parseSpeedLimit(await read<unknown>(SPEED_LIMIT_KEY));
|
||
}
|
||
|
||
export async function saveDownloadSpeedLimit(bytesPerSecond: number | null): Promise<number | null> {
|
||
if (bytesPerSecond != null && (!Number.isFinite(bytesPerSecond) || bytesPerSecond < MIN_SPEED_LIMIT)) {
|
||
throw new SettingsError("The speed limit must be at least 0.1 MB/s, or empty for no limit.");
|
||
}
|
||
if (bytesPerSecond == null) await db().delete(settings).where(eq(settings.key, SPEED_LIMIT_KEY));
|
||
else await write(SPEED_LIMIT_KEY, Math.round(bytesPerSecond));
|
||
return getDownloadSpeedLimit();
|
||
}
|
||
|
||
const GUARDRAILS_KEY = "agent.guardrails";
|
||
|
||
/** Limits for downloads requested through the API (Settings → API tokens). */
|
||
export async function getGuardrails(): Promise<Guardrails> {
|
||
return parseGuardrails(await read<unknown>(GUARDRAILS_KEY));
|
||
}
|
||
|
||
export async function saveGuardrails(input: Partial<Guardrails>): Promise<Guardrails> {
|
||
const next = { ...(await getGuardrails()), ...input };
|
||
if (!APPROVAL_MODES.includes(next.approvalMode)) throw new SettingsError(`Approval mode must be one of: ${APPROVAL_MODES.join(", ")}.`);
|
||
if (!(next.maxRequestBytes >= 1_000_000)) throw new SettingsError("Max size per request must be at least 0.001 GB.");
|
||
if (!(next.minFreeBytes >= 0)) throw new SettingsError("Minimum free space can't be negative.");
|
||
if (!Number.isInteger(next.maxOpenJobs) || next.maxOpenJobs < 1 || next.maxOpenJobs > 50) throw new SettingsError("Max agent jobs at once must be 1–50.");
|
||
const parsed = parseGuardrails(next);
|
||
if (parsed.allowedAuthors.length !== next.allowedAuthors.length) throw new SettingsError("The author allowlist contains an invalid name.");
|
||
await write(GUARDRAILS_KEY, parsed);
|
||
return parsed;
|
||
}
|
||
|
||
/** Manual hardware values (Settings → Hardware) that replace what detection reports. */
|
||
export async function getHardwareOverrides(): Promise<HardwareOverrides> {
|
||
return parseOverrides(await read<unknown>(HARDWARE_OVERRIDES_KEY));
|
||
}
|
||
|
||
export async function saveHardwareOverrides(input: unknown): Promise<HardwareOverrides> {
|
||
let next: HardwareOverrides;
|
||
try {
|
||
next = validateOverrides(input);
|
||
} catch (err) {
|
||
if (err instanceof HardwareOverrideError) throw new SettingsError(err.message);
|
||
throw err;
|
||
}
|
||
if (Object.keys(next).length === 0) await db().delete(settings).where(eq(settings.key, HARDWARE_OVERRIDES_KEY));
|
||
else await write(HARDWARE_OVERRIDES_KEY, next);
|
||
return next;
|
||
}
|
||
|
||
/** Limits for deployments and benchmarks requested through the API (Settings → API tokens). */
|
||
export async function getTuning(): Promise<TuningGuardrails> {
|
||
return parseTuning(await read<unknown>(TUNING_KEY));
|
||
}
|
||
|
||
export async function saveTuning(input: Partial<TuningGuardrails>): Promise<TuningGuardrails> {
|
||
const next = { ...(await getTuning()), ...input };
|
||
if (!APPROVAL_MODES.includes(next.approvalMode)) throw new SettingsError(`Approval mode must be one of: ${APPROVAL_MODES.join(", ")}.`);
|
||
const intIn = (v: number, min: number, max: number, what: string) => {
|
||
if (!Number.isInteger(v) || v < min || v > max) throw new SettingsError(`${what} must be ${min}–${max}.`);
|
||
};
|
||
intIn(next.maxAgentDeployments, 1, 16, "Agent deployments at once");
|
||
intIn(next.maxRunMinutes, 1, 24 * 60, "Max minutes per run");
|
||
intIn(next.maxSweepMinutes, 1, 7 * 24 * 60, "Max minutes per sweep");
|
||
intIn(next.maxSweepVariants, 2, 16, "Max sweep variants");
|
||
const r = next.hostPortRange;
|
||
if (r && (!Number.isInteger(r.from) || !Number.isInteger(r.to) || r.from < 1024 || r.to > 65_535 || r.from > r.to)) {
|
||
throw new SettingsError("Host port range must be within 1024–65535, from ≤ to.");
|
||
}
|
||
if (next.maxMemoryMb != null && !(next.maxMemoryMb >= 256)) throw new SettingsError("Memory cap must be at least 256 MiB, or empty.");
|
||
if (next.maxCpus != null && !(next.maxCpus >= 0.1)) throw new SettingsError("CPU cap must be at least 0.1 cores, or empty.");
|
||
const parsed = parseTuning(next);
|
||
for (const engine of ["llama.cpp", "vllm"] as const) {
|
||
if (parsed.allowedArgs[engine].length !== new Set(next.allowedArgs[engine]).size) throw new SettingsError(`The ${engine} argument allowlist contains something that isn't a flag.`);
|
||
}
|
||
await write(TUNING_KEY, parsed);
|
||
return parsed;
|
||
}
|