router.push("/")} />}
-
- {showProgress && !pending && }
+ {showProgress && }
{latest?.state === "failed" && latest.errorMessage && (
diff --git a/src/app/(app)/[org]/[repo]/page.tsx b/src/app/(app)/[org]/[repo]/page.tsx
index f725da3..43a4edc 100644
--- a/src/app/(app)/[org]/[repo]/page.tsx
+++ b/src/app/(app)/[org]/[repo]/page.tsx
@@ -9,8 +9,7 @@ import {
LanguagesIcon,
ListChecksIcon,
MessagesSquareIcon,
- PlusIcon,
- RocketIcon,
+ GaugeIcon,
ScaleIcon,
SparklesIcon,
TriangleAlertIcon,
@@ -19,15 +18,15 @@ import type { Metadata } from "next";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { CopyButton } from "@/components/copy-button";
-import { DeploymentStateBadge } from "@/components/deployment-state";
+import { BenchmarkStateBadge } from "@/components/benchmark-state";
import { HubStateBadge } from "@/components/hub-state-badge";
import { LocalTime } from "@/components/local-time";
import { ModelStatusBadge } from "@/components/model-status-badge";
-import { RequestedByBadge } from "@/components/requested-by-badge";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { formatBytes, shortSha } from "@/lib/format";
-import { deploymentsByModel, listDeployableModels } from "@/lib/deployments";
+import { listBenchmarks } from "@/lib/benchmarks";
+import { headline, targetName } from "@/lib/benchmark-view";
import { fetchModelCard } from "@/lib/hub/client";
import { modelFamilies } from "@/lib/hub/metadata";
import { listModelJobs } from "@/lib/jobs";
@@ -102,17 +101,14 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
const hubTags = model.hubTags ?? [];
const hubMissing = model.hubState === "repo_missing" || model.hubState === "commit_missing";
- const [tags, related, card, worker, recentJobs, byModel, deployable] = await Promise.all([
+ const [tags, related, card, worker, recentJobs, runs] = await Promise.all([
modelTagList(model.id),
relatedModels(model.id, baseModels),
tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined),
getWorkerStatus(),
listModelJobs(model.id, 1),
- deploymentsByModel(),
- listDeployableModels(),
+ listBenchmarks({ modelId: model.id }),
]);
- const modelDeployments = byModel.get(model.id) ?? [];
- const canDeploy = deployable.some((m) => m.id === model.id);
const update =
!hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha
? model.updateDiff
@@ -146,22 +142,12 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
-
{update && (
update available
)}
- {canDeploy && (
-
-
- Deploy
-
- )}
- {(modelDeployments.length > 0 || canDeploy) && (
-
-
- {modelDeployments.length === 0 ? (
-
Not deployed yet.
- ) : (
- modelDeployments.map((d) => (
-
+ {runs.length > 0 && (
+
+
+ {runs.slice(0, 5).map((r) => {
+ const h = headline(r.summary);
+ return (
+
- {d.name}
- {d.runtimeName}
+ {r.label ?? targetName(r.snapshot)}
+
+ {r.kind === "eval" ? (r.quality?.score != null ? `quality ${r.quality.score}%` : "quality eval") : h.decode != null ? `${h.decode.toFixed(1)} t/s decode` : r.kind === "ab" ? "A/B" : "run"}
+
-
+
- ))
- )}
- {canDeploy && (
-
-
- New deployment
-
- )}
+ );
+ })}
+
+ All runs of this model →
+
)}
diff --git a/src/app/(app)/benchmarks/[id]/ab-report.tsx b/src/app/(app)/benchmarks/[id]/ab-report.tsx
index 81c8e97..b633451 100644
--- a/src/app/(app)/benchmarks/[id]/ab-report.tsx
+++ b/src/app/(app)/benchmarks/[id]/ab-report.tsx
@@ -1,7 +1,6 @@
import { TriangleAlertIcon } from "lucide-react";
-import { BenchmarkResources } from "@/components/benchmark-resources";
import { abCaveats, abHeadline, abMethod, abSummaryText, halfWidth } from "@/lib/ab-report";
-import { CONFIG_ROWS } from "@/lib/benchmark-view";
+import { CONFIG_ROWS, targetName } from "@/lib/benchmark-view";
import type { PairedResult } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
import type { ListRow } from "../benchmark-list";
@@ -75,8 +74,8 @@ export function AbReport({ run }: { run: ListRow }) {
BetterBench {ab.betterbenchVersion} · paired A/B · {ab.pairs} pairs
-
{run.label ?? `${a.deploymentName} vs ${b.deploymentName}`}
-
{abSummaryText(ab, a.deploymentName, b.deploymentName)}
+
{run.label ?? `${targetName(a)} vs ${targetName(b)}`}
+
{abSummaryText(ab, targetName(a), targetName(b))}
@@ -99,8 +98,8 @@ export function AbReport({ run }: { run: ListRow }) {
-
-
+
+
Pairs
{ab.pairs}
@@ -136,8 +135,8 @@ export function AbReport({ run }: { run: ListRow }) {
- A · {a.deploymentName}
- B · {b.deploymentName}
+ A · {targetName(a)}
+ B · {targetName(b)}
@@ -161,13 +160,6 @@ export function AbReport({ run }: { run: ListRow }) {
{same.length > 0 && Same on both: {same.map((x) => `${x.row.label.toLowerCase()} ${x.va}`).join(" · ")}.
}
- {run.resources && (
-
- )}
-
Method
diff --git a/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx b/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx
index d144407..c073f51 100644
--- a/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx
+++ b/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx
@@ -31,10 +31,8 @@ import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { reportSummary, weightsLabel } from "@/lib/benchmark-report";
-import { CONFIG_ROWS, describeSettings } from "@/lib/benchmark-view";
+import { CONFIG_ROWS, describeSettings, engineName, isEndpointSnapshot, modelName, targetName } from "@/lib/benchmark-view";
import type { ListRow } from "../benchmark-list";
-import { AgentApprovalBar } from "@/components/approval-bar";
-import { RequestedByBadge } from "@/components/requested-by-badge";
import { RunMetaCard } from "@/components/run-meta";
import { cancelBenchmark, deleteBenchmark, describeBenchmark, renameBenchmark } from "../actions";
import { AbReport } from "./ab-report";
@@ -63,7 +61,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
const [now, setNow] = useState(() => Date.now());
const [label, setLabel] = useState(initial.label ?? "");
const [description, setDescription] = useState(initial.description ?? "");
- const active = r.state === "pending_approval" || r.state === "queued" || r.state === "running";
+ const active = r.state === "queued" || r.state === "running";
useEffect(() => {
if (!active) return;
@@ -78,13 +76,14 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
}, [active, r.id]);
async function again() {
- if (!r.deploymentId) return;
+ if (!r.endpointId) return;
const res = await fetch("/api/benchmarks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
- deploymentId: r.deploymentId,
- deploymentBId: r.kind === "ab" ? r.deploymentBId : null,
+ endpointId: r.endpointId,
+ endpointBId: r.kind === "ab" ? r.endpointBId : null,
+ model: modelName(r.snapshot),
kind: r.kind,
label: r.label,
description: r.description,
@@ -100,7 +99,18 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
}
const s = r.snapshot;
+ const sB = r.snapshotB;
const sum = r.summary;
+ // Runs from before 0.15 measured a deployment (gone now); newer ones an endpoint.
+ const legacy = !isEndpointSnapshot(s);
+ const endpointLink = (id: string | null, name: string) =>
+ legacy ? name : id ? (
+
+ {name}
+
+ ) : (
+ `${name} (deleted)`
+ );
const took = duration(r.startedAt, r.finishedAt, now);
return (
@@ -110,10 +120,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
- {r.label ??
- (r.kind === "ab"
- ? `${s.deploymentName} vs ${r.snapshotB?.deploymentName}`
- : s.deploymentName)}
+ {r.label ?? (r.kind === "ab" && sB ? `${targetName(s)} vs ${targetName(sB)}` : targetName(s))}
{r.kind === "ab" && (
@@ -124,54 +131,21 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
state={r.state}
cancelling={!!r.cancelRequestedAt}
/>
-
- {r.deploymentId ? (
-
- {s.deploymentName}
-
- ) : (
- `${s.deploymentName} (deleted)`
- )}{" "}
- ·{" "}
+ {endpointLink(r.endpointId, targetName(s))} ·{" "}
{r.modelId ? (
-
- {s.repoId}
+
+ {modelName(s)}
) : (
- s.repoId
+ modelName(s)
)}{" "}
- · {s.runtimeName}
- {r.kind === "ab" && r.snapshotB && (
+ · {engineName(s)}
+ {r.kind === "ab" && sB && (
<>
{" "}
- · B:{" "}
- {r.deploymentBId ? (
-
- {r.snapshotB.deploymentName}
-
- ) : (
- r.snapshotB.deploymentName
- )}
- >
- )}
- {r.sweepId && (
- <>
- {" "}
- ·{" "}
-
- part of a sweep
-
+ · B: {endpointLink(r.endpointBId, targetName(sB))} ({engineName(sB)})
>
)}
@@ -218,12 +192,12 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
Cancel
) : (
- r.deploymentId &&
- !r.sweepId && (
+ r.endpointId &&
+ (r.kind !== "ab" || r.endpointBId) && (
Run again
@@ -270,13 +244,6 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
- {r.state === "pending_approval" && (
-
- )}
{r.error && (
@@ -308,7 +275,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
{r.kind === "run" && r.state === "completed" && r.summary && (
)}
@@ -360,7 +327,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
{r.kind !== "ab" && (
- Settings measured
+ {legacy ? "Settings measured" : "Setup"}
@@ -374,15 +341,20 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
);
})}
-
-
- Command
-
+ {!isEndpointSnapshot(s) && (
+
+
+ Command
+
+
+
+ {s.command}
+
-
- {s.command}
-
-
+ )}
+ {isEndpointSnapshot(s) && s.hardware.description && (
+
{s.hardware.description}
+ )}
{sum && (
BetterBench {sum.betterbenchVersion} · corpus v
diff --git a/src/app/(app)/benchmarks/[id]/benchmark-report.tsx b/src/app/(app)/benchmarks/[id]/benchmark-report.tsx
index b318b81..332238f 100644
--- a/src/app/(app)/benchmarks/[id]/benchmark-report.tsx
+++ b/src/app/(app)/benchmarks/[id]/benchmark-report.tsx
@@ -2,10 +2,9 @@
import { TriangleAlertIcon } from "lucide-react";
import { BarChart } from "@/components/bar-chart";
-import { BenchmarkResources } from "@/components/benchmark-resources";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { f0, f1, isBatched, reportCaveats, reportMethod, reportSubtitle, reportSummary, undersampled, weightsLabel } from "@/lib/benchmark-report";
-import { configChips } from "@/lib/benchmark-view";
+import { configChips, engineName, modelName } from "@/lib/benchmark-view";
import type { BenchmarkSummary } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
import type { ListRow } from "../benchmark-list";
@@ -79,7 +78,7 @@ export function BenchmarkReport({ run }: { run: ListRow }) {
BetterBench {sum.betterbenchVersion} · {date(sum.timestamp ?? run.startedAt)}
-
{run.label ?? `${s.repoId} ${weightsLabel(s) !== "safetensors" ? weightsLabel(s) : ""}`.trim()}
+
{run.label ?? `${modelName(s)} ${weightsLabel(s) !== "safetensors" && !modelName(s).includes(weightsLabel(s)) ? weightsLabel(s) : ""}`.trim()}
{reportSubtitle(run)}
@@ -88,7 +87,7 @@ export function BenchmarkReport({ run }: { run: ListRow }) {
{x}
))}
-
{s.runtimeName}
+
{engineName(s)}
{configChips(s).map((x) => (
{x}
@@ -200,12 +199,6 @@ export function BenchmarkReport({ run }: { run: ListRow }) {
)}
- {run.resources && (
-
- )}
-
{sum.single.length > 0 && (
diff --git a/src/app/(app)/benchmarks/[id]/page.tsx b/src/app/(app)/benchmarks/[id]/page.tsx
index 96290c0..5a1b30b 100644
--- a/src/app/(app)/benchmarks/[id]/page.tsx
+++ b/src/app/(app)/benchmarks/[id]/page.tsx
@@ -1,13 +1,15 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getBenchmark } from "@/lib/benchmarks";
+import { targetName } from "@/lib/benchmark-view";
import { BenchmarkDetail } from "./benchmark-detail";
+
export const dynamic = "force-dynamic";
export async function generateMetadata({ params }: PageProps<"/benchmarks/[id]">): Promise
{
const run = await getBenchmark((await params).id);
- return { title: run ? `${run.label ?? run.snapshot.deploymentName} · Benchmark` : "Benchmark" };
+ return { title: run ? `${run.label ?? targetName(run.snapshot)} · Benchmark` : "Benchmark" };
}
export default async function BenchmarkPage({ params }: PageProps<"/benchmarks/[id]">) {
diff --git a/src/app/(app)/benchmarks/benchmark-list.tsx b/src/app/(app)/benchmarks/benchmark-list.tsx
index 43a6f00..88f4894 100644
--- a/src/app/(app)/benchmarks/benchmark-list.tsx
+++ b/src/app/(app)/benchmarks/benchmark-list.tsx
@@ -4,7 +4,6 @@ import { GaugeIcon, GitCompareIcon } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { BenchmarkStateBadge } from "@/components/benchmark-state";
-import { RequestedByBadge } from "@/components/requested-by-badge";
import { NativeSelect } from "@/components/ui/native-select";
import { LocalTime } from "@/components/local-time";
import { buttonVariants } from "@/components/ui/button";
@@ -19,7 +18,7 @@ import {
TableRow,
} from "@/components/ui/table";
import type { BenchmarkRow } from "@/lib/benchmarks";
-import { configChips, describeSettings, headline } from "@/lib/benchmark-view";
+import { configChips, describeSettings, engineName, headline, modelName, targetName } from "@/lib/benchmark-view";
import { cn } from "@/lib/utils";
export type ListRow = Omit<
@@ -40,41 +39,40 @@ const fmt = (v: number | null | undefined, digits = 1) =>
export function BenchmarkList({
rows: initial,
compact,
+ filter,
}: {
rows: ListRow[];
compact?: boolean;
+ /** The list's filter, kept when polling: an endpoint's or a model's runs. */
+ filter?: { endpoint?: string; model?: string };
}) {
const [rows, setRows] = useState(initial);
const [selected, setSelected] = useState([]);
- // "" = everything, "-" = started in Kaname, else a token name.
+ // "" = every endpoint, else an endpoint's name.
const [by, setBy] = useState("");
const busy = rows.some((r) => r.state === "queued" || r.state === "running");
- const tokens = [
- ...new Set(rows.map((r) => r.requestedBy).filter((x): x is string => !!x)),
- ].sort();
- const shown = rows.filter(
- (r) => !by || (by === "-" ? !r.requestedBy : r.requestedBy === by),
- );
+ const targets = [...new Set(rows.map((r) => targetName(r.snapshot)))].sort();
+ const shown = rows.filter((r) => !by || targetName(r.snapshot) === by);
+
+ const query = new URLSearchParams(Object.entries(filter ?? {}).filter((e): e is [string, string] => !!e[1])).toString();
useEffect(() => {
if (!busy || compact) return;
const t = setInterval(async () => {
- const res = await fetch("/api/benchmarks", { cache: "no-store" }).catch(
- () => null,
- );
+ const res = await fetch(`/api/benchmarks${query ? `?${query}` : ""}`, { cache: "no-store" }).catch(() => null);
if (res?.ok) setRows(await res.json());
}, 3_000);
return () => clearInterval(t);
- }, [busy, compact]);
+ }, [busy, compact, query]);
if (rows.length === 0) {
return (
- No benchmarks yet. Open a running{" "}
-
- deployment
+ No benchmarks yet. Open an{" "}
+
+ endpoint
{" "}
and start one there.
@@ -94,7 +92,7 @@ export function BenchmarkList({
return (
- {!compact && (comparable.length > 1 || tokens.length > 0) && (
+ {!compact && (comparable.length > 1 || targets.length > 1) && (
{selected.length === 0
@@ -102,18 +100,17 @@ export function BenchmarkList({
: `${selected.length} selected (up to ${MAX_COMPARE}).`}
- {tokens.length > 0 && (
+ {targets.length > 1 && (
setBy(e.target.value)}
className="h-8 text-xs"
- aria-label="Requested by"
+ aria-label="Endpoint"
>
- Requested by anyone
- Started in Kaname
- {tokens.map((t) => (
+ All endpoints
+ {targets.map((t) => (
- {t} (API)
+ {t}
))}
@@ -181,7 +178,7 @@ export function BenchmarkList({
checked={selected.includes(r.id)}
disabled={r.state !== "completed"}
onCheckedChange={() => toggle(r.id)}
- aria-label={`Select ${r.label ?? s.deploymentName} for comparison`}
+ aria-label={`Select ${r.label ?? targetName(s)} for comparison`}
/>
)}
@@ -190,21 +187,17 @@ export function BenchmarkList({
href={`/benchmarks/${r.id}`}
className="font-medium hover:underline"
>
- {r.label ?? s.deploymentName}
+ {r.label ?? targetName(s)}
- {r.label && `${s.deploymentName} · `}
- {s.repoId} ·
-
+ {r.label && `${targetName(s)} · `}
+ {modelName(s)} ·
- {s.runtimeName}
+ {engineName(s)}
{configChips(s).map((c) => (
(
- {r.label ?? r.snapshot.deploymentName}
+ {r.label ?? targetName(r.snapshot)}
{i === 0 &&
baseline }
diff --git a/src/app/(app)/benchmarks/page.tsx b/src/app/(app)/benchmarks/page.tsx
index de3aeee..51ed0a2 100644
--- a/src/app/(app)/benchmarks/page.tsx
+++ b/src/app/(app)/benchmarks/page.tsx
@@ -1,21 +1,44 @@
import type { Metadata } from "next";
+import Link from "next/link";
import { listBenchmarks } from "@/lib/benchmarks";
+import { getModel } from "@/lib/library";
import { BenchmarkList } from "./benchmark-list";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Benchmarks" };
-export default async function BenchmarksPage() {
- const rows = await listBenchmarks();
+export default async function BenchmarksPage({ searchParams }: PageProps<"/benchmarks">) {
+ const modelId = (await searchParams).model;
+ const model = typeof modelId === "string" ? await getModel(modelId) : null;
+ const rows = await listBenchmarks({ modelId: model?.model.id });
return (
Benchmarks
- BetterBench runs against your deployments. Start one from a running deployment; select runs to compare their settings and numbers.
+ {model ? (
+ <>
+ Runs of{" "}
+
+ {model.model.repoId}
+
+ .{" "}
+
+ Show all
+
+ >
+ ) : (
+ <>
+ Speed (BetterBench), A/B and quality runs against your{" "}
+
+ endpoints
+
+ . Start one from an endpoint; select runs to compare their settings and numbers.
+ >
+ )}
-
+
);
}
diff --git a/src/app/(app)/benchmarks/sweeps/[id]/page.tsx b/src/app/(app)/benchmarks/sweeps/[id]/page.tsx
deleted file mode 100644
index 816fb4e..0000000
--- a/src/app/(app)/benchmarks/sweeps/[id]/page.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { Metadata } from "next";
-import { notFound } from "next/navigation";
-import { getSweep } from "@/lib/sweeps";
-import { SweepDetail } from "./sweep-detail";
-
-export const dynamic = "force-dynamic";
-export const metadata: Metadata = { title: "Sweep · Benchmarks" };
-
-export default async function SweepPage({ params }: PageProps<"/benchmarks/sweeps/[id]">) {
- const data = await getSweep((await params).id);
- if (!data) notFound();
- return
;
-}
diff --git a/src/app/(app)/benchmarks/sweeps/[id]/sweep-detail.tsx b/src/app/(app)/benchmarks/sweeps/[id]/sweep-detail.tsx
deleted file mode 100644
index 6c28e95..0000000
--- a/src/app/(app)/benchmarks/sweeps/[id]/sweep-detail.tsx
+++ /dev/null
@@ -1,305 +0,0 @@
-"use client";
-
-import { GitCompareIcon, Grid3x3Icon, SquareIcon, Trash2Icon } from "lucide-react";
-import Link from "next/link";
-import { useRouter } from "next/navigation";
-import { useEffect, useState } from "react";
-import { toast } from "sonner";
-import { BarChart } from "@/components/bar-chart";
-import { BenchmarkStateBadge } from "@/components/benchmark-state";
-import { Button, buttonVariants } from "@/components/ui/button";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
-import { AgentApprovalBar } from "@/components/approval-bar";
-import { RequestedByBadge } from "@/components/requested-by-badge";
-import { metaRows } from "@/lib/benchmark-meta";
-import { describeSettings, headline } from "@/lib/benchmark-view";
-import type { benchmarkSweeps, BenchmarkSummary, QualityResult, ResourceStats, RunMeta, SweepVariant } from "@/lib/db/schema";
-import { formatBytes } from "@/lib/format";
-import { cn } from "@/lib/utils";
-
-type Sweep = typeof benchmarkSweeps.$inferSelect;
-type Run = {
- id: string;
- state: string;
- summary: BenchmarkSummary | null;
- resources: ResourceStats | null;
- phase: string | null;
- error: string | null;
- meta: RunMeta | null;
- quality: QualityResult | null;
-};
-export type SweepData = { sweep: Sweep; runs: Run[] };
-
-const VARIANT_STATE: Record
= {
- pending: "Waiting",
- deploying: "Deploying",
- benchmarking: "Benchmarking",
- evaluating: "Quality eval",
- done: "Done",
- failed: "Failed",
- skipped: "Skipped",
-};
-
-type Row = {
- v: SweepVariant;
- run: Run | null;
- decode: number | null;
- ttft: number | null;
- prefill: number | null;
- peak: number | null;
- cpu: number | null;
- ram: number | null;
- vram: number | null;
- power: number | null;
- temp: number | null;
- quality: number | null;
-};
-
-function rowsOf(data: SweepData): Row[] {
- return data.sweep.variants.map((v) => {
- const run = data.runs.find((r) => r.id === v.runId) ?? null;
- const ev = data.runs.find((r) => r.id === v.evalRunId) ?? null;
- const h = headline(run?.summary ?? null);
- const c = run?.resources?.containers.find((x) => x.side === "a");
- const g = run?.resources?.gpus ?? [];
- return {
- v,
- run,
- decode: h.decode,
- ttft: h.ttftMs,
- prefill: h.prefill?.tps ?? null,
- peak: h.peak?.tps ?? null,
- cpu: c?.cpuAvg ?? null,
- ram: c?.memPeakBytes ?? null,
- vram: g.some((x) => x.vramPeakMb != null) ? g.reduce((s, x) => s + (x.vramPeakMb ?? 0), 0) : null,
- power: g.some((x) => x.powerAvgW != null) ? g.reduce((s, x) => s + (x.powerAvgW ?? 0), 0) : null,
- temp: g.some((x) => x.tempPeakC != null) ? Math.max(...g.map((x) => x.tempPeakC ?? -Infinity)) : null,
- quality: ev?.quality?.score ?? null,
- };
- });
-}
-
-/**
- * Recorded setup (GPU, PCIe, engine version, quant, KV cache, context, concurrency): values shared by
- * every variant go above the table, the ones that differ become columns.
- */
-function setupOf(rows: Row[]) {
- const per = rows.map((r) => (r.run?.meta ? metaRows(r.run.meta).filter((x) => x.key !== "image" && x.key !== "digest") : null));
- const keys = [...new Map(per.flatMap((x) => x ?? []).map((x) => [x.key, x.label])).entries()];
- const recorded = per.filter((x) => x != null);
- const value = (i: number, key: string) => per[i]?.find((x) => x.key === key)?.value ?? null;
- const differs = keys.filter(([key]) => new Set(recorded.map((x) => x.find((y) => y.key === key)?.value ?? "")).size > 1);
- const shared = keys.filter((k) => !differs.includes(k)).map(([key, label]) => ({ label, value: recorded[0]?.find((y) => y.key === key)?.value ?? null }));
- return { shared: recorded.length ? shared : [], columns: differs.map(([key, label]) => ({ key, label })), value };
-}
-
-/** Best value per column (higher or lower is better), to set it in bold. */
-function best(rows: Row[], key: keyof Row, higher: boolean): number | null {
- const vals = rows.map((r) => r[key]).filter((x): x is number => typeof x === "number");
- if (vals.length < 2) return null;
- return higher ? Math.max(...vals) : Math.min(...vals);
-}
-
-export function SweepDetail({ initial }: { initial: SweepData }) {
- const router = useRouter();
- const [data, setData] = useState(initial);
- const [busy, setBusy] = useState(false);
- const { sweep } = data;
- const active = sweep.state === "pending_approval" || sweep.state === "queued" || sweep.state === "running";
-
- useEffect(() => {
- if (!active) return;
- const t = setInterval(async () => {
- const res = await fetch(`/api/sweeps/${sweep.id}`, { cache: "no-store" }).catch(() => null);
- if (res?.ok) setData(await res.json());
- }, 3_000);
- return () => clearInterval(t);
- }, [sweep.id, active]);
-
- async function act(path: string, method: string, done: () => void) {
- setBusy(true);
- try {
- const res = await fetch(path, { method });
- const json = await res.json().catch(() => ({}));
- if (!res.ok) return toast.error(json.error?.message ?? `Failed (${res.status})`);
- done();
- } finally {
- setBusy(false);
- }
- }
-
- const rows = rowsOf(data);
- const setup = setupOf(rows);
- const finished = rows.filter((r) => r.decode != null);
- const runIds = rows.map((r) => r.v.runId).filter((x): x is string => !!x && rows.some((r) => r.run?.id === x && r.run.state === "completed"));
- const bestOf = {
- decode: best(rows, "decode", true),
- ttft: best(rows, "ttft", false),
- prefill: best(rows, "prefill", true),
- peak: best(rows, "peak", true),
- cpu: best(rows, "cpu", false),
- ram: best(rows, "ram", false),
- vram: best(rows, "vram", false),
- power: best(rows, "power", false),
- temp: best(rows, "temp", false),
- quality: best(rows, "quality", true),
- };
- const hasQuality = !!sweep.settings.quality;
- const cell = (v: number | null, b: number | null, fmt: (x: number) => string) => (
- {v != null ? fmt(v) : "—"}
- );
- const done = rows.filter((r) => r.v.state === "done" || r.v.state === "failed" || r.v.state === "skipped").length;
-
- return (
-
-
-
-
-
- {sweep.label ?? `Sweep of ${sweep.base.name}`}
-
-
- {sweep.params.map((p) => p.key).join(" × ")} · {rows.length} variants · {describeSettings(sweep.settings)} ·{" "}
- {sweep.baseDeploymentId ? (
-
- {sweep.base.name}
-
- ) : (
- sweep.base.name
- )}
-
-
-
-
-
- {runIds.length >= 2 && (
-
-
- Compare in detail
-
- )}
- {active ? (
- act(`/api/sweeps/${sweep.id}/cancel`, "POST", () => router.refresh())}>
-
- Cancel
-
- ) : (
- act(`/api/sweeps/${sweep.id}`, "DELETE", () => router.push("/benchmarks"))}>
-
- Delete
-
- )}
-
-
-
- {active && (
-
- {done} of {rows.length} variants finished. Each variant is deployed, benchmarked and removed again, one after another.
-
- )}
- {sweep.state === "pending_approval" && (
-
`${p.key}: ${p.values.join(", ")}`).join("; ")}${sweep.timeLimitS ? `, at most ${Math.round(sweep.timeLimitS / 60)} min` : ""}); each variant is deployed, benchmarked and removed`}
- base={`/api/sweeps/${sweep.id}`}
- />
- )}
- {sweep.error && {sweep.error}
}
-
- {finished.length > 0 && (
-
-
- Generation speed by variant
- Single-stream decode, tokens per second (BetterBench combined score). Higher is better.
-
-
- ({
- label: r.v.label,
- value: r.decode,
- valueLabel: r.decode!.toFixed(1),
- details: [r.ttft != null ? `TTFT ${r.ttft.toFixed(0)} ms` : "", r.ram != null ? `Peak RAM ${formatBytes(r.ram)}` : ""].filter(Boolean),
- }))}
- />
-
-
- )}
-
-
-
- Variants
- Best value per column in bold. Resource figures are averages/peaks over the run.
- {setup.shared.length > 0 && (
-
- {setup.shared
- .filter((x) => x.value)
- .map((x) => `${x.label}: ${x.value}`)
- .join(" · ")}
-
- )}
-
-
-
-
-
- Variant
- State
- {setup.columns.map((c) => (
-
- {c.label}
-
- ))}
- Decode t/s
- {hasQuality && Quality }
- TTFT ms
- Prefill t/s
- Peak t/s
- CPU cores
- Peak RAM
- Peak VRAM
- GPU power
- Peak temp
-
-
-
- {rows.map((r, i) => (
-
-
- {r.v.runId ? (
-
- {r.v.label}
-
- ) : (
- r.v.label
- )}
-
-
- {VARIANT_STATE[r.v.state]}
- {r.v.state === "benchmarking" && r.run?.phase ? ` · ${r.run.phase}` : ""}
- {(r.v.error || r.run?.error) && r.v.state === "failed" ? ` · ${(r.v.error ?? r.run?.error ?? "").slice(0, 60)}` : ""}
-
- {setup.columns.map((c) => (
-
- {setup.value(i, c.key) ?? "–"}
-
- ))}
- {cell(r.decode, bestOf.decode, (x) => x.toFixed(1))}
- {hasQuality && cell(r.quality, bestOf.quality, (x) => `${x}%`)}
- {cell(r.ttft, bestOf.ttft, (x) => x.toFixed(0))}
- {cell(r.prefill, bestOf.prefill, (x) => x.toFixed(0))}
- {cell(r.peak, bestOf.peak, (x) => x.toFixed(1))}
- {cell(r.cpu, bestOf.cpu, (x) => x.toFixed(2))}
- {cell(r.ram, bestOf.ram, (x) => formatBytes(x))}
- {cell(r.vram, bestOf.vram, (x) => `${(x / 1024).toFixed(1)} GiB`)}
- {cell(r.power, bestOf.power, (x) => `${Math.round(x)} W`)}
- {cell(r.temp, bestOf.temp, (x) => `${Math.round(x)} °C`)}
-
- ))}
-
-
-
-
-
- );
-}
diff --git a/src/app/(app)/benchmarks/sweeps/new/page.tsx b/src/app/(app)/benchmarks/sweeps/new/page.tsx
deleted file mode 100644
index 38843c9..0000000
--- a/src/app/(app)/benchmarks/sweeps/new/page.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import type { Metadata } from "next";
-import { listDeployableModels, listDeployments } from "@/lib/deployments";
-import { SweepForm, type SweepBase } from "./sweep-form";
-
-export const dynamic = "force-dynamic";
-export const metadata: Metadata = { title: "New sweep" };
-
-export default async function NewSweepPage({ searchParams }: PageProps<"/benchmarks/sweeps/new">) {
- const { deployment } = await searchParams;
- const [deployments, models] = await Promise.all([listDeployments(), listDeployableModels()]);
- const bases: SweepBase[] = deployments
- .filter((d) => !d.sweepId)
- .map((d) => ({
- id: d.id,
- name: d.name,
- engine: d.engine,
- accelerator: d.accelerator,
- repoId: d.repoId,
- options: d.options,
- cpus: d.cpus,
- memoryMb: d.memoryMb,
- ggufFiles: models.find((m) => m.id === d.modelId)?.candidates.gguf.map((g) => g.path) ?? [],
- }));
- return (
-
-
-
New sweep
-
- Vary one or two settings of a deployment. Kaname deploys each variant in turn, benchmarks it with BetterBench, removes it again and compares all of them,
- including the resources each one used.
-
-
-
-
- );
-}
diff --git a/src/app/(app)/benchmarks/sweeps/new/sweep-form.tsx b/src/app/(app)/benchmarks/sweeps/new/sweep-form.tsx
deleted file mode 100644
index 877635f..0000000
--- a/src/app/(app)/benchmarks/sweeps/new/sweep-form.tsx
+++ /dev/null
@@ -1,257 +0,0 @@
-"use client";
-
-import { Grid3x3Icon, PlusIcon, XIcon } from "lucide-react";
-import { useRouter } from "next/navigation";
-import { useState } from "react";
-import { toast } from "sonner";
-import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
-import { Checkbox } from "@/components/ui/checkbox";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { NativeSelect } from "@/components/ui/native-select";
-import type { BenchmarkPhase, DeploymentOptions, RuntimeAccelerator, RuntimeEngine } from "@/lib/db/schema";
-import { quantGroup } from "@/lib/selection";
-import { expandSweep, MAX_SWEEP_VARIANTS, splitValues, SweepError, sweepKeysFor } from "@/lib/sweep";
-
-export type SweepBase = {
- id: string;
- name: string;
- engine: RuntimeEngine;
- accelerator: RuntimeAccelerator;
- repoId: string;
- options: DeploymentOptions;
- cpus: number | null;
- memoryMb: number | null;
- ggufFiles: string[];
-};
-
-const PHASES: { id: BenchmarkPhase; label: string }[] = [
- { id: "decode", label: "Generation" },
- { id: "prefill", label: "Prompt processing" },
- { id: "concurrency", label: "Parallel requests" },
-];
-
-/** The base's current value of a sweep key, shown as a hint. */
-function currentValue(base: SweepBase, key: string): string {
- const o = base.options;
- const v: Record = {
- contextSize: o.contextSize,
- modelFile: o.modelFile,
- kvCache: o.cacheTypeK ?? "f16",
- threads: o.threads ?? "auto",
- parallel: o.parallel ?? "auto",
- batchSize: o.batchSize ?? "default",
- ubatchSize: o.ubatchSize ?? "default",
- flashAttn: o.flashAttn ?? "auto",
- cacheRamMb: o.cacheRamMb ?? "8192 (default)",
- gpuLayers: o.gpuLayers ?? "auto",
- dtype: o.dtype ?? "runtime default",
- maxNumSeqs: o.maxNumSeqs ?? "default",
- kvCacheGb: o.kvCacheGb ?? "runtime default",
- gpuMemoryUtilization: o.gpuMemoryUtilization ?? "0.9",
- cpus: base.cpus ?? "no limit",
- };
- return String(v[key] ?? "");
-}
-
-type Param = { key: string; text: string; files: string[] };
-
-export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initialBaseId?: string }) {
- const router = useRouter();
- const [baseId, setBaseId] = useState(initialBaseId && bases.some((b) => b.id === initialBaseId) ? initialBaseId : (bases[0]?.id ?? ""));
- const base = bases.find((b) => b.id === baseId) ?? null;
- const keys = base ? sweepKeysFor(base.engine, base.accelerator) : [];
- const [params, setParams] = useState ([{ key: "contextSize", text: "", files: [] }]);
- const [label, setLabel] = useState("");
- const [quality, setQuality] = useState(false);
- const [mode, setMode] = useState("quick");
- const [passes, setPasses] = useState("10");
- const [phases, setPhases] = useState(["decode", "prefill", "concurrency"]);
- const [busy, setBusy] = useState(false);
-
- const values = (p: Param) => (p.key === "modelFile" ? p.files : splitValues(p.text));
- let preview: { variants: ReturnType | null; error: string | null } = { variants: null, error: null };
- if (base) {
- try {
- preview = { variants: expandSweep(params.map((p) => ({ key: p.key, values: values(p) })), base.engine, base.accelerator, { modelFiles: base.ggufFiles }), error: null };
- } catch (err) {
- preview = { variants: null, error: err instanceof SweepError ? err.message : String(err) };
- }
- }
-
- const setParam = (i: number, patch: Partial ) => setParams((ps) => ps.map((p, j) => (j === i ? { ...p, ...patch } : p)));
-
- async function submit() {
- if (!base || !preview.variants) return;
- setBusy(true);
- try {
- const res = await fetch("/api/sweeps", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- baseDeploymentId: base.id,
- label: label.trim() || null,
- params: params.map((p) => ({ key: p.key, values: values(p) })),
- quick: mode === "quick",
- passes: mode === "custom" ? Number(passes) || 10 : null,
- phases: phases.length === PHASES.length ? [] : phases,
- quality,
- }),
- });
- const json = await res.json().catch(() => ({}));
- if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`);
- router.push(`/benchmarks/sweeps/${json.id}`);
- } finally {
- setBusy(false);
- }
- }
-
- if (bases.length === 0) return Create a deployment first; a sweep varies its settings.
;
-
- return (
-
-
-
-
- Base deployment
- Every variant starts from its settings. It doesn't need to be running.
-
-
- setBaseId(e.target.value)} aria-label="Base deployment">
- {bases.map((b) => (
-
- {b.name} · {b.repoId}
-
- ))}
-
-
-
-
-
-
- What to vary
- One or two settings; every combination becomes a variant (up to {MAX_SWEEP_VARIANTS}).
-
-
- {base &&
- params.map((p, i) => {
- const def = keys.find((k) => k.key === p.key);
- return (
-
-
- setParam(i, { key: e.target.value, text: "", files: [] })} aria-label={`Setting ${i + 1}`}>
- {keys
- .filter((k) => k.key === p.key || !params.some((q) => q.key === k.key))
- .map((k) => (
-
- {k.label}
-
- ))}
-
- {params.length > 1 && (
- setParams((ps) => ps.filter((_, j) => j !== i))}>
-
-
- )}
-
- {p.key === "modelFile" ? (
-
- {base.ggufFiles.map((f) => (
-
- setParam(i, { files: v ? [...p.files, f] : p.files.filter((x) => x !== f) })} />
- {quantGroup(f) ?? f}
-
- ))}
- {base.ggufFiles.length < 2 &&
Only one GGUF file is downloaded; download more quants to compare them.
}
-
- ) : (
-
setParam(i, { text: e.target.value })} placeholder={def?.hint} aria-label="Values" className="font-mono text-sm" />
- )}
-
Base value: {currentValue(base, p.key)}
-
- );
- })}
- {params.length < 2 && base && (
- setParams((ps) => [...ps, { key: keys.find((k) => !ps.some((q) => q.key === k.key))?.key ?? "threads", text: "", files: [] }])}
- >
-
- Vary a second setting
-
- )}
-
-
-
-
-
- Benchmark per variant
-
-
-
- setMode(e.target.value)} aria-label="Run length">
- Quick: 5 passes (smoke test)
- Full: 20 passes (comparable)
- Custom number of passes
-
- {mode === "custom" && setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes" />}
-
-
- {PHASES.map((p) => (
-
- setPhases((cur) => (v ? [...cur, p.id] : cur.filter((x) => x !== p.id)))} />
- {p.label}
-
- ))}
-
-
- setQuality(v === true)} className="mt-0.5" />
-
- Also run the quality eval on each variant
- Tool calling, coding and long-context retrieval, after the speed run (adds a few minutes per variant).
-
-
-
- Label
- setLabel(e.target.value)} maxLength={80} placeholder="e.g. context vs KV cache (optional)" />
-
-
-
-
-
-
-
-
-
- {preview.variants ? `${preview.variants.length} variants` : "Variants"}
-
-
-
- {preview.error ? (
- {preview.error}
- ) : (
-
- {preview.variants?.map((v) => (
-
- {v.index + 1}
- {v.label}
-
- ))}
-
- )}
-
- Variants run one after another, each in its own temporary deployment{base?.memoryMb ? " (memory limit: the base's, raised where a variant needs more)" : ""}.
- {mode !== "quick" && " Full runs on a CPU can take hours per variant."}
-
-
-
- Start sweep
-
-
-
-
- );
-}
diff --git a/src/app/(app)/deployments/[id]/benchmark-card.tsx b/src/app/(app)/deployments/[id]/benchmark-card.tsx
deleted file mode 100644
index a28afaf..0000000
--- a/src/app/(app)/deployments/[id]/benchmark-card.tsx
+++ /dev/null
@@ -1,286 +0,0 @@
-"use client";
-
-import { BadgeCheckIcon, GaugeIcon, GitCompareArrowsIcon, Grid3x3Icon } from "lucide-react";
-import Link from "next/link";
-import { useRouter } from "next/navigation";
-import { useEffect, useState } from "react";
-import { toast } from "sonner";
-import { BenchmarkStateBadge } from "@/components/benchmark-state";
-import { Button, buttonVariants } from "@/components/ui/button";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Checkbox } from "@/components/ui/checkbox";
-import { Input } from "@/components/ui/input";
-import { NativeSelect } from "@/components/ui/native-select";
-import { abHeadline } from "@/lib/ab-report";
-import { headline } from "@/lib/benchmark-view";
-import type { BenchmarkPhase } from "@/lib/db/schema";
-import { QUALITY_SECTIONS, type QualitySection } from "@/lib/db/schema";
-import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
-import { cn } from "@/lib/utils";
-import type { ListRow } from "../../benchmarks/benchmark-list";
-
-const PHASES: { id: BenchmarkPhase; label: string; hint: string }[] = [
- { id: "decode", label: "Generation", hint: "single request, 8 prompt categories" },
- { id: "prefill", label: "Prompt processing", hint: "growing input lengths, up to the context size" },
- { id: "concurrency", label: "Parallel requests", hint: "1, 2, 4 and 8 at once" },
-];
-
-type Mode = "run" | "ab" | "quality" | "sweep";
-type Peer = { id: string; name: string; state: string; modelId: string };
-
-/** Benchmark this deployment: a single run, a paired A/B against another one, or a sweep. */
-export function BenchmarkCard({ deploymentId, modelId, running, initial }: { deploymentId: string; modelId: string; running: boolean; initial: ListRow[] }) {
- const router = useRouter();
- const [tab, setTab] = useState("run");
- const [mode, setMode] = useState("quick");
- const [passes, setPasses] = useState("10");
- const [phases, setPhases] = useState(["decode", "prefill", "concurrency"]);
- const [label, setLabel] = useState("");
- const [description, setDescription] = useState("");
- const [busy, setBusy] = useState(false);
- const [runs, setRuns] = useState(initial);
- const [peers, setPeers] = useState(null);
- const [peerId, setPeerId] = useState("");
- const [mde, setMde] = useState("1");
- const [maxPairs, setMaxPairs] = useState("200");
- const [sections, setSections] = useState([...QUALITY_SECTIONS]);
-
- const active = runs.some((r) => r.state === "queued" || r.state === "running");
- useEffect(() => {
- const t = setInterval(
- async () => {
- const res = await fetch(`/api/benchmarks?deployment=${deploymentId}`, { cache: "no-store" }).catch(() => null);
- if (res?.ok) setRuns(await res.json());
- },
- active ? 3_000 : 15_000,
- );
- return () => clearInterval(t);
- }, [deploymentId, active]);
-
- // Other deployments of the same model (A/B partners).
- useEffect(() => {
- if (tab !== "ab") return;
- let stop = false;
- void fetch("/api/deployments", { cache: "no-store" })
- .then((r) => (r.ok ? r.json() : []))
- .then((rows: Peer[]) => {
- if (stop) return;
- const list = rows.filter((p) => p.modelId === modelId && p.id !== deploymentId);
- setPeers(list);
- setPeerId((cur) => cur || list.find((p) => p.state === "running")?.id || "");
- });
- return () => {
- stop = true;
- };
- }, [tab, modelId, deploymentId]);
-
- async function start(body: Record) {
- setBusy(true);
- try {
- const res = await fetch("/api/benchmarks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ deploymentId, label: label.trim() || null, description: description.trim() || null, ...body }) });
- const json = await res.json().catch(() => ({}));
- if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`);
- router.push(`/benchmarks/${json.id}`);
- } finally {
- setBusy(false);
- }
- }
-
- const peer = peers?.find((p) => p.id === peerId);
- const TABS: { id: Mode; label: string; icon: typeof GaugeIcon }[] = [
- { id: "run", label: "Run", icon: GaugeIcon },
- { id: "ab", label: "A/B", icon: GitCompareArrowsIcon },
- { id: "quality", label: "Quality", icon: BadgeCheckIcon },
- { id: "sweep", label: "Sweep", icon: Grid3x3Icon },
- ];
-
- return (
-
-
-
-
- Benchmark
-
-
-
-
- {TABS.map((t) => (
- setTab(t.id)}
- className={cn("flex items-center gap-1 rounded-md px-2.5 py-1 text-xs", tab === t.id ? "bg-background font-medium shadow-sm" : "text-muted-foreground hover:text-foreground")}
- >
-
- {t.label}
-
- ))}
-
-
- {tab === "run" && (
- <>
-
- setMode(e.target.value)} aria-label="Run length">
- Quick: 5 passes (smoke test)
- Full: 20 passes (comparable)
- Custom number of passes
-
- {mode === "custom" && (
- setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes per category" />
- )}
-
-
- {PHASES.map((p) => (
-
- setPhases((cur) => (v ? [...cur, p.id] : cur.filter((x) => x !== p.id)))} className="mt-0.5" />
-
- {p.label}
- {p.hint}
-
-
- ))}
-
- setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
- setDescription(e.target.value)} maxLength={4000} placeholder="Description: what this run tries out (optional, published with it)" />
-
- start({ quick: mode === "quick", passes: mode === "custom" ? Number(passes) || 10 : null, phases: phases.length === PHASES.length ? [] : phases })
- }
- disabled={!running || busy || phases.length === 0}
- >
-
- Run benchmark
-
-
- {running ? "On a CPU a full run can take hours. Avoid other load on the server while it runs." : "Start the deployment to benchmark it."}
-
- >
- )}
-
- {tab === "ab" && (
- <>
-
- Paired A/B: the same prompts go to this deployment (A) and another one of the same model (B), alternating, until the difference is known to ±the target. Both
- must be running and fit in memory together.
-
- {peers === null ? (
- Loading…
- ) : peers.length === 0 ? (
-
- No other deployment of this model. Create one with the setting you want to compare (e.g. a different KV cache type), or run a sweep.
-
- ) : (
- <>
- setPeerId(e.target.value)} aria-label="Deployment B">
- Choose B…
- {peers.map((p) => (
-
- {p.name} {p.state !== "running" ? `(${p.state})` : ""}
-
- ))}
-
- {peer && peer.state !== "running" && (
-
- {peer.name} isn't running.{" "}
-
- Start it
- {" "}
- first.
-
- )}
-
-
- Target precision (±%)
- setMde(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" />
-
-
- Max pairs
- setMaxPairs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" />
-
-
- setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. f16 vs q8_0 KV (optional)" />
- setDescription(e.target.value)} maxLength={4000} placeholder="Description: what this run tries out (optional, published with it)" />
- start({ deploymentBId: peerId, mdePct: Number(mde) || 1, maxPairs: Math.max(12, Number(maxPairs) || 200) })}
- disabled={!running || busy || !peer || peer.state !== "running"}
- >
-
- Start A/B
-
- >
- )}
- {!running && Start this deployment (A) first.
}
- >
- )}
-
- {tab === "quality" && (
- <>
-
- A short, deterministic check of the answers (greedy decoding, fixed seed, thinking off): to see whether a quant, KV cache type or build changes quality,
- next to the speed numbers.
-
-
- {QUALITY_SECTIONS.map((s) => (
-
- setSections((cur) => (v ? [...cur, s] : cur.filter((x) => x !== s)))} className="mt-0.5" />
-
- {SECTION_LABEL[s]}
- {SECTION_HINT[s]}
-
-
- ))}
-
- setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
- start({ kind: "eval", evalSections: sections.length === QUALITY_SECTIONS.length ? [] : sections })} disabled={!running || busy || sections.length === 0}>
-
- Run quality eval
-
- {!running && Start the deployment to evaluate it.
}
- >
- )}
-
- {tab === "sweep" && (
- <>
-
- Vary one or two settings (context size, KV cache type, threads, quant, GPU layers, …). Kaname deploys each variant in turn, benchmarks it, removes it again, and
- compares all of them. This deployment doesn't need to run.
-
-
-
- Set up a sweep
-
- >
- )}
-
- {runs.length > 0 && (
-
- {runs.slice(0, 5).map((r) => {
- const h = headline(r.summary);
- return (
-
-
- {r.kind !== "run" && {r.kind === "ab" ? "A/B" : "quality"} }
- {r.label ?? new Date(r.createdAt).toLocaleString()}
-
-
- {r.kind === "ab"
- ? r.ab && abHeadline(r.ab.decode_tps)
- : r.kind === "eval"
- ? r.quality?.score != null && `${r.quality.score}%`
- : h.decode != null && `${h.decode.toFixed(1)} t/s`}
-
-
-
- );
- })}
-
- All benchmarks →
-
-
- )}
-
-
- );
-}
diff --git a/src/app/(app)/deployments/[id]/deployment-detail.tsx b/src/app/(app)/deployments/[id]/deployment-detail.tsx
deleted file mode 100644
index 29da38a..0000000
--- a/src/app/(app)/deployments/[id]/deployment-detail.tsx
+++ /dev/null
@@ -1,403 +0,0 @@
-"use client";
-
-import { ExternalLinkIcon, PencilIcon, PlayIcon, SendIcon, ShieldCheckIcon, ShieldIcon, SquareIcon, Trash2Icon } from "lucide-react";
-import { toast } from "sonner";
-import { AgentApprovalBar } from "@/components/approval-bar";
-import { RequestedByBadge } from "@/components/requested-by-badge";
-import Link from "next/link";
-import { useRouter } from "next/navigation";
-import { useEffect, useState } from "react";
-import { CopyButton } from "@/components/copy-button";
-import { DeploymentStateBadge } from "@/components/deployment-state";
-import { LiveLog } from "@/components/live-log";
-import { LocalTime } from "@/components/local-time";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
-} from "@/components/ui/alert-dialog";
-import { Button, buttonVariants } from "@/components/ui/button";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Progress } from "@/components/ui/progress";
-import { useHostname, webUiUrl } from "@/hooks/use-hostname";
-import { ENGINE_PORT } from "@/lib/deploy-command";
-import { ACCELERATOR_LABEL } from "@/lib/runtimes-shared";
-import type { DeploymentRow } from "@/lib/deployments";
-import { formatBytes, percent } from "@/lib/format";
-import { quantGroup } from "@/lib/selection";
-import { cn } from "@/lib/utils";
-import { deleteDeployment, startDeployment, stopDeployment } from "../actions";
-import type { ListRow } from "../../benchmarks/benchmark-list";
-import { BenchmarkCard } from "./benchmark-card";
-
-type Deployment = Omit & {
- startedAt: string | null;
- readyAt: string | null;
- stoppedAt: string | null;
- createdAt: string;
-};
-
-function Stat({ label, value, children }: { label: string; value: React.ReactNode; children?: React.ReactNode }) {
- return (
-
- {label}
- {value}
- {children}
-
- );
-}
-
-export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment; benchmarks: ListRow[] }) {
- const router = useRouter();
- const [d, setD] = useState(initial);
- const [now, setNow] = useState(() => Date.now());
- const active = d.desiredState === "running" || d.state === "starting" || d.state === "running" || d.state === "stopping";
-
- useEffect(() => {
- const t = setInterval(async () => {
- setNow(Date.now());
- const res = await fetch(`/api/deployments/${d.id}`, { cache: "no-store" }).catch(() => null);
- if (res?.status === 404) router.push("/deployments");
- else if (res?.ok) setD(await res.json());
- }, 2_000);
- return () => clearInterval(t);
- }, [d.id, router]);
-
- const file = d.options.modelFile ? (quantGroup(d.options.modelFile) ?? d.options.modelFile) : null;
- const loadSecs = d.readyAt && d.startedAt ? (new Date(d.readyAt).getTime() - new Date(d.startedAt).getTime()) / 1000 : null;
- const startingSecs = d.state === "starting" && d.startedAt ? Math.max(0, (now - new Date(d.startedAt).getTime()) / 1000) : null;
- const port = ENGINE_PORT[d.engine];
- const internal = d.containerName ? `http://${d.containerName}:${port}/v1` : null;
- const hostname = useHostname();
- const published = d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/v1` : null;
- const webUi = webUiUrl(d, hostname);
-
- return (
-
-
-
-
-
-
{d.name}
-
-
- {d.protected && (
-
-
- protected
-
- )}
-
-
-
- {d.repoId}
-
- {file && ` · ${file}`}
- {d.options.mmproj && " · vision"}
- {d.options.draftFile && ` · ${d.options.draftType === "draft-mtp" ? "MTP" : "draft"}`} · {d.runtimeName}
-
-
{d.runtimeImage}
-
-
- {webUi && (
-
-
- Web UI
-
- )}
- {active ? (
-
stopDeployment(d.id)}>
-
- Stop
-
- ) : (
-
startDeployment(d.id)}>
-
- Start
-
- )}
-
{
- const res = await fetch(`/api/deployments/${d.id}/protect`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ protected: !d.protected }) });
- if (!res.ok) return void toast.error(`Could not change it (${res.status})`);
- setD({ ...d, protected: !d.protected });
- toast.success(d.protected ? "No longer protected from agents" : "Protected from agents");
- }}
- >
- {d.protected ? : }
- {d.protected ? "Protected" : "Protect"}
-
-
-
- Edit
-
-
- }>
-
- Delete
-
-
-
- Delete {d.name}?
- The container is stopped and removed. The model files stay in the library.
-
-
- Cancel
- {
- if (await deleteDeployment(d.id)) router.push("/deployments");
- }}
- >
- Delete
-
-
-
-
-
-
-
- {d.startRequestedAt && (
-
- )}
-
- {d.state === "failed" && d.error && (
-
{d.error}
- )}
-
-
-
-
-
-
- {d.cpus ? `limit ${d.cpus}` : "no limit"}
-
-
- {d.stats && d.state === "running" && d.memoryMb ? (
-
- ) : (
- {d.memoryMb ? `limit ${formatBytes(d.memoryMb * 2 ** 20)}` : "no limit"}
- )}
-
-
- until /health answered
-
-
-
- {d.engine === "vllm" ? `seqs ${d.options.maxNumSeqs ?? "default"}` : `slots ${d.options.parallel ?? "auto"}`}
-
-
-
-
-
-
-
-
-
-
-
-
-
- Endpoint
-
-
- {internal ? (
-
- {internal}
-
-
- ) : (
- Not started yet.
- )}
- On the Docker network, for Kaname and other containers.
- {published && (
-
- {published}
-
-
- )}
-
- OpenAI-compatible; model name {d.repoId}.
- {d.options.requireApiKey && (
- <>
- {" "}
- Requires one of the{" "}
-
- API keys
- {" "}
- as Authorization: Bearer.
- >
- )}
-
-
-
-
-
- Details
-
-
-
- Container
- {d.containerName ?? "–"}
- Runs on
-
- {ACCELERATOR_LABEL[d.accelerator]}
- {d.accelerator === "nvidia" && ` · ${d.options.gpus?.length ? `${d.options.gpus.length} selected GPU${d.options.gpus.length === 1 ? "" : "s"}` : "all GPUs"}`}
-
- Started
-
-
-
- Stopped
-
-
-
- {d.command && (
- <>
- Arguments
-
- {d.command.join(" ")}
-
-
- >
- )}
-
-
-
-
-
-
- );
-}
-
-/** Live container log (polls new lines every 1.5 s). */
-/** Smoke test over the OpenAI API: streams the answer and measures time to first token and speed. */
-function Chat({ id, running }: { id: string; running: boolean }) {
- const [prompt, setPrompt] = useState("Write one sentence about the sea.");
- const [answer, setAnswer] = useState("");
- const [busy, setBusy] = useState(false);
- const [stats, setStats] = useState<{ ttft: number | null; total: number; tokens: number | null; promptTokens: number | null } | null>(null);
- const [error, setError] = useState(null);
-
- async function send() {
- setBusy(true);
- setAnswer("");
- setError(null);
- setStats(null);
- const t0 = performance.now();
- let first: number | null = null;
- let usage: { completion_tokens?: number; prompt_tokens?: number } | null = null;
- let chunks = 0;
- try {
- const res = await fetch(`/api/deployments/${id}/chat`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ messages: [{ role: "user", content: prompt }], maxTokens: 256 }),
- });
- if (!res.ok || !res.body) {
- const body = await res.json().catch(() => ({}));
- throw new Error(body.error?.message ?? `HTTP ${res.status}`);
- }
- const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
- let buf = "";
- for (;;) {
- const { value, done } = await reader.read();
- if (done) break;
- buf += value;
- let nl: number;
- while ((nl = buf.indexOf("\n")) >= 0) {
- const line = buf.slice(0, nl).trim();
- buf = buf.slice(nl + 1);
- if (!line.startsWith("data:")) continue;
- const data = line.slice(5).trim();
- if (data === "[DONE]") continue;
- const j = JSON.parse(data);
- if (j.usage) usage = j.usage;
- const delta: string = j.choices?.[0]?.delta?.content ?? j.choices?.[0]?.delta?.reasoning_content ?? "";
- if (delta) {
- first ??= performance.now();
- chunks++;
- setAnswer((a) => a + delta);
- }
- }
- }
- const total = (performance.now() - t0) / 1000;
- setStats({ ttft: first ? (first - t0) / 1000 : null, total, tokens: usage?.completion_tokens ?? chunks, promptTokens: usage?.prompt_tokens ?? null });
- } catch (err) {
- setError(err instanceof Error ? err.message : String(err));
- } finally {
- setBusy(false);
- }
- }
-
- const genSecs = stats && stats.ttft != null ? stats.total - stats.ttft : null;
- return (
-
-
- Try it
-
-
-
-
- );
-}
diff --git a/src/app/(app)/deployments/[id]/edit/page.tsx b/src/app/(app)/deployments/[id]/edit/page.tsx
deleted file mode 100644
index 34197a0..0000000
--- a/src/app/(app)/deployments/[id]/edit/page.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import type { Metadata } from "next";
-import { notFound } from "next/navigation";
-import { getDeployment } from "@/lib/deployments";
-import { DeploymentForm } from "../../deployment-form";
-import { formData } from "../../form-data";
-
-export const dynamic = "force-dynamic";
-export const metadata: Metadata = { title: "Edit deployment" };
-
-export default async function EditDeploymentPage({ params }: PageProps<"/deployments/[id]/edit">) {
- const { id } = await params;
- const [d, data] = await Promise.all([getDeployment(id), formData()]);
- if (!d) notFound();
- return (
-
-
Edit {d.name}
- {d.state !== "stopped" && d.state !== "failed" && (
-
Stop the deployment before saving changes.
- )}
-
-
- );
-}
diff --git a/src/app/(app)/deployments/[id]/page.tsx b/src/app/(app)/deployments/[id]/page.tsx
deleted file mode 100644
index 91c2450..0000000
--- a/src/app/(app)/deployments/[id]/page.tsx
+++ /dev/null
@@ -1,19 +0,0 @@
-import type { Metadata } from "next";
-import { notFound } from "next/navigation";
-import { listBenchmarks } from "@/lib/benchmarks";
-import { getDeployment } from "@/lib/deployments";
-import { DeploymentDetail } from "./deployment-detail";
-
-export const dynamic = "force-dynamic";
-
-export async function generateMetadata({ params }: PageProps<"/deployments/[id]">): Promise {
- const d = await getDeployment((await params).id);
- return { title: d ? d.name : "Deployment" };
-}
-
-export default async function DeploymentPage({ params }: PageProps<"/deployments/[id]">) {
- const { id } = await params;
- const [d, runs] = await Promise.all([getDeployment(id), listBenchmarks({ deploymentId: id })]);
- if (!d) notFound();
- return ;
-}
diff --git a/src/app/(app)/deployments/actions.ts b/src/app/(app)/deployments/actions.ts
deleted file mode 100644
index 34dd392..0000000
--- a/src/app/(app)/deployments/actions.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-"use client";
-
-import { toast } from "sonner";
-
-async function call(url: string, method: string): Promise {
- const res = await fetch(url, { method });
- if (res.ok) return true;
- const body = await res.json().catch(() => ({}));
- toast.error(body.error?.message ?? `Request failed (${res.status})`);
- return false;
-}
-
-export const startDeployment = (id: string) => call(`/api/deployments/${id}/start`, "POST");
-export const stopDeployment = (id: string) => call(`/api/deployments/${id}/stop`, "POST");
-export const deleteDeployment = (id: string) => call(`/api/deployments/${id}`, "DELETE");
diff --git a/src/app/(app)/deployments/deployment-form.tsx b/src/app/(app)/deployments/deployment-form.tsx
deleted file mode 100644
index 772bf27..0000000
--- a/src/app/(app)/deployments/deployment-form.tsx
+++ /dev/null
@@ -1,1291 +0,0 @@
-"use client";
-
-import { BoxesIcon, CheckIcon, SearchIcon, TerminalIcon } from "lucide-react";
-import Link from "next/link";
-import { useRouter } from "next/navigation";
-import { useState } from "react";
-import { toast } from "sonner";
-import { ArgsEditor } from "@/components/args-editor";
-import { CopyButton } from "@/components/copy-button";
-import { FileRoleBadge } from "@/components/labels";
-import { Button } from "@/components/ui/button";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
-import { Checkbox } from "@/components/ui/checkbox";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { NativeSelect } from "@/components/ui/native-select";
-import type {
- DeploymentOptions,
- HardwareGpu,
- HostGpu,
- RuntimeAccelerator,
- RuntimeEngine,
-} from "@/lib/db/schema";
-import type { ModelCandidates } from "@/lib/deploy-candidates";
-import {
- API_KEY_PLACEHOLDER,
- buildCommand,
- ENGINE_PORT,
- estimateMemoryMb,
- estimateVramMb,
- renderCommand,
-} from "@/lib/deploy-command";
-import { argsToRows, rowsToArgs } from "@/lib/extra-args";
-import { ACCELERATOR_LABEL } from "@/lib/runtimes-shared";
-import { formatBytes } from "@/lib/format";
-import { quantGroup } from "@/lib/selection";
-import { cn } from "@/lib/utils";
-
-export type FormRuntime = {
- id: string;
- name: string;
- engine: RuntimeEngine;
- image: string;
- imageState: string;
- env: Record;
- extraArgs: string[];
- accelerator: RuntimeAccelerator;
-};
-export type FormModel = {
- id: string;
- repoId: string;
- localPath: string;
- candidates: ModelCandidates;
-};
-export type FormHost = {
- cpus: number | null;
- memoryBytes: number | null;
- cpuFeatures: string[];
- nvidia: boolean;
- gpus: HostGpu[];
- /** All GPUs on the host with Settings → Hardware applied (Intel/AMD VRAM for the estimate). */
- hardwareGpus: HardwareGpu[];
-} | null;
-export type FormInitial = {
- id?: string;
- name: string;
- runtimeId: string;
- modelId: string;
- options: DeploymentOptions;
- cpus: number | null;
- memoryMb: number | null;
- hostPort: number | null;
-};
-
-const CONTEXT_PRESETS = [2048, 4096, 8192, 16384, 32768];
-const KV_TYPES = ["f16", "q8_0", "q4_0"];
-
-const intOrNull = (s: string) =>
- (s.trim() === "" ? null : Math.max(0, Math.round(Number(s)))) || null;
-/** Like intOrNull, but 0 and -1 are meaningful (e.g. --cache-ram 0 = off). */
-const intOrNullSigned = (s: string) =>
- s.trim() === "" || !Number.isFinite(Number(s)) ? null : Math.round(Number(s));
-/** Default prompt cache for new llama.cpp deployments (llama-server's own default is 8 GiB). */
-const DEFAULT_CACHE_RAM_MB = 1024;
-const numOrNull = (s: string) => (s.trim() === "" ? null : Number(s)) || null;
-
-function Section({
- step,
- title,
- description,
- children,
-}: {
- step: number;
- title: string;
- description?: string;
- children: React.ReactNode;
-}) {
- return (
-
-
-
-
- {step}
-
- {title}
-
- {description && {description} }
-
- {children}
-
- );
-}
-
-/** A titled block of related options inside the launch options card. */
-function Group({
- title,
- description,
- children,
-}: {
- title: string;
- description?: string;
- children: React.ReactNode;
-}) {
- return (
-
-
-
{title}
- {description && (
-
{description}
- )}
-
-
{children}
-
- );
-}
-
-/** `flag`: the command-line flag the field sets, shown next to the label. */
-function Field({
- label,
- flag,
- hint,
- children,
- htmlFor,
- wide,
-}: {
- label: string;
- flag?: string;
- hint?: React.ReactNode;
- children: React.ReactNode;
- htmlFor?: string;
- wide?: boolean;
-}) {
- return (
-
-
- {label}
- {flag && (
-
- {flag}
-
- )}
-
- {children}
- {hint &&
{hint}
}
-
- );
-}
-
-/** Pick runtime → model and files → launch options. Used for "New deployment" and "Edit". */
-export function DeploymentForm({
- runtimes,
- models,
- host,
- apiKeyCount,
- initial,
-}: {
- runtimes: FormRuntime[];
- models: FormModel[];
- host: FormHost;
- apiKeyCount: number;
- initial?: FormInitial;
-}) {
- const router = useRouter();
- const editing = !!initial?.id;
- const [runtimeId, setRuntimeId] = useState(
- initial?.runtimeId ??
- runtimes.find((r) => r.imageState === "present")?.id ??
- "",
- );
- const runtime = runtimes.find((r) => r.id === runtimeId) ?? null;
- const engine = runtime?.engine ?? "llama.cpp";
- const accelerator: RuntimeAccelerator = runtime?.accelerator ?? "cpu";
- const gpu = accelerator !== "cpu";
-
- const [query, setQuery] = useState("");
- const [modelId, setModelId] = useState(initial?.modelId ?? "");
- const servable = models.filter((m) =>
- engine === "llama.cpp" ? m.candidates.gguf.length > 0 : m.candidates.vllm,
- );
- const shown = servable.filter((m) =>
- m.repoId.toLowerCase().includes(query.trim().toLowerCase()),
- );
- const model = servable.find((m) => m.id === modelId) ?? null;
-
- const o = initial?.options;
- const [modelFile, setModelFile] = useState(o?.modelFile ?? "");
- const [mmproj, setMmproj] = useState(o?.mmproj ?? "");
- const [draftFile, setDraftFile] = useState(o?.draftFile ?? "");
- const [name, setName] = useState(initial?.name ?? "");
- const [contextSize, setContextSize] = useState(
- String(o?.contextSize ?? 4096),
- );
- const [threads, setThreads] = useState(
- o?.threads != null ? String(o.threads) : "",
- );
- const [parallel, setParallel] = useState(
- o?.parallel != null ? String(o.parallel) : "1",
- );
- const [cacheTypeK, setCacheTypeK] = useState(o?.cacheTypeK ?? "");
- const [cacheTypeV, setCacheTypeV] = useState(o?.cacheTypeV ?? "");
- const [flashAttn, setFlashAttn] = useState(o?.flashAttn ?? "");
- const [webui, setWebui] = useState(o?.webui !== false);
- const [requireApiKey, setRequireApiKey] = useState(!!o?.requireApiKey);
- const [batchSize, setBatchSize] = useState(
- o?.batchSize != null ? String(o.batchSize) : "",
- );
- const [ubatchSize, setUbatchSize] = useState(
- o?.ubatchSize != null ? String(o.ubatchSize) : "",
- );
- const [dtype, setDtype] = useState(o?.dtype ?? "");
- const [maxNumSeqs, setMaxNumSeqs] = useState(
- o?.maxNumSeqs != null ? String(o.maxNumSeqs) : "",
- );
- const [kvCacheGb, setKvCacheGb] = useState(
- o?.kvCacheGb != null ? String(o.kvCacheGb) : "",
- );
- const [cacheRam, setCacheRam] = useState(
- o
- ? o.cacheRamMb != null
- ? String(o.cacheRamMb)
- : ""
- : String(DEFAULT_CACHE_RAM_MB),
- );
- const [gpuIds, setGpuIds] = useState(o?.gpus ?? []);
- const [gpuLayers, setGpuLayers] = useState(o?.gpuLayers ?? "auto");
- const [splitMode, setSplitMode] = useState(o?.splitMode ?? "");
- const [tensorSplit, setTensorSplit] = useState(o?.tensorSplit ?? "");
- const [cpuMoe, setCpuMoe] = useState(!!o?.cpuMoe);
- const [nCpuMoe, setNCpuMoe] = useState(
- o?.nCpuMoe != null ? String(o.nCpuMoe) : "",
- );
- const [tensorParallel, setTensorParallel] = useState(
- o?.tensorParallel != null ? String(o.tensorParallel) : "",
- );
- const [gpuMemUtil, setGpuMemUtil] = useState(
- o?.gpuMemoryUtilization != null ? String(o.gpuMemoryUtilization) : "",
- );
- const [argRows, setArgRows] = useState(() => argsToRows(o?.extraArgs ?? []));
- const [cpus, setCpus] = useState(
- initial?.cpus != null ? String(initial.cpus) : "",
- );
- const [memoryMb, setMemoryMb] = useState(
- initial?.memoryMb != null ? String(initial.memoryMb) : "",
- );
- const [memoryTouched, setMemoryTouched] = useState(!!initial?.memoryMb);
- const [hostPort, setHostPort] = useState(
- initial?.hostPort != null ? String(initial.hostPort) : "",
- );
- const [saving, setSaving] = useState(false);
-
- function pickModel(m: FormModel) {
- setModelId(m.id);
- const first = m.candidates.gguf[0];
- setModelFile(engine === "llama.cpp" ? (first?.path ?? "") : "");
- setMmproj(m.candidates.mmproj[0]?.path ?? "");
- setDraftFile("");
- if (!editing)
- setName(
- `${m.repoId.split("/")[1]}${first && engine === "llama.cpp" ? ` ${quantGroup(first.path) ?? ""}` : ""}`.trim(),
- );
- }
-
- const options: DeploymentOptions = {
- modelFile: engine === "llama.cpp" ? modelFile : "",
- mmproj: engine === "llama.cpp" && mmproj ? mmproj : null,
- draftFile: engine === "llama.cpp" && draftFile ? draftFile : null,
- draftType:
- model?.candidates.drafts.find((d) => d.path === draftFile)?.type ?? null,
- contextSize: intOrNull(contextSize) ?? 4096,
- threads: intOrNull(threads),
- parallel: intOrNull(parallel),
- batchSize: engine === "llama.cpp" ? intOrNull(batchSize) : null,
- ubatchSize: engine === "llama.cpp" ? intOrNull(ubatchSize) : null,
- cacheTypeK: engine === "llama.cpp" && cacheTypeK ? cacheTypeK : null,
- cacheTypeV: engine === "llama.cpp" && cacheTypeV ? cacheTypeV : null,
- flashAttn:
- engine === "llama.cpp" && flashAttn
- ? (flashAttn as "auto" | "on" | "off")
- : null,
- webui: engine === "llama.cpp" ? webui : null,
- requireApiKey,
- dtype: engine === "vllm" && dtype ? dtype : null,
- maxNumSeqs: engine === "vllm" ? intOrNull(maxNumSeqs) : null,
- kvCacheGb: engine === "vllm" && !gpu ? numOrNull(kvCacheGb) : null,
- cacheRamMb: engine === "llama.cpp" ? intOrNullSigned(cacheRam) : null,
- gpus: accelerator === "nvidia" && gpuIds.length ? gpuIds : null,
- gpuLayers:
- gpu && engine === "llama.cpp" && gpuLayers !== "auto" ? gpuLayers : null,
- splitMode:
- gpu && engine === "llama.cpp" && splitMode
- ? (splitMode as "none" | "layer" | "row" | "tensor")
- : null,
- tensorSplit:
- gpu && engine === "llama.cpp" && tensorSplit.trim()
- ? tensorSplit.trim()
- : null,
- cpuMoe: gpu && engine === "llama.cpp" ? cpuMoe : null,
- nCpuMoe:
- gpu && engine === "llama.cpp" && !cpuMoe ? intOrNull(nCpuMoe) : null,
- tensorParallel: gpu && engine === "vllm" ? intOrNull(tensorParallel) : null,
- gpuMemoryUtilization:
- gpu && engine === "vllm" ? numOrNull(gpuMemUtil) : null,
- extraArgs: rowsToArgs(argRows),
- };
-
- const fileBytes = model
- ? engine === "llama.cpp"
- ? (model.candidates.gguf.find((g) => g.path === modelFile)?.size ?? 0) +
- (model.candidates.mmproj.find((g) => g.path === mmproj)?.size ?? 0) +
- (model.candidates.drafts.find((g) => g.path === draftFile)?.size ?? 0)
- : (model.candidates.vllm?.size ?? 0)
- : 0;
- const estimate = model
- ? estimateMemoryMb(fileBytes, options.contextSize, engine, {
- ...options,
- accelerator,
- })
- : null;
- const hostGpus = host?.gpus ?? [];
- const chosenGpus = gpuIds.length
- ? hostGpus.filter((g) => gpuIds.includes(g.uuid))
- : hostGpus;
- const vramMb = chosenGpus.reduce((s, g) => s + g.memoryMb, 0);
- // Intel/AMD GPUs come in as /dev/dri: all of them, VRAM as detected (or set in Settings → Hardware).
- const driGpus = (host?.hardwareGpus ?? []).filter((g) => (accelerator === "rocm" ? g.vendor === "amd" : g.vendor === "intel" || g.vendor === "amd"));
- const gpuVramMb = accelerator === "nvidia" ? vramMb || null : driGpus.some((g) => g.vramMb) ? driGpus.reduce((s, g) => s + (g.vramMb ?? 0), 0) : null;
- const vramEstimate = model && gpu ? estimateVramMb(fileBytes, options.contextSize, engine, options, gpuVramMb) : null;
- const memory = memoryTouched ? intOrNull(memoryMb) : estimate;
- const preview =
- runtime && model
- ? renderCommand(
- runtime.image,
- buildCommand({
- engine,
- options,
- model,
- runtime: {
- env: runtime.env,
- extraArgs: runtime.extraArgs,
- accelerator,
- },
- apiKeys: Array.from(
- { length: apiKeyCount },
- () => API_KEY_PLACEHOLDER,
- ),
- }),
- )
- : null;
- const noBf16 = host && !host.cpuFeatures.includes("avx512_bf16");
-
- async function submit(start: boolean) {
- if (!runtime || !model) return;
- setSaving(true);
- try {
- const body = {
- name: name.trim() || model.repoId,
- runtimeId: runtime.id,
- modelId: model.id,
- options,
- cpus: numOrNull(cpus),
- memoryMb: memory,
- hostPort: intOrNull(hostPort),
- start,
- };
- const res = await fetch(
- editing ? `/api/deployments/${initial!.id}` : "/api/deployments",
- {
- method: editing ? "PUT" : "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body),
- },
- );
- const json = await res.json().catch(() => ({}));
- if (!res.ok) {
- toast.error(json.error?.message ?? `Could not save (${res.status})`);
- return;
- }
- const id = editing ? initial!.id : json.id;
- if (editing && start)
- await fetch(`/api/deployments/${id}/start`, { method: "POST" });
- toast.success(start ? "Deployment starting" : "Deployment saved");
- router.push(`/deployments/${id}`);
- router.refresh();
- } finally {
- setSaving(false);
- }
- }
-
- return (
-
-
- {runtimes.length === 0 ? (
-
- No runtimes yet.{" "}
-
- Add one in Settings
-
- .
-
- ) : (
-
- {runtimes.map((r) => {
- const ready = r.imageState === "present";
- return (
- {
- setRuntimeId(r.id);
- if (r.engine !== engine) setModelId("");
- }}
- className={cn(
- "flex flex-col items-start gap-1 rounded-lg border px-3 py-2.5 text-left transition-colors disabled:cursor-not-allowed disabled:opacity-50",
- runtimeId === r.id
- ? "border-primary bg-primary/5 ring-1 ring-primary"
- : "hover:bg-muted/50",
- )}
- >
-
-
-
- {r.name}
-
- {runtimeId === r.id && (
-
- )}
-
-
- {r.image}
-
-
- {r.engine === "vllm"
- ? "vLLM · safetensors"
- : "llama.cpp · GGUF"}
- {!ready && " · image not pulled"}
-
-
- );
- })}
-
- )}
- {runtimes.some((r) => r.imageState !== "present") && (
-
- Runtimes whose image isn't pulled yet can't be picked.{" "}
-
- Pull them in Settings
-
- .
-
- )}
-
-
- {runtime && (
-
- {servable.length === 0 ? (
-
- No downloaded model fits this runtime.{" "}
-
- Add one in the library
-
- {engine === "vllm"
- ? " (a safetensors repo, e.g. HuggingFaceTB/SmolLM2-135M-Instruct)."
- : "."}
-
- ) : (
- <>
- {servable.length > 6 && (
-
-
- setQuery(e.target.value)}
- placeholder="Search models…"
- className="pl-8"
- />
-
- )}
-
- {shown.map((m) => (
- pickModel(m)}
- className={cn(
- "flex items-center justify-between gap-3 px-3 py-2 text-left text-sm hover:bg-muted/50",
- modelId === m.id && "bg-primary/5",
- )}
- >
-
- {modelId === m.id ? (
-
- ) : (
-
- )}
- {m.repoId}
-
-
- {engine === "llama.cpp"
- ? `${m.candidates.gguf.length} GGUF${m.candidates.mmproj.length ? " · vision" : ""}${m.candidates.drafts.length ? " · MTP/draft" : ""}`
- : formatBytes(m.candidates.vllm?.size ?? 0)}
-
-
- ))}
-
-
- {model && engine === "llama.cpp" && (
-
-
-
- {model.candidates.gguf.map((g) => (
-
- setModelFile(g.path)}
- className="accent-primary"
- />
-
- {quantGroup(g.path) ?? g.path}
-
-
- {formatBytes(g.size)}
-
-
- ))}
-
-
-
- setMmproj(e.target.value)}
- disabled={model.candidates.mmproj.length === 0}
- >
- None
- {model.candidates.mmproj.map((m) => (
-
- {m.path} ({formatBytes(m.size)})
-
- ))}
-
-
-
- setDraftFile(e.target.value)}
- disabled={model.candidates.drafts.length === 0}
- >
- Off
- {model.candidates.drafts.map((d) => (
-
- {d.type === "draft-mtp" ? "MTP: " : "Draft: "}
- {d.path} ({formatBytes(d.size)})
-
- ))}
-
-
-
- )}
- {model && (
-
- {[modelFile, mmproj, draftFile].filter(Boolean).map((p) => (
-
-
-
- ))}
- {formatBytes(fileBytes)} of model files
-
- )}
- >
- )}
-
- )}
-
- {runtime && model && (
-
-
-
- setName(e.target.value)}
- maxLength={80}
- />
-
-
- setHostPort(e.target.value.replace(/\D/g, ""))}
- inputMode="numeric"
- placeholder="not published"
- />
-
-
- setRequireApiKey(v === true)}
- className="mt-0.5"
- disabled={apiKeyCount === 0 && !requireApiKey}
- />
-
- Require an API key
-
- {apiKeyCount === 0 ? (
- <>
- No keys yet.{" "}
-
- Add one in Settings
-
- .
- >
- ) : (
- <>
- Accepts any of the {apiKeyCount} key
- {apiKeyCount === 1 ? "" : "s"} from{" "}
-
- Settings → Runtime API keys
- {" "}
- as{" "}
- Authorization: Bearer.
- {engine === "vllm" ? " vLLM only checks /v1 paths." : ""}
- >
- )}
-
-
-
- {engine === "llama.cpp" && (
-
- setWebui(v === true)}
- className="mt-0.5"
- />
-
- Serve the llama.cpp web UI
-
- {webui
- ? hostPort
- ? `Opens at http://:${hostPort}/ (no login on that port).`
- : "Set a host port to open it."
- : "Off: passes --no-webui; the API keeps working."}
-
-
-
- )}
-
-
-
-
-
-
- setContextSize(e.target.value.replace(/\D/g, ""))
- }
- inputMode="numeric"
- className="w-28"
- />
- {CONTEXT_PRESETS.map((c) => (
- setContextSize(String(c))}
- >
- {c / 1024}k
-
- ))}
-
-
- {engine === "vllm" ? (
-
-
- setMaxNumSeqs(e.target.value.replace(/\D/g, ""))
- }
- inputMode="numeric"
- placeholder="default"
- />
-
- ) : (
-
-
- setParallel(e.target.value.replace(/\D/g, ""))
- }
- inputMode="numeric"
- placeholder="auto"
- />
-
- )}
-
-
- {gpu && (
-
- {accelerator === "nvidia" && (
-
-
GPUs
- {!host?.nvidia ? (
-
- Docker on this host has no NVIDIA runtime. Install the
- NVIDIA Container Toolkit, then restart the worker.
-
- ) : hostGpus.length === 0 ? (
-
- No GPUs detected yet; the deployment gets all of them.
-
- ) : (
-
- {hostGpus.map((g) => (
-
- {
- const all = hostGpus.map((x) => x.uuid);
- const cur = gpuIds.length ? gpuIds : all;
- const next = v
- ? [...new Set([...cur, g.uuid])]
- : cur.filter((x) => x !== g.uuid);
- setGpuIds(next.length === all.length ? [] : next);
- }}
- />
-
- {g.index}: {g.name}
-
-
- {formatBytes(g.memoryMb * 2 ** 20)}
-
-
- ))}
-
- {gpuIds.length === 0
- ? "All GPUs"
- : `${gpuIds.length} of ${hostGpus.length}`}{" "}
- · {formatBytes(vramMb * 2 ** 20)} VRAM
- {fileBytes > 0 &&
- ` · model files ${formatBytes(fileBytes)}`}
-
-
- )}
-
- )}
- {accelerator !== "nvidia" && driGpus.length > 0 && (
-
- {driGpus.map((g) => `${g.name ?? "GPU"}${g.vramMb ? ` (${formatBytes(g.vramMb * 2 ** 20)})` : ""}`).join(", ")} via /dev/dri
-
- )}
- {model && (
- gpuVramMb ? "text-amber-700 dark:text-amber-300" : "text-muted-foreground"}`}>
- {vramEstimate == null
- ? "VRAM need: depends on how many layers/experts go to the GPU."
- : `VRAM need, roughly: ${formatBytes(vramEstimate * 2 ** 20)}${gpuVramMb ? ` of ${formatBytes(gpuVramMb * 2 ** 20)}` : ""}${
- engine === "vllm" ? " (vLLM reserves its GPU memory share up front)" : " (weights, KV cache, compute buffers)"
- }${gpuVramMb != null && vramEstimate > gpuVramMb ? ". Doesn't fit: lower the context, quantize the KV cache or offload fewer layers." : ""}`}
-
- )}
- {engine === "llama.cpp" ? (
- <>
-
-
-
- setGpuLayers(
- e.target.value === "n" ? "20" : e.target.value,
- )
- }
- >
- auto
- all
- number…
-
- {gpuLayers !== "auto" && gpuLayers !== "all" && (
-
- setGpuLayers(
- e.target.value.replace(/\D/g, "") || "0",
- )
- }
- inputMode="numeric"
- className="w-20"
- aria-label="Number of GPU layers"
- />
- )}
-
-
-
- setSplitMode(e.target.value)}
- >
- default (layer)
- none (one GPU)
- layer
- row
- tensor
-
-
-
-
- setTensorSplit(e.target.value.replace(/[^\d.,]/g, ""))
- }
- placeholder="even"
- />
-
-
-
- {
- setCpuMoe(e.target.value === "all");
- if (e.target.value === "") setNCpuMoe("");
- if (e.target.value === "n" && !nCpuMoe)
- setNCpuMoe("10");
- }}
- >
- none
- all experts
- first N layers…
-
- {!cpuMoe && nCpuMoe !== "" && (
-
- setNCpuMoe(e.target.value.replace(/\D/g, ""))
- }
- inputMode="numeric"
- className="w-20"
- aria-label="Layers with MoE experts in RAM"
- />
- )}
-
-
- >
- ) : (
- <>
-
-
- setTensorParallel(e.target.value.replace(/\D/g, ""))
- }
- inputMode="numeric"
- placeholder={String(Math.max(1, chosenGpus.length))}
- />
-
-
-
- setGpuMemUtil(e.target.value.replace(/[^\d.]/g, ""))
- }
- inputMode="decimal"
- placeholder="0.9"
- />
-
- >
- )}
-
- )}
-
- {engine === "llama.cpp" ? (
-
-
-
- setThreads(e.target.value.replace(/\D/g, ""))
- }
- inputMode="numeric"
- placeholder="auto"
- />
-
-
- setFlashAttn(e.target.value)}
- >
- auto
- on
- off
-
-
-
-
- setBatchSize(e.target.value.replace(/\D/g, ""))
- }
- inputMode="numeric"
- placeholder="2048"
- />
-
-
-
- setUbatchSize(e.target.value.replace(/\D/g, ""))
- }
- inputMode="numeric"
- placeholder="512"
- />
-
-
- ) : (
-
-
- setDtype(e.target.value)}
- >
- runtime default
- bfloat16
- float32
- float16
- auto
-
-
-
- )}
-
-
- {engine === "llama.cpp" ? (
- <>
-
- setCacheTypeK(e.target.value)}
- >
- f16 (default)
- {KV_TYPES.filter((t) => t !== "f16").map((t) => (
-
- {t}
-
- ))}
-
-
-
- setCacheTypeV(e.target.value)}
- >
- f16 (default)
- {KV_TYPES.filter((t) => t !== "f16").map((t) => (
-
- {t}
-
- ))}
-
-
-
-
- setCacheRam(e.target.value.replace(/[^\d-]/g, ""))
- }
- inputMode="numeric"
- placeholder="8192"
- />
-
- >
- ) : gpu ? (
-
- On a GPU, vLLM sizes the KV cache from the GPU memory share
- above.
-
- ) : (
-
-
- setKvCacheGb(e.target.value.replace(/[^\d.]/g, ""))
- }
- inputMode="decimal"
- placeholder={runtime.env.VLLM_CPU_KVCACHE_SPACE ?? "4"}
- />
-
- )}
-
-
-
-
- setCpus(e.target.value.replace(/[^\d.]/g, ""))}
- inputMode="decimal"
- placeholder="no limit"
- />
-
-
- Estimate:{" "}
- {estimate != null ? formatBytes(estimate * 2 ** 20) : "–"}
- {host?.memoryBytes
- ? ` · host: ${formatBytes(host.memoryBytes)}`
- : ""}
- {memoryTouched && (
- setMemoryTouched(false)}
- >
- use estimate
-
- )}
- >
- }
- >
- {
- setMemoryTouched(true);
- setMemoryMb(e.target.value.replace(/\D/g, ""));
- }}
- inputMode="numeric"
- />
-
-
-
-
-
-
-
- )}
-
- {runtime && model && (
-
- {preview && (
-
-
-
- {preview}
-
-
-
-
-
- )}
-
- router.back()}>
- Cancel
-
- submit(false)}
- >
- {editing ? "Save" : "Create"}
-
- submit(true)}
- >
- {editing ? "Save & start" : "Create & start"}
-
-
-
- )}
-
- );
-}
diff --git a/src/app/(app)/deployments/deployment-list.tsx b/src/app/(app)/deployments/deployment-list.tsx
deleted file mode 100644
index 6ef7b63..0000000
--- a/src/app/(app)/deployments/deployment-list.tsx
+++ /dev/null
@@ -1,210 +0,0 @@
-"use client";
-
-import {
- ExternalLinkIcon,
- PlayIcon,
- RocketIcon,
- SquareIcon,
-} from "lucide-react";
-import Link from "next/link";
-import { useEffect, useState } from "react";
-import { DeploymentStateBadge } from "@/components/deployment-state";
-import { RequestedByBadge } from "@/components/requested-by-badge";
-import { NativeSelect } from "@/components/ui/native-select";
-import { Button, buttonVariants } from "@/components/ui/button";
-import { Card } from "@/components/ui/card";
-import { useHostname, webUiUrl } from "@/hooks/use-hostname";
-import type { DeploymentRow } from "@/lib/deployments";
-import { formatBytes } from "@/lib/format";
-import { quantGroup } from "@/lib/selection";
-import { startDeployment, stopDeployment } from "./actions";
-
-type Row = Omit<
- DeploymentRow,
- "startedAt" | "readyAt" | "stoppedAt" | "createdAt"
-> & {
- startedAt: string | null;
- readyAt: string | null;
- stoppedAt: string | null;
- createdAt: string;
-};
-
-const isActive = (r: Row) =>
- r.desiredState === "running" ||
- r.state === "starting" ||
- r.state === "running" ||
- r.state === "stopping";
-
-/** Live list (polls every 2 s while something is starting/stopping, else every 5 s). */
-export function DeploymentList({ rows: initial }: { rows: Row[] }) {
- const [rows, setRows] = useState(initial);
- // "" = everything, "-" = created in the UI, else a token name.
- const [by, setBy] = useState("");
- const tokens = [
- ...new Set(rows.map((r) => r.requestedBy).filter((x): x is string => !!x)),
- ].sort();
- const shown = rows.filter(
- (r) => !by || (by === "-" ? !r.requestedBy : r.requestedBy === by),
- );
- const hostname = useHostname();
- const busy = rows.some(
- (r) =>
- r.state === "starting" ||
- r.state === "stopping" ||
- (r.desiredState === "running") !== (r.state === "running"),
- );
-
- async function reload() {
- const res = await fetch("/api/deployments", { cache: "no-store" }).catch(
- () => null,
- );
- if (res?.ok) setRows(await res.json());
- }
- useEffect(() => {
- const t = setInterval(reload, busy ? 2_000 : 5_000);
- return () => clearInterval(t);
- }, [busy]);
-
- if (rows.length === 0) {
- return (
-
-
-
- No deployments yet. Pick a runtime and a downloaded model to start
- one.
-
-
- New deployment
-
-
- );
- }
-
- return (
-
- {tokens.length > 0 && (
-
- Requested by
- setBy(e.target.value)}
- className="h-7 text-xs"
- aria-label="Requested by"
- >
- Anyone
- Created in Kaname
- {tokens.map((t) => (
-
- {t} (API)
-
- ))}
-
-
- )}
-
- {shown.map((r) => {
- const file = r.options.modelFile
- ? (quantGroup(r.options.modelFile) ?? r.options.modelFile)
- : null;
- const loadSecs =
- r.readyAt && r.startedAt
- ? (new Date(r.readyAt).getTime() -
- new Date(r.startedAt).getTime()) /
- 1000
- : null;
- return (
-
-
-
-
- {r.name}
-
-
- {r.repoId}
- {file && ` · ${file}`}
- {r.options.mmproj && " · vision"}
- {r.options.draftFile && " · MTP/draft"}
-
-
- {r.runtimeName}
-
- {r.protected && (
-
- protected
-
- )}
- {r.startRequestedAt && (
-
- start awaits approval
-
- )}
-
-
-
-
-
-
- {r.state === "running" && r.stats
- ? `CPU ${(r.stats.cpuPercent / 100).toFixed(1)} cores · RAM ${formatBytes(r.stats.memoryBytes)}${r.memoryMb ? ` / ${formatBytes(r.memoryMb * 2 ** 20)}` : ""}`
- : r.state === "failed"
- ? (r.error?.split("\n")[0] ?? "failed")
- : `ctx ${r.options.contextSize}${r.memoryMb ? ` · ${formatBytes(r.memoryMb * 2 ** 20)} RAM` : ""}`}
- {r.state === "running" &&
- loadSecs != null &&
- ` · loaded in ${loadSecs.toFixed(1)} s`}
-
-
- {r.state === "running" && webUiUrl(r, hostname) && (
-
-
- Web UI
-
- )}
- {isActive(r) ? (
-
- (await stopDeployment(r.id)) && reload()
- }
- >
-
- Stop
-
- ) : (
-
- (await startDeployment(r.id)) && reload()
- }
- >
-
- Start
-
- )}
-
-
-
- );
- })}
-
-
- );
-}
diff --git a/src/app/(app)/deployments/form-data.ts b/src/app/(app)/deployments/form-data.ts
deleted file mode 100644
index 2d9e907..0000000
--- a/src/app/(app)/deployments/form-data.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import "server-only";
-import { listApiKeys } from "@/lib/api-keys";
-import { listDeployableModels } from "@/lib/deployments";
-import { applyOverrides } from "@/lib/hardware";
-import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
-import { getHardwareOverrides } from "@/lib/settings";
-import type { FormHost, FormModel, FormRuntime } from "./deployment-form";
-
-/** Everything the deployment form needs: runtimes, servable models, host facts, API key count. */
-export async function formData(): Promise<{
- runtimes: FormRuntime[];
- models: FormModel[];
- host: FormHost;
- apiKeyCount: number;
-}> {
- const [runtimes, models, docker, keys, overrides] = await Promise.all([
- listRuntimes(),
- listDeployableModels(),
- getDockerInfo(),
- listApiKeys(),
- getHardwareOverrides(),
- ]);
- return {
- runtimes: runtimes.map((r) => ({
- id: r.id,
- name: r.name,
- engine: r.engine,
- image: r.image,
- imageState: r.imageState,
- env: r.env,
- extraArgs: r.extraArgs,
- accelerator: r.accelerator,
- })),
- models,
- host: docker
- ? {
- cpus: docker.cpus,
- memoryBytes: docker.memoryBytes,
- cpuFeatures: docker.cpuFeatures,
- nvidia: !!docker.nvidia,
- gpus: docker.gpus ?? [],
- hardwareGpus: applyOverrides(docker.hardware, overrides)?.gpus ?? [],
- }
- : null,
- apiKeyCount: keys.length,
- };
-}
diff --git a/src/app/(app)/deployments/new/page.tsx b/src/app/(app)/deployments/new/page.tsx
deleted file mode 100644
index 4c951dd..0000000
--- a/src/app/(app)/deployments/new/page.tsx
+++ /dev/null
@@ -1,19 +0,0 @@
-import type { Metadata } from "next";
-import { deployPreset } from "@/lib/deployments";
-import { DeploymentForm } from "../deployment-form";
-import { formData } from "../form-data";
-
-export const dynamic = "force-dynamic";
-export const metadata: Metadata = { title: "New deployment" };
-
-/** `?model=` (the library's "Deploy") preselects the model and a runtime that can serve it. */
-export default async function NewDeploymentPage({ searchParams }: PageProps<"/deployments/new">) {
- const { model } = await searchParams;
- const [data, preset] = await Promise.all([formData(), typeof model === "string" ? deployPreset(model) : null]);
- return (
-
-
New deployment
-
-
- );
-}
diff --git a/src/app/(app)/deployments/page.tsx b/src/app/(app)/deployments/page.tsx
deleted file mode 100644
index df71312..0000000
--- a/src/app/(app)/deployments/page.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import type { Metadata } from "next";
-import Link from "next/link";
-import { buttonVariants } from "@/components/ui/button";
-import { listDeployments } from "@/lib/deployments";
-import { getDockerInfo } from "@/lib/runtimes";
-import { DeploymentList } from "./deployment-list";
-
-export const dynamic = "force-dynamic";
-export const metadata: Metadata = { title: "Deployments" };
-
-export default async function DeploymentsPage() {
- const [rows, docker] = await Promise.all([listDeployments(), getDockerInfo()]);
- return (
-
-
-
Deployments
-
- New deployment
-
-
- {!docker?.connected && (
-
- {docker ? `Docker isn't reachable: ${docker.error}` : "Docker isn't connected, so deployments can't start."} See{" "}
-
- Settings → Runtimes
-
- .
-
- )}
-
-
- );
-}
diff --git a/src/app/(app)/endpoints/[id]/benchmark-start.tsx b/src/app/(app)/endpoints/[id]/benchmark-start.tsx
new file mode 100644
index 0000000..80f950e
--- /dev/null
+++ b/src/app/(app)/endpoints/[id]/benchmark-start.tsx
@@ -0,0 +1,215 @@
+"use client";
+
+import { BadgeCheckIcon, GaugeIcon, GitCompareArrowsIcon, Loader2Icon } from "lucide-react";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Input } from "@/components/ui/input";
+import { NativeSelect } from "@/components/ui/native-select";
+import { type BenchmarkPhase, QUALITY_SECTIONS, type QualitySection } from "@/lib/db/schema";
+import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
+import { cn } from "@/lib/utils";
+
+const PHASES: { id: BenchmarkPhase; label: string; hint: string }[] = [
+ { id: "decode", label: "Generation", hint: "single request, 8 prompt categories" },
+ { id: "prefill", label: "Prompt processing", hint: "growing input lengths, up to the context size" },
+ { id: "concurrency", label: "Parallel requests", hint: "1, 2, 4 and 8 at once" },
+];
+
+type Mode = "run" | "ab" | "quality";
+type Peer = { id: string; name: string; model: string | null; models: string[] };
+
+/** Benchmark an endpoint: a BetterBench run, a paired A/B against another endpoint, or the quality eval. */
+export function BenchmarkStart({ endpoint, peers }: { endpoint: { id: string; name: string; model: string | null; models: string[] }; peers: Peer[] }) {
+ const router = useRouter();
+ const [tab, setTab] = useState("run");
+ const [model, setModel] = useState(endpoint.model ?? "");
+ const [mode, setMode] = useState("quick");
+ const [passes, setPasses] = useState("10");
+ const [phases, setPhases] = useState(["decode", "prefill", "concurrency"]);
+ const [label, setLabel] = useState("");
+ const [description, setDescription] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [peerId, setPeerId] = useState("");
+ const [mde, setMde] = useState("1");
+ const [maxPairs, setMaxPairs] = useState("200");
+ const [sections, setSections] = useState([...QUALITY_SECTIONS]);
+
+ // The model a run requests: the one picked here, the endpoint's, or the only one it serves.
+ const runModel = model || (endpoint.models.length === 1 ? endpoint.models[0] : "");
+ const peer = peers.find((p) => p.id === peerId);
+ const peerServes = !peer || !runModel || peer.models.length === 0 || peer.models.includes(runModel);
+
+ async function start(body: Record) {
+ setBusy(true);
+ try {
+ const res = await fetch("/api/benchmarks", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ endpointId: endpoint.id, model: runModel || null, label: label.trim() || null, description: description.trim() || null, ...body }),
+ });
+ const json = await res.json().catch(() => ({}));
+ if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`);
+ router.push(`/benchmarks/${json.id}`);
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ const TABS: { id: Mode; label: string; icon: typeof GaugeIcon }[] = [
+ { id: "run", label: "Speed", icon: GaugeIcon },
+ { id: "ab", label: "A/B", icon: GitCompareArrowsIcon },
+ { id: "quality", label: "Quality", icon: BadgeCheckIcon },
+ ];
+
+ const labelInputs = (
+ <>
+ setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
+ {tab !== "quality" && (
+ setDescription(e.target.value)} maxLength={4000} placeholder="What this run tries out (optional; published with it, default: the endpoint's notes)" />
+ )}
+ >
+ );
+
+ return (
+
+
+
+
+ Benchmark
+
+
+
+
+
+ {TABS.map((t) => (
+ setTab(t.id)}
+ className={cn("flex items-center gap-1 rounded-md px-2.5 py-1 text-xs", tab === t.id ? "bg-background font-medium shadow-sm" : "text-muted-foreground hover:text-foreground")}
+ >
+
+ {t.label}
+
+ ))}
+
+ {endpoint.models.length > 1 && (
+
setModel(e.target.value)} className="h-8 max-w-72 text-xs" aria-label="Model">
+ Choose a model…
+ {endpoint.models.map((m) => (
+
+ {m}
+
+ ))}
+
+ )}
+
+
+ {tab === "run" && (
+ <>
+
+ setMode(e.target.value)} aria-label="Run length">
+ Quick: 5 passes (smoke test)
+ Full: 20 passes (comparable)
+ Custom number of passes
+
+ {mode === "custom" && (
+ setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes per category" />
+ )}
+
+
+ {PHASES.map((p) => (
+
+ setPhases((cur) => (v ? [...cur, p.id] : cur.filter((x) => x !== p.id)))} className="mt-0.5" />
+
+ {p.label}
+ {p.hint}
+
+
+ ))}
+
+ {labelInputs}
+ start({ quick: mode === "quick", passes: mode === "custom" ? Number(passes) || 10 : null, phases: phases.length === PHASES.length ? [] : phases })}
+ disabled={busy || phases.length === 0}
+ >
+ {busy ? : }
+ Run benchmark
+
+ Kaname checks the server first. Keep other load off it while the run lasts; on a CPU a full run can take hours.
+ >
+ )}
+
+ {tab === "ab" && (
+ <>
+
+ Paired A/B: the same prompts go to this endpoint (A) and another one serving the same model (B), alternating, until the difference is known to ±the target.
+
+ {peers.length === 0 ? (
+ Add a second endpoint serving the same model (e.g. with another KV cache type or engine build) to compare.
+ ) : (
+ <>
+ setPeerId(e.target.value)} aria-label="Endpoint B">
+ Choose B…
+ {peers.map((p) => (
+
+ {p.name}
+ {runModel && p.models.length > 0 && !p.models.includes(runModel) ? " (doesn't serve this model)" : ""}
+
+ ))}
+
+ {!peerServes && {peer?.name} doesn't list {runModel}. Both sides get the same model name.
}
+
+
+ Target precision (±%)
+ setMde(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" />
+
+
+ Max pairs
+ setMaxPairs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" />
+
+
+ {labelInputs}
+ start({ endpointBId: peerId, mdePct: Number(mde) || 1, maxPairs: Math.max(12, Number(maxPairs) || 200) })} disabled={busy || !peer || !peerServes}>
+ {busy ? : }
+ Start A/B
+
+ >
+ )}
+ >
+ )}
+
+ {tab === "quality" && (
+ <>
+
+ A short, deterministic check of the answers (greedy decoding, fixed seed, thinking off): to see whether a quant, KV cache type or build changes quality, next to
+ the speed numbers.
+
+
+ {QUALITY_SECTIONS.map((s) => (
+
+ setSections((cur) => (v ? [...cur, s] : cur.filter((x) => x !== s)))} className="mt-0.5" />
+
+ {SECTION_LABEL[s]}
+ {SECTION_HINT[s]}
+
+
+ ))}
+
+ {labelInputs}
+ start({ kind: "eval", evalSections: sections.length === QUALITY_SECTIONS.length ? [] : sections })} disabled={busy || sections.length === 0}>
+ {busy ? : }
+ Run quality eval
+
+ >
+ )}
+
+
+ );
+}
diff --git a/src/app/(app)/endpoints/[id]/edit/page.tsx b/src/app/(app)/endpoints/[id]/edit/page.tsx
new file mode 100644
index 0000000..8c09e2d
--- /dev/null
+++ b/src/app/(app)/endpoints/[id]/edit/page.tsx
@@ -0,0 +1,18 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { getEndpoint } from "@/lib/endpoints";
+import { EndpointForm } from "../../endpoint-form";
+
+export const dynamic = "force-dynamic";
+export const metadata: Metadata = { title: "Edit endpoint" };
+
+export default async function EditEndpointPage({ params }: PageProps<"/endpoints/[id]/edit">) {
+ const endpoint = await getEndpoint((await params).id);
+ if (!endpoint) notFound();
+ return (
+
+
Edit {endpoint.name}
+
+
+ );
+}
diff --git a/src/app/(app)/endpoints/[id]/endpoint-header.tsx b/src/app/(app)/endpoints/[id]/endpoint-header.tsx
new file mode 100644
index 0000000..2300278
--- /dev/null
+++ b/src/app/(app)/endpoints/[id]/endpoint-header.tsx
@@ -0,0 +1,101 @@
+"use client";
+
+import { Loader2Icon, PencilIcon, PlugZapIcon, Trash2Icon } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { toast } from "sonner";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";
+import { Button, buttonVariants } from "@/components/ui/button";
+import { Card, CardContent } from "@/components/ui/card";
+import type { EndpointView } from "@/lib/endpoints";
+import { ProbeResult } from "../endpoint-form";
+import { EndpointStatus } from "../endpoint-status";
+
+/** Name, URL, connection test, edit and delete. */
+export function EndpointHeader({ endpoint, runCount }: { endpoint: EndpointView; runCount: number }) {
+ const router = useRouter();
+ const [probe, setProbe] = useState(endpoint.probe);
+ const [testing, setTesting] = useState(false);
+
+ async function test() {
+ setTesting(true);
+ try {
+ const res = await fetch(`/api/endpoints/${endpoint.id}/test`, { method: "POST" });
+ const json = await res.json().catch(() => ({}));
+ if (!res.ok) return toast.error(json.error?.message ?? `Test failed (${res.status})`);
+ setProbe(json);
+ router.refresh();
+ } finally {
+ setTesting(false);
+ }
+ }
+
+ async function remove() {
+ const res = await fetch(`/api/endpoints/${endpoint.id}`, { method: "DELETE" });
+ if (!res.ok) {
+ const json = await res.json().catch(() => ({}));
+ return toast.error(json.error?.message ?? `Could not delete (${res.status})`);
+ }
+ router.push("/endpoints");
+ router.refresh();
+ }
+
+ return (
+
+
+
+
+
{endpoint.name}
+
+ {endpoint.baseUrl}
+ {endpoint.hasApiKey ? " · API key set" : ""}
+
+
+
+
+
+ {testing ? : }
+ Test connection
+
+
+
+ Edit
+
+
+ }>
+
+ Delete
+
+
+
+ Delete {endpoint.name}?
+
+ The endpoint and its stored API key are removed.{runCount > 0 ? ` Its ${runCount} run${runCount === 1 ? "" : "s"} stay, with what they recorded.` : ""}
+
+
+
+ Cancel
+
+ Delete
+
+
+
+
+
+
+ {probe && }
+
+
+ );
+}
diff --git a/src/app/(app)/endpoints/[id]/page.tsx b/src/app/(app)/endpoints/[id]/page.tsx
new file mode 100644
index 0000000..d0a3298
--- /dev/null
+++ b/src/app/(app)/endpoints/[id]/page.tsx
@@ -0,0 +1,57 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { RunMetaCard } from "@/components/run-meta";
+import { endpointRunMeta, endpointSystem } from "@/lib/benchmark-meta";
+import { kanameVersion } from "@/lib/benchmark-snapshot";
+import { listBenchmarks } from "@/lib/benchmarks";
+import { getEndpoint, listEndpoints } from "@/lib/endpoints";
+import { BenchmarkList } from "../../benchmarks/benchmark-list";
+import { BenchmarkStart } from "./benchmark-start";
+import { EndpointHeader } from "./endpoint-header";
+
+export const dynamic = "force-dynamic";
+
+export async function generateMetadata({ params }: PageProps<"/endpoints/[id]">): Promise {
+ const e = await getEndpoint((await params).id);
+ return { title: e ? `${e.name} · Endpoint` : "Endpoint" };
+}
+
+export default async function EndpointPage({ params }: PageProps<"/endpoints/[id]">) {
+ const { id } = await params;
+ const endpoint = await getEndpoint(id);
+ if (!endpoint) notFound();
+ const [runs, all] = await Promise.all([listBenchmarks({ endpointId: id }), listEndpoints()]);
+ const model = endpoint.model ?? (endpoint.probe?.models.length === 1 ? endpoint.probe.models[0] : null);
+ // What a run would record now (the worker asks the server again when it starts).
+ const preview = endpointRunMeta({
+ type: "endpoint",
+ endpointName: endpoint.name,
+ model: model ?? "(model)",
+ engine: endpoint.engine ?? endpoint.probe?.engine ?? null,
+ engineVersion: endpoint.probe?.engineVersion ?? null,
+ contextSize: endpoint.probe?.contextSize ?? null,
+ slots: endpoint.probe?.slots ?? null,
+ hardware: endpoint.hardware,
+ });
+
+ return (
+
+
+
+
+ e.id !== id).map((e) => ({ id: e.id, name: e.name, models: e.probe?.models ?? [], model: e.model }))}
+ />
+
+
+
+
+
+ );
+}
diff --git a/src/app/(app)/endpoints/endpoint-form.tsx b/src/app/(app)/endpoints/endpoint-form.tsx
new file mode 100644
index 0000000..d2e83bc
--- /dev/null
+++ b/src/app/(app)/endpoints/endpoint-form.tsx
@@ -0,0 +1,297 @@
+"use client";
+
+import { CheckCircle2Icon, Loader2Icon, PlugZapIcon, SaveIcon, XCircleIcon } from "lucide-react";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Input } from "@/components/ui/input";
+import { NativeSelect } from "@/components/ui/native-select";
+import { ENGINE_LABEL } from "@/lib/benchmark-meta";
+import { ENDPOINT_ENGINES, type EndpointHardware, type EndpointProbe } from "@/lib/db/schema";
+import type { EndpointView } from "@/lib/endpoints";
+
+type Field = { key: keyof EndpointHardware; label: string; placeholder?: string; kind?: "number" | "int"; hint?: string };
+
+const GROUPS: { title: string; hint: string; fields: Field[] }[] = [
+ {
+ title: "GPU",
+ hint: "Leave empty for a CPU-only server.",
+ fields: [
+ { key: "gpuName", label: "GPU", placeholder: "NVIDIA GeForce RTX 4090" },
+ { key: "gpuCount", label: "Count", placeholder: "1", kind: "int" },
+ { key: "vramGb", label: "VRAM per GPU (GB)", placeholder: "24", kind: "number" },
+ { key: "pcie", label: "PCIe link", placeholder: "Gen4 x16" },
+ { key: "gpuDriver", label: "Driver", placeholder: "nvidia 580.82" },
+ ],
+ },
+ {
+ title: "Machine",
+ hint: "Only facts like these are published, never host names or addresses.",
+ fields: [
+ { key: "cpu", label: "CPU", placeholder: "AMD EPYC 7282" },
+ { key: "memoryGb", label: "RAM (GB)", placeholder: "128", kind: "number" },
+ { key: "os", label: "OS", placeholder: "Debian 13" },
+ { key: "virtualization", label: "Virtualization", placeholder: "Proxmox VM with GPU passthrough, or bare metal" },
+ ],
+ },
+ {
+ title: "Server",
+ hint: "What the server runs. Empty fields are taken from what it reports where it can.",
+ fields: [
+ { key: "engineName", label: "Engine name", placeholder: "ik_llama.cpp (default: detected)" },
+ { key: "engineVersion", label: "Engine version", placeholder: "default: detected" },
+ { key: "image", label: "Container image", placeholder: "ghcr.io/ggml-org/llama.cpp:server-cuda" },
+ { key: "quant", label: "Quant", placeholder: "Q4_K_M (default: from the model name)" },
+ { key: "kvCache", label: "KV cache type", placeholder: "q8_0" },
+ { key: "contextSize", label: "Context (tokens)", placeholder: "default: reported", kind: "int" },
+ { key: "concurrency", label: "Parallel slots", placeholder: "4", kind: "int" },
+ ],
+ },
+];
+
+const toText = (v: unknown) => (v == null ? "" : String(v));
+
+/** Create or edit an endpoint. The API key is never sent to the browser: on edit it can be kept, replaced or removed. */
+export function EndpointForm({ initial }: { initial?: EndpointView }) {
+ const router = useRouter();
+ const [name, setName] = useState(initial?.name ?? "");
+ const [baseUrl, setBaseUrl] = useState(initial?.baseUrl ?? "");
+ const [apiKey, setApiKey] = useState("");
+ const [removeKey, setRemoveKey] = useState(false);
+ const [model, setModel] = useState(initial?.model ?? "");
+ const [engine, setEngine] = useState(initial?.engine ?? "");
+ const [hw, setHw] = useState>(() =>
+ Object.fromEntries(Object.entries(initial?.hardware ?? {}).map(([k, v]) => [k, typeof v === "boolean" ? (v ? "on" : "off") : toText(v)])),
+ );
+ const [probe, setProbe] = useState(initial?.probe ?? null);
+ const [testing, setTesting] = useState(false);
+ const [saving, setSaving] = useState(false);
+
+ const fields = GROUPS.flatMap((g) => g.fields);
+ function body() {
+ const hardware: Record = {};
+ for (const f of fields) {
+ const v = (hw[f.key] ?? "").trim();
+ if (!v) continue;
+ hardware[f.key] = f.kind ? Number(v.replace(",", ".")) : v;
+ }
+ if (hw.p2p) hardware.p2p = hw.p2p;
+ if (hw.rebar) hardware.rebar = hw.rebar === "on";
+ if (hw.description?.trim()) hardware.description = hw.description.trim();
+ return {
+ name,
+ baseUrl,
+ // Left out: keep the stored key. "": remove it.
+ ...(apiKey.trim() ? { apiKey: apiKey.trim() } : removeKey || !initial ? { apiKey: "" } : {}),
+ model: model.trim() || null,
+ engine: engine || null,
+ hardware,
+ };
+ }
+
+ async function test() {
+ setTesting(true);
+ try {
+ const res = await fetch(initial ? `/api/endpoints/${initial.id}/test` : "/api/endpoints/test", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body()),
+ });
+ const json = await res.json().catch(() => ({}));
+ if (!res.ok) return toast.error(json.error?.message ?? `Test failed (${res.status})`);
+ setProbe(json);
+ if (json.ok && !model && json.models.length === 1) setModel(json.models[0]);
+ } finally {
+ setTesting(false);
+ }
+ }
+
+ async function save(e: React.FormEvent) {
+ e.preventDefault();
+ setSaving(true);
+ try {
+ const res = await fetch(initial ? `/api/endpoints/${initial.id}` : "/api/endpoints", {
+ method: initial ? "PATCH" : "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body()),
+ });
+ const json = await res.json().catch(() => ({}));
+ if (!res.ok) return toast.error(json.error?.message ?? `Could not save (${res.status})`);
+ router.push(`/endpoints/${json.id}`);
+ router.refresh();
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ const set = (key: string) => (e: React.ChangeEvent) => setHw((cur) => ({ ...cur, [key]: e.target.value }));
+ const models = probe?.ok ? probe.models : [];
+
+ return (
+
+ );
+}
+
+/** What "Test connection" found. */
+export function ProbeResult({ probe }: { probe: EndpointProbe }) {
+ if (!probe.ok) {
+ return (
+
+
+ {probe.error}
+
+ );
+ }
+ return (
+
+
+
+
+ Reachable{probe.latencyMs != null ? ` (${probe.latencyMs} ms)` : ""}
+ {probe.engine ? ` · ${ENGINE_LABEL[probe.engine]}${probe.engineVersion ? ` ${probe.engineVersion}` : ""}` : " · engine not detected"}
+ {probe.contextSize ? ` · ${probe.contextSize.toLocaleString("en-US")} tokens context` : ""}
+ {probe.slots ? ` · ${probe.slots} slots` : ""}
+
+
+ {probe.models.length ? `Serves: ${probe.models.slice(0, 6).join(", ")}${probe.models.length > 6 ? ", …" : ""}` : "Lists no models."}
+
+
+
+ );
+}
diff --git a/src/app/(app)/endpoints/endpoint-status.tsx b/src/app/(app)/endpoints/endpoint-status.tsx
new file mode 100644
index 0000000..c485f81
--- /dev/null
+++ b/src/app/(app)/endpoints/endpoint-status.tsx
@@ -0,0 +1,21 @@
+import { LocalTime } from "@/components/local-time";
+import type { EndpointProbe } from "@/lib/db/schema";
+import { cn } from "@/lib/utils";
+
+/** Reachable / unreachable / untested, from the last connection test. */
+export function EndpointStatus({ probe }: { probe: EndpointProbe | null }) {
+ const state = !probe ? "untested" : probe.ok ? "reachable" : "unreachable";
+ return (
+
+
+
+ {state}
+
+ {probe && (
+
+
+
+ )}
+
+ );
+}
diff --git a/src/app/(app)/endpoints/new/page.tsx b/src/app/(app)/endpoints/new/page.tsx
new file mode 100644
index 0000000..083c5af
--- /dev/null
+++ b/src/app/(app)/endpoints/new/page.tsx
@@ -0,0 +1,13 @@
+import type { Metadata } from "next";
+import { EndpointForm } from "../endpoint-form";
+
+export const metadata: Metadata = { title: "New endpoint" };
+
+export default function NewEndpointPage() {
+ return (
+
+
New endpoint
+
+
+ );
+}
diff --git a/src/app/(app)/endpoints/page.tsx b/src/app/(app)/endpoints/page.tsx
new file mode 100644
index 0000000..b5ac34c
--- /dev/null
+++ b/src/app/(app)/endpoints/page.tsx
@@ -0,0 +1,94 @@
+import { PlusIcon, ServerIcon } from "lucide-react";
+import type { Metadata } from "next";
+import Link from "next/link";
+import { buttonVariants } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { ENGINE_LABEL } from "@/lib/benchmark-meta";
+import { headline } from "@/lib/benchmark-view";
+import { listBenchmarks } from "@/lib/benchmarks";
+import { listEndpoints } from "@/lib/endpoints";
+import { EndpointStatus } from "./endpoint-status";
+
+export const dynamic = "force-dynamic";
+export const metadata: Metadata = { title: "Endpoints" };
+
+export default async function EndpointsPage() {
+ const [endpoints, runs] = await Promise.all([listEndpoints(), listBenchmarks()]);
+ // Newest completed speed run and quality score per endpoint.
+ const latest = new Map();
+ for (const r of runs) {
+ if (!r.endpointId || r.state !== "completed") continue;
+ const cur = latest.get(r.endpointId) ?? { decode: null, quality: null };
+ if (r.kind === "run" && cur.decode == null) cur.decode = headline(r.summary).decode;
+ if (r.kind === "eval" && cur.quality == null) cur.quality = r.quality?.score ?? null;
+ latest.set(r.endpointId, cur);
+ }
+
+ return (
+
+
+
+
Endpoints
+
OpenAI-compatible servers to benchmark. They run elsewhere; Kaname only sends them requests.
+
+
+
+ Add endpoint
+
+
+
+ {endpoints.length === 0 ? (
+
+
+
+ No endpoints yet. Add the URL of a llama.cpp, vLLM, SGLang or Ollama server, describe its hardware, and benchmark it.
+
+
+ ) : (
+
+
+
+
+ Endpoint
+ Model
+ Hardware
+ Decode t/s
+ Quality
+ Status
+
+
+
+ {endpoints.map((e) => {
+ const l = latest.get(e.id);
+ const engine = e.hardware.engineName || (e.engine ?? e.probe?.engine ? ENGINE_LABEL[(e.engine ?? e.probe?.engine)!] : null);
+ return (
+
+
+
+ {e.name}
+
+
+ {e.baseUrl}
+ {engine && ` · ${engine}${e.probe?.engineVersion ? ` ${e.probe.engineVersion}` : ""}`}
+
+
+ {e.model ?? (e.probe?.models.length === 1 ? e.probe.models[0] : "–")}
+
+ {e.hardware.gpuName ? `${e.hardware.gpuCount ?? 1}× ${e.hardware.gpuName}` : (e.hardware.cpu ?? "–")}
+
+ {l?.decode != null ? l.decode.toFixed(1) : "–"}
+ {l?.quality != null ? `${l.quality}%` : "–"}
+
+
+
+
+ );
+ })}
+
+
+
+ )}
+
+ );
+}
diff --git a/src/app/(app)/jobs/[id]/job-live.tsx b/src/app/(app)/jobs/[id]/job-live.tsx
index 26074d1..d4db1b4 100644
--- a/src/app/(app)/jobs/[id]/job-live.tsx
+++ b/src/app/(app)/jobs/[id]/job-live.tsx
@@ -1,13 +1,10 @@
"use client";
import Link from "next/link";
-import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
-import { ApprovalBar } from "@/components/approval-bar";
import { cancelJob } from "@/components/job-actions";
import { JobFilesTable } from "@/components/job-files-table";
import { JobProgress } from "@/components/job-progress";
-import { RequestedByBadge } from "@/components/requested-by-badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useLive } from "@/hooks/use-live";
@@ -24,7 +21,6 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
const files = snapshot?.files ?? [];
const open = OPEN.includes(job.state);
const [busy, setBusy] = useState(false);
- const router = useRouter();
const logRef = useRef(null);
const [follow, setFollow] = useState(true);
@@ -50,7 +46,6 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
{job.repoId}
-
{open && (
- {job.state === "pending_approval" && router.push("/")} />}
-
Created
- {job.requestedBy && (
- <>
- Requested by
- {job.requestedBy} (API token)
- >
- )}
Started
diff --git a/src/app/(app)/library-view.tsx b/src/app/(app)/library-view.tsx
index c2b8f39..87d0675 100644
--- a/src/app/(app)/library-view.tsx
+++ b/src/app/(app)/library-view.tsx
@@ -1,6 +1,6 @@
"use client";
-import { RocketIcon, SearchIcon, XIcon } from "lucide-react";
+import { SearchIcon, XIcon } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useMemo, useState } from "react";
@@ -8,10 +8,9 @@ import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { LocalTime } from "@/components/local-time";
import { HUB_STATE_LABEL, HubStateBadge } from "@/components/hub-state-badge";
import { MODEL_STATUS, ModelStatusBadge } from "@/components/model-status-badge";
-import { RequestedByBadge } from "@/components/requested-by-badge";
import { TagBadge, TagDot } from "@/components/tag-badge";
import { Badge } from "@/components/ui/badge";
-import { Button, buttonVariants } from "@/components/ui/button";
+import { Button } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
@@ -20,7 +19,6 @@ import type { ModelStatus } from "@/lib/db/schema";
import { formatBytes, shortSha } from "@/lib/format";
import type { JobSnapshot } from "@/lib/jobs";
import type { LibraryRow } from "@/lib/library";
-import { cn } from "@/lib/utils";
import {
EMPTY_FILTERS,
type Facet,
@@ -29,7 +27,6 @@ import {
type Filters,
matchesFilters,
matchesQuery,
- PENDING_APPROVAL,
type SearchableModel,
} from "@/lib/search";
import { FacetFilter } from "./facet-filter";
@@ -42,10 +39,9 @@ const FACET_LABEL: Record = {
quant: "Quant",
tag: "Tag",
status: "Status",
- requester: "Requested by",
};
-const statusLabel = (v: string) => (v === PENDING_APPROVAL ? "awaiting approval" : (MODEL_STATUS[v as ModelStatus]?.label ?? v));
+const statusLabel = (v: string) => MODEL_STATUS[v as ModelStatus]?.label ?? v;
function toSearchable(r: LibraryRow): SearchableModel {
return {
@@ -66,8 +62,6 @@ function toSearchable(r: LibraryRow): SearchableModel {
: r.updateAvailable
? "update available"
: null,
- requestedBy: r.requestedBy,
- pendingApproval: r.pendingApproval,
};
}
@@ -186,9 +180,6 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
Pinned
Downloaded
Status
-
- Deploy
-
@@ -202,26 +193,8 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
{r.repoId}
-
{base && base !== r.repoId &&
base {base} }
{r.architecture &&
{r.architecture} }
- {r.deployments.map((d) => (
-
-
-
{d.name}
-
-
- ))}
{r.tags.map((t) => (
- {job.state !== "queued" && job.state !== "pending_approval" && }
+ {job.state !== "queued" && }
) : (
@@ -263,19 +236,6 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
)}
-
- {r.deployable && (
-
-
- Deploy
-
- )}
-
);
})}
diff --git a/src/app/(app)/settings/api-keys/api-key-settings.tsx b/src/app/(app)/settings/api-keys/api-key-settings.tsx
deleted file mode 100644
index fa43919..0000000
--- a/src/app/(app)/settings/api-keys/api-key-settings.tsx
+++ /dev/null
@@ -1,172 +0,0 @@
-"use client";
-
-import { EyeIcon, EyeOffIcon, KeyRoundIcon, PlusIcon, Trash2Icon } from "lucide-react";
-import { useRouter } from "next/navigation";
-import { useState } from "react";
-import { toast } from "sonner";
-import { CopyButton } from "@/components/copy-button";
-import { LocalTime } from "@/components/local-time";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
-} from "@/components/ui/alert-dialog";
-import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
-import { Input } from "@/components/ui/input";
-import type { ApiKeyRow } from "@/lib/api-keys";
-
-/** Keys that deployments with "Require an API key" accept. */
-export function ApiKeySettings({ keys }: { keys: ApiKeyRow[] }) {
- const [created, setCreated] = useState<{ name: string; key: string } | null>(null);
- return (
-
-
- Runtime API keys
-
- Deployments with “Require an API key” accept any of these keys as Authorization: Bearer <key>.
- Changes apply when a deployment (re)starts.
-
-
-
-
- {created && (
-
-
API key “{created.name}” added. You can show it again from the list.
-
- {created.key}
-
-
-
- )}
- {keys.length === 0 ? (
- No API keys yet.
- ) : (
-
- {keys.map((k) => (
-
- ))}
-
- )}
-
-
- );
-}
-
-function NewKeyRow({ onCreated }: { onCreated: (k: { name: string; key: string }) => void }) {
- const router = useRouter();
- const [name, setName] = useState("");
- const [key, setKey] = useState("");
- const [busy, setBusy] = useState(false);
-
- async function create(e: React.FormEvent) {
- e.preventDefault();
- if (!name.trim()) return;
- setBusy(true);
- try {
- const res = await fetch("/api/api-keys", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name, key: key.trim() || undefined }),
- });
- const json = await res.json().catch(() => ({}));
- if (!res.ok) {
- toast.error(json.error?.message ?? `Could not add the key (${res.status})`);
- return;
- }
- onCreated({ name: json.name, key: json.key });
- setName("");
- setKey("");
- router.refresh();
- } finally {
- setBusy(false);
- }
- }
-
- return (
-
- setName(e.target.value)} placeholder="Name, e.g. Open WebUI" aria-label="Key name" />
- setKey(e.target.value.replace(/\s/g, ""))}
- placeholder="Key (empty: generate one)"
- aria-label="Key value"
- spellCheck={false}
- autoComplete="off"
- className="font-mono text-xs md:text-xs"
- />
-
-
- Add
-
-
- );
-}
-
-function KeyRow({ apiKey }: { apiKey: ApiKeyRow }) {
- const router = useRouter();
- const [shown, setShown] = useState(null);
-
- async function toggle() {
- if (shown) return setShown(null);
- const res = await fetch(`/api/api-keys/${apiKey.id}`, { cache: "no-store" });
- const json = await res.json().catch(() => ({}));
- if (!res.ok) toast.error(json.error?.message ?? `Could not load the key (${res.status})`);
- else setShown(json.key);
- }
-
- async function remove() {
- const res = await fetch(`/api/api-keys/${apiKey.id}`, { method: "DELETE" });
- if (!res.ok) toast.error(`Could not delete (${res.status})`);
- else toast.success(`API key "${apiKey.name}" deleted`);
- router.refresh();
- }
-
- return (
-
-
-
{apiKey.name}
- {shown ? (
-
-
- {shown}
-
-
-
- ) : (
-
{apiKey.hint}
- )}
-
- {shown ? : }
-
-
-
-
-
- }>
-
-
-
-
- Delete API key “{apiKey.name}”?
- Clients using it are rejected once their deployments restart.
-
-
- Cancel
-
- Delete
-
-
-
-
-
- );
-}
diff --git a/src/app/(app)/settings/api-keys/page.tsx b/src/app/(app)/settings/api-keys/page.tsx
deleted file mode 100644
index 9d4a14d..0000000
--- a/src/app/(app)/settings/api-keys/page.tsx
+++ /dev/null
@@ -1,10 +0,0 @@
-import type { Metadata } from "next";
-import { listApiKeys } from "@/lib/api-keys";
-import { ApiKeySettings } from "./api-key-settings";
-
-export const dynamic = "force-dynamic";
-export const metadata: Metadata = { title: "Runtime API keys · Settings" };
-
-export default async function ApiKeySettingsPage() {
- return ;
-}
diff --git a/src/app/(app)/settings/api-tokens/guardrail-settings.tsx b/src/app/(app)/settings/api-tokens/guardrail-settings.tsx
deleted file mode 100644
index be71207..0000000
--- a/src/app/(app)/settings/api-tokens/guardrail-settings.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-"use client";
-
-import { ShieldCheckIcon } from "lucide-react";
-import { useRouter } from "next/navigation";
-import { useState } from "react";
-import { toast } from "sonner";
-import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { NativeSelect } from "@/components/ui/native-select";
-import { type ApprovalMode, type Guardrails, parseAuthorList } from "@/lib/agent-guardrails";
-
-const GB = 1_000_000_000;
-const toGb = (b: number) => String(Math.round((b / GB) * 1000) / 1000);
-
-/** Limits for downloads requested through the API. Saved together with one button. */
-export function GuardrailSettings({ initial }: { initial: Guardrails }) {
- const router = useRouter();
- const [mode, setMode] = useState(initial.approvalMode);
- const [maxGb, setMaxGb] = useState(toGb(initial.maxRequestBytes));
- const [minFreeGb, setMinFreeGb] = useState(toGb(initial.minFreeBytes));
- const [maxJobs, setMaxJobs] = useState(String(initial.maxOpenJobs));
- const [authors, setAuthors] = useState(initial.allowedAuthors.join(", "));
- const [busy, setBusy] = useState(false);
-
- let authorError: string | null = null;
- let authorList: string[] = [];
- try {
- authorList = parseAuthorList(authors);
- } catch (err) {
- authorError = err instanceof Error ? err.message : String(err);
- }
- const num = (s: string) => Number(s.replace(",", "."));
-
- async function save(e: React.FormEvent) {
- e.preventDefault();
- if (authorError) return;
- setBusy(true);
- try {
- const res = await fetch("/api/settings/agent", {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- approvalMode: mode,
- maxRequestBytes: Math.round(num(maxGb) * GB),
- minFreeBytes: Math.round(num(minFreeGb) * GB),
- maxOpenJobs: Math.round(num(maxJobs)),
- allowedAuthors: authorList,
- }),
- });
- const json = await res.json().catch(() => ({}));
- if (!res.ok) return toast.error(json.error?.message ?? `Could not save (${res.status})`);
- toast.success("Guardrails saved");
- router.refresh();
- } finally {
- setBusy(false);
- }
- }
-
- return (
-
-
-
-
- Guardrails for API downloads
-
- Apply to every download requested with a token, across all tokens. Downloads you start in the UI are not affected.
-
-
-
-
- Approval
- setMode(e.target.value as ApprovalMode)} className="max-w-md">
- Ask me: requests wait as “pending approval”
- Automatic: downloads start right away
-
-
-
-
-
Allowed authors
-
setAuthors(e.target.value)} placeholder="Empty: any author. e.g. unsloth, ggml-org, Qwen" aria-invalid={!!authorError} />
-
- {authorError ?? "Hugging Face users or organizations (the part before the slash), comma-separated."}
-
-
-
- “Agent jobs at once” counts requests that are pending approval, queued or downloading. The free-space check also subtracts what other open
- downloads still need.
-
-
- Save guardrails
-
-
-
-
- );
-}
diff --git a/src/app/(app)/settings/api-tokens/page.tsx b/src/app/(app)/settings/api-tokens/page.tsx
deleted file mode 100644
index 87b31e8..0000000
--- a/src/app/(app)/settings/api-tokens/page.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import type { Metadata } from "next";
-import { listActivity } from "@/lib/agent-activity";
-import { listTokens } from "@/lib/api-tokens";
-import { listRuntimes } from "@/lib/runtimes";
-import { getGuardrails, getTuning } from "@/lib/settings";
-import { GuardrailSettings } from "./guardrail-settings";
-import { TokenSettings } from "./token-settings";
-import { TuningSettings } from "./tuning-settings";
-
-export const dynamic = "force-dynamic";
-export const metadata: Metadata = { title: "API tokens · Settings" };
-
-export default async function ApiTokenSettingsPage() {
- const [tokens, guardrails, tuning, runtimes] = await Promise.all([listTokens(), getGuardrails(), getTuning(), listRuntimes()]);
- const activity = Object.fromEntries(
- await Promise.all(
- tokens.map(async (t) => [t.id, (await listActivity(t.id, 50)).map((a) => ({ ...a, createdAt: a.createdAt.toISOString() }))] as const),
- ),
- );
- return (
-
-
-
- ({ id: r.id, name: r.name, pulled: r.imageState === "present" }))} />
-
- );
-}
diff --git a/src/app/(app)/settings/api-tokens/token-settings.tsx b/src/app/(app)/settings/api-tokens/token-settings.tsx
deleted file mode 100644
index 28aa5f6..0000000
--- a/src/app/(app)/settings/api-tokens/token-settings.tsx
+++ /dev/null
@@ -1,390 +0,0 @@
-"use client";
-
-import { BotIcon, PlusIcon, Trash2Icon } from "lucide-react";
-import Link from "next/link";
-import { useRouter } from "next/navigation";
-import { useState } from "react";
-import { toast } from "sonner";
-import { CopyButton } from "@/components/copy-button";
-import { LocalTime } from "@/components/local-time";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
-} from "@/components/ui/alert-dialog";
-import { Badge } from "@/components/ui/badge";
-import { Button } from "@/components/ui/button";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
-import { Checkbox } from "@/components/ui/checkbox";
-import { Input } from "@/components/ui/input";
-import { SCOPE_LABEL } from "@/lib/token-scopes";
-import type { ApiTokenRow } from "@/lib/api-tokens";
-import { TOKEN_SCOPES, type TokenScope } from "@/lib/db/schema";
-
-/** Bearer tokens for /api/v1 (e.g. an AI agent). The token is shown once, then only its prefix. */
-export function TokenSettings({
- tokens,
- activity,
-}: {
- tokens: ApiTokenRow[];
- activity: Record;
-}) {
- const [created, setCreated] = useState<{
- name: string;
- token: string;
- } | null>(null);
- return (
-
-
- API tokens
-
- For programs and agents calling Kaname's API at{" "}
- /api/v1 with{" "}
-
- Authorization: Bearer <token>
-
- . No token can delete models or files, change settings, or manage
- runtimes and tokens.
-
-
-
-
- {created && (
-
-
- Token “{created.name}” created. Copy it now: it is not
- shown again.
-
-
-
- {created.token}
-
-
-
-
- )}
- {tokens.length === 0 ? (
- No tokens yet.
- ) : (
-
- {tokens.map((t) => (
-
- ))}
-
- )}
-
-
- );
-}
-
-function NewTokenForm({
- onCreated,
-}: {
- onCreated: (t: { name: string; token: string }) => void;
-}) {
- const router = useRouter();
- const [name, setName] = useState("");
- const [scopes, setScopes] = useState(["models:read"]);
- const [busy, setBusy] = useState(false);
-
- async function create(e: React.FormEvent) {
- e.preventDefault();
- setBusy(true);
- try {
- const res = await fetch("/api/api-tokens", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name, scopes }),
- });
- const json = await res.json().catch(() => ({}));
- if (!res.ok)
- return toast.error(
- json.error?.message ?? `Could not create the token (${res.status})`,
- );
- onCreated({ name: name.trim().toLowerCase(), token: json.token });
- setName("");
- router.refresh();
- } finally {
- setBusy(false);
- }
- }
-
- return (
-
-
-
- setName(e.target.value.toLowerCase().replace(/[^a-z0-9._-]/g, ""))
- }
- placeholder="Name, e.g. hermes"
- aria-label="Token name"
- className="max-w-56"
- />
-
-
- Create token
-
-
-
- {TOKEN_SCOPES.map((s) => (
-
-
- setScopes((cur) =>
- v ? [...cur, s] : cur.filter((x) => x !== s),
- )
- }
- className="mt-0.5"
- />
-
- {s}
-
- {SCOPE_LABEL[s]}
-
-
-
- ))}
-
-
- The name is shown as “requested by” on everything the token
- asks for.
-
-
- );
-}
-
-function TokenRow({
- token,
- activity,
-}: {
- token: ApiTokenRow;
- activity: ActivityItem[];
-}) {
- const router = useRouter();
- const revoked = !!token.revokedAt;
- const [editing, setEditing] = useState(false);
- const [scopes, setScopes] = useState(token.scopes);
- const [showActivity, setShowActivity] = useState(false);
-
- async function saveScopes() {
- const res = await fetch(`/api/api-tokens/${token.id}`, {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ scopes }),
- });
- const json = await res.json().catch(() => ({}));
- if (!res.ok)
- return void toast.error(json.error?.message ?? `Failed (${res.status})`);
- toast.success(`Scopes of "${token.name}" changed`);
- setEditing(false);
- router.refresh();
- }
-
- async function act(method: "POST" | "DELETE") {
- const res = await fetch(`/api/api-tokens/${token.id}`, { method });
- const json = await res.json().catch(() => ({}));
- if (!res.ok) toast.error(json.error?.message ?? `Failed (${res.status})`);
- else
- toast.success(
- method === "POST"
- ? `Token "${token.name}" revoked`
- : `Token "${token.name}" deleted`,
- );
- router.refresh();
- }
-
- return (
-
-
-
-
{token.name}
-
- {token.prefix}…
-
-
- {token.scopes.map((s) => (
-
- {s}
-
- ))}
-
- {revoked &&
revoked }
-
- {token.lastUsedAt ? (
- <>
- used
- >
- ) : (
- "never used"
- )}
-
- {activity.length > 0 && (
-
setShowActivity((v) => !v)}
- >
- Activity ({activity.length})
-
- )}
- {!revoked && (
-
setEditing((v) => !v)}
- >
- Scopes
-
- )}
-
- }>
- {revoked ? : "Revoke"}
-
-
-
-
- {revoked ? "Delete" : "Revoke"} token “{token.name}
- ”?
-
-
- {revoked
- ? "The entry goes away and the name can be used again. Models it requested keep their “requested by” label."
- : "It stops working immediately. Downloads it already requested are not affected."}
-
-
-
- Cancel
- act(revoked ? "DELETE" : "POST")}
- >
- {revoked ? "Delete" : "Revoke"}
-
-
-
-
-
- {editing && (
-
- {TOKEN_SCOPES.map((s) => (
-
-
- setScopes((cur) =>
- v ? [...cur, s] : cur.filter((x) => x !== s),
- )
- }
- className="mt-0.5"
- />
-
- {s}
-
- {SCOPE_LABEL[s]}
-
-
-
- ))}
-
- Save scopes
-
-
- )}
- {showActivity &&
}
-
- );
-}
-
-export type ActivityItem = {
- id: string;
- action: string;
- targetType: string | null;
- targetId: string | null;
- outcome: string;
- code: string | null;
- message: string | null;
- createdAt: string;
-};
-
-const TARGET_HREF: Record string> = {
- deployment: (id) => `/deployments/${id}`,
- benchmark: (id) => `/benchmarks/${id}`,
- sweep: (id) => `/benchmarks/sweeps/${id}`,
- model: (id) => `/models/${id}`,
-};
-
-/** What the token did, newest first: outcome, and the reason when a guardrail refused it. */
-function ActivityList({ items }: { items: ActivityItem[] }) {
- return (
-
- {items.map((a) => (
-
-
-
-
- {a.action}
-
- {a.outcome === "refused"
- ? `refused: ${a.code}`
- : a.outcome === "pending_approval"
- ? "awaiting approval"
- : "ok"}
-
- {a.targetType && a.targetId && TARGET_HREF[a.targetType] && (
-
- {a.targetType}
-
- )}
- {a.message && (
- {a.message}
- )}
-
- ))}
-
- );
-}
diff --git a/src/app/(app)/settings/api-tokens/tuning-settings.tsx b/src/app/(app)/settings/api-tokens/tuning-settings.tsx
deleted file mode 100644
index b7de594..0000000
--- a/src/app/(app)/settings/api-tokens/tuning-settings.tsx
+++ /dev/null
@@ -1,166 +0,0 @@
-"use client";
-
-import { ShieldCheckIcon } from "lucide-react";
-import { useRouter } from "next/navigation";
-import { useState } from "react";
-import { toast } from "sonner";
-import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
-import { Checkbox } from "@/components/ui/checkbox";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { NativeSelect } from "@/components/ui/native-select";
-import type { ApprovalMode } from "@/lib/agent-guardrails";
-import { DEFAULT_ALLOWED_ARGS, parseFlagList, type TuningGuardrails } from "@/lib/agent-tuning";
-
-const intText = (s: string) => s.replace(/\D/g, "");
-const decText = (s: string) => s.replace(/[^\d.,]/g, "");
-const num = (s: string) => Number(s.replace(",", "."));
-
-/** Limits for deployments, benchmark runs and sweeps requested through the API. */
-export function TuningSettings({ initial, runtimes }: { initial: TuningGuardrails; runtimes: { id: string; name: string; pulled: boolean }[] }) {
- const router = useRouter();
- const [mode, setMode] = useState(initial.approvalMode);
- const [maxDeps, setMaxDeps] = useState(String(initial.maxAgentDeployments));
- const [runMin, setRunMin] = useState(String(initial.maxRunMinutes));
- const [sweepMin, setSweepMin] = useState(String(initial.maxSweepMinutes));
- const [variants, setVariants] = useState(String(initial.maxSweepVariants));
- const [allowed, setAllowed] = useState(initial.allowedRuntimeIds);
- const [llamaArgs, setLlamaArgs] = useState(initial.allowedArgs["llama.cpp"].join(" "));
- const [vllmArgs, setVllmArgs] = useState(initial.allowedArgs.vllm.join(" "));
- const [portFrom, setPortFrom] = useState(initial.hostPortRange ? String(initial.hostPortRange.from) : "");
- const [portTo, setPortTo] = useState(initial.hostPortRange ? String(initial.hostPortRange.to) : "");
- const [memGiB, setMemGiB] = useState(initial.maxMemoryMb ? String(Math.round((initial.maxMemoryMb / 1024) * 10) / 10) : "");
- const [cpus, setCpus] = useState(initial.maxCpus != null ? String(initial.maxCpus) : "");
- const [busy, setBusy] = useState(false);
-
- let argError: string | null = null;
- let llama: string[] = [];
- let vllm: string[] = [];
- try {
- llama = parseFlagList(llamaArgs);
- vllm = parseFlagList(vllmArgs);
- } catch (err) {
- argError = err instanceof Error ? err.message : String(err);
- }
-
- async function save(e: React.FormEvent) {
- e.preventDefault();
- if (argError) return;
- setBusy(true);
- try {
- const res = await fetch("/api/settings/tuning", {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- approvalMode: mode,
- maxAgentDeployments: num(maxDeps),
- maxRunMinutes: num(runMin),
- maxSweepMinutes: num(sweepMin),
- maxSweepVariants: num(variants),
- allowedRuntimeIds: allowed,
- allowedArgs: { "llama.cpp": llama, vllm },
- hostPortRange: portFrom && portTo ? { from: num(portFrom), to: num(portTo) } : null,
- maxMemoryMb: memGiB ? Math.round(num(memGiB) * 1024) : null,
- maxCpus: cpus ? num(cpus) : null,
- }),
- });
- const json = await res.json().catch(() => ({}));
- if (!res.ok) return void toast.error(json.error?.message ?? `Could not save (${res.status})`);
- toast.success("Guardrails saved");
- router.refresh();
- } finally {
- setBusy(false);
- }
- }
-
- const field = (id: string, label: string, value: string, set: (v: string) => void, opts: { placeholder?: string; decimal?: boolean } = {}) => (
-
- {label}
- set((opts.decimal ? decText : intText)(e.target.value))} inputMode={opts.decimal ? "decimal" : "numeric"} placeholder={opts.placeholder} />
-
- );
-
- return (
-
-
-
-
- Guardrails for API deployments and benchmarks
-
-
- For tokens with the deployments and benchmarks scopes. Agents only change and benchmark deployments their own token created, never protected ones (the
- shield on a deployment's page), and can't start anything that would crowd a running protected deployment out of VRAM.
-
-
-
-
-
-
Approval
-
setMode(e.target.value as ApprovalMode)} className="max-w-md">
- Ask me: starts, runs and sweeps wait for approval
- Automatic: they go ahead right away
-
-
Creating or editing a stopped deployment, stopping and deleting their own ones never needs approval.
-
-
- {field("t-deps", "Agent deployments at once", maxDeps, setMaxDeps)}
- {field("t-run", "Max minutes per run", runMin, setRunMin)}
- {field("t-sweep", "Max minutes per sweep", sweepMin, setSweepMin)}
- {field("t-var", "Max variants per sweep", variants, setVariants)}
-
-
- One agent run or sweep at a time, and no agent deployment starts while one is measured. Raise “deployments at once” to 2 for A/B runs.
-
-
- {field("t-mem", "Memory cap per deployment (GiB)", memGiB, setMemGiB, { placeholder: "host RAM", decimal: true })}
- {field("t-cpu", "CPU cap (cores)", cpus, setCpus, { placeholder: "all cores", decimal: true })}
- {field("t-pf", "Host ports from", portFrom, setPortFrom, { placeholder: "none" })}
- {field("t-pt", "Host ports to", portTo, setPortTo, { placeholder: "none" })}
-
-
-
Runtimes agents may use
-
- {runtimes.map((r) => (
-
- setAllowed((cur) => (v ? [...cur, r.id] : cur.filter((x) => x !== r.id)))} />
- {r.name}
- {!r.pulled && (not pulled) }
-
- ))}
-
-
None ticked: every runtime with a pulled image.
-
- {(
- [
- ["llama.cpp", llamaArgs, setLlamaArgs],
- ["vllm", vllmArgs, setVllmArgs],
- ] as const
- ).map(([engine, value, set]) => (
-
- Extra argument flags agents may use: {engine}
- set(e.target.value)}
- rows={3}
- spellCheck={false}
- className="w-full rounded-md border bg-transparent px-2.5 py-1.5 font-mono text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
- />
- set(DEFAULT_ALLOWED_ARGS[engine].join(" "))}>
- Reset to the default list
-
-
- ))}
-
- {argError ??
- "Anything else is refused with the offending argument named, and values can't be paths or URLs. Docker options (devices, volumes, privileges, network) never come from arguments: they belong to the runtime, which tokens can't change."}
-
-
- Save guardrails
-
-
-
-
- );
-}
diff --git a/src/app/(app)/settings/hardware/hardware-settings.tsx b/src/app/(app)/settings/hardware/hardware-settings.tsx
deleted file mode 100644
index 77e62f6..0000000
--- a/src/app/(app)/settings/hardware/hardware-settings.tsx
+++ /dev/null
@@ -1,267 +0,0 @@
-"use client";
-
-import { useRouter } from "next/navigation";
-import { useState } from "react";
-import { toast } from "sonner";
-import { LocalTime } from "@/components/local-time";
-import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { NativeSelect } from "@/components/ui/native-select";
-import type { HardwareOverrides, HostHardware } from "@/lib/db/schema";
-import { formatBytes } from "@/lib/format";
-import { formatLink, onOff } from "@/lib/hardware";
-
-type GpuForm = { name: string; vramMb: string; linkCurrent: string; linkMax: string; rebar: "" | "on" | "off" };
-
-const toForm = (o: NonNullable[string] | undefined): GpuForm => ({
- name: o?.name ?? "",
- vramMb: o?.vramMb != null ? String(o.vramMb) : "",
- linkCurrent: o?.linkCurrent ?? "",
- linkMax: o?.linkMax ?? "",
- rebar: o?.rebar == null ? "" : o.rebar ? "on" : "off",
-});
-
-const STORAGE_KIND: Record = { nvme: "NVMe", ssd: "SSD", hdd: "HDD", virtual: "virtual disk" };
-
-/** What Kaname detected on the Docker host, with manual values for what it can't see. */
-export function HardwareSettings({
- detected,
- overrides,
- summary,
- dockerConnected,
-}: {
- detected: HostHardware | null;
- overrides: HardwareOverrides;
- summary: string[];
- dockerConnected: boolean;
-}) {
- const router = useRouter();
- const [gpus, setGpus] = useState>(() => Object.fromEntries((detected?.gpus ?? []).map((g) => [g.pciAddress, toForm(overrides.gpus?.[g.pciAddress])])));
- const [p2p, setP2p] = useState(overrides.p2p ?? "");
- const [storage, setStorage] = useState(overrides.storage ?? "");
- const [hypervisor, setHypervisor] = useState(overrides.hypervisor ?? "");
- const [passthrough, setPassthrough] = useState(overrides.gpuPassthrough == null ? "" : overrides.gpuPassthrough ? "yes" : "no");
- const [gpuDriver, setGpuDriver] = useState(overrides.gpuDriver ?? "");
- const [busy, setBusy] = useState(false);
-
- const setGpu = (addr: string, patch: Partial) => setGpus((g) => ({ ...g, [addr]: { ...g[addr], ...patch } }));
-
- async function save() {
- setBusy(true);
- try {
- const body: HardwareOverrides = {
- gpus: Object.fromEntries(
- Object.entries(gpus).map(([addr, g]) => [
- addr,
- {
- name: g.name || undefined,
- vramMb: g.vramMb ? Number(g.vramMb) : undefined,
- linkCurrent: g.linkCurrent || undefined,
- linkMax: g.linkMax || undefined,
- rebar: g.rebar ? g.rebar === "on" : undefined,
- },
- ]),
- ),
- p2p: (p2p || undefined) as HardwareOverrides["p2p"],
- storage: storage || undefined,
- hypervisor: hypervisor || undefined,
- gpuPassthrough: passthrough ? passthrough === "yes" : undefined,
- gpuDriver: gpuDriver || undefined,
- };
- const res = await fetch("/api/settings/hardware", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
- const out = await res.json().catch(() => ({}));
- if (!res.ok) return void toast.error(out.error?.message ?? `Could not save (${res.status})`);
- toast.success("Saved; new benchmark runs use these values");
- router.refresh();
- } finally {
- setBusy(false);
- }
- }
-
- if (!detected) {
- return (
-
-
- Hardware
-
- {dockerConnected ? "The worker hasn't reported its hardware yet (it checks every few minutes)." : "Hardware is detected by the worker once Docker is connected (Settings → Runtimes)."}
-
-
-
- );
- }
-
- const v = detected.virtualization;
- return (
- {
- e.preventDefault();
- void save();
- }}
- >
-
-
- GPUs
-
- Recorded with every benchmark run. Detected from sysfs as the worker sees it; in a VM the PCIe link is the one the VM sees, which may not be the physical
- slot. Fill in a field to replace the detected value (empty = detected).
-
-
-
- {detected.gpus.length === 0 && No NVIDIA, Intel or AMD GPU found.
}
- {detected.gpus.map((g) => {
- const f = gpus[g.pciAddress];
- return (
-
-
- {g.name ?? "Unknown GPU"}
-
- {" "}
- · {g.pciAddress} · {g.driver ?? "no driver"}
- {g.driverVersion ? ` ${g.driverVersion}` : ""}
-
-
-
-
setGpu(g.pciAddress, { name: x })} />
- setGpu(g.pciAddress, { vramMb: x.replace(/\D/g, "") })}
- />
-
-
ReBAR
-
setGpu(g.pciAddress, { rebar: e.target.value as GpuForm["rebar"] })}>
- Detected: {onOff(g.rebar)}
- on
- off
-
-
Largest BAR {g.barMb != null ? formatBytes(g.barMb * 2 ** 20) : "unknown"}
-
- setGpu(g.pciAddress, { linkCurrent: x })}
- />
- setGpu(g.pciAddress, { linkMax: x })}
- />
-
-
- );
- })}
- {detected.gpus.length > 1 && (
-
- Peer-to-peer between GPUs
- setP2p(e.target.value as typeof p2p)}>
- Detected: {detected.p2p ?? "unknown"}
- on
- partial
- off
-
-
- )}
-
-
-
-
-
- System
- Part of the system summary recorded with each run, passed to BetterBench and shown in the launch80 preview.
-
-
-
-
-
-
- GPU passthrough
- setPassthrough(e.target.value)}>
- Detected: {v.vm ? (detected.gpus.length ? "yes" : "no") : v.vm === false ? "no (bare metal)" : "unknown"}
- yes
- no
-
-
-
[g.driver, g.driverVersion].filter(Boolean).join(" ")))].join(", ") || null}
- value={gpuDriver}
- placeholderHint="e.g. xe, compute runtime 25.35"
- onChange={setGpuDriver}
- />
-
-
-
- Save
-
-
-
-
-
-
-
- System summary
-
- Exactly what runs record and publish (after saving). Never the hostname, IP addresses, users or paths. Checked .
-
-
-
-
- {summary.map((l) => (
- {l}
- ))}
-
-
-
-
- );
-}
-
-function Field({
- id,
- label,
- detected,
- value,
- onChange,
- placeholderHint,
-}: {
- id: string;
- label: string;
- detected: string | null;
- value: string;
- onChange: (v: string) => void;
- placeholderHint?: string;
-}) {
- return (
-
-
{label}
-
onChange(e.target.value)} placeholder={detected ?? placeholderHint ?? "unknown"} maxLength={120} />
-
Detected: {detected ?? "unknown"}
-
- );
-}
diff --git a/src/app/(app)/settings/hardware/page.tsx b/src/app/(app)/settings/hardware/page.tsx
deleted file mode 100644
index bb965c9..0000000
--- a/src/app/(app)/settings/hardware/page.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import type { Metadata } from "next";
-import { kanameVersion } from "@/lib/benchmark-snapshot";
-import { applyOverrides, systemSummary, systemSummaryLines } from "@/lib/hardware";
-import { getDockerInfo } from "@/lib/runtimes";
-import { getHardwareOverrides } from "@/lib/settings";
-import { HardwareSettings } from "./hardware-settings";
-
-export const dynamic = "force-dynamic";
-export const metadata: Metadata = { title: "Hardware · Settings" };
-
-export default async function HardwareSettingsPage() {
- const [docker, overrides] = await Promise.all([getDockerInfo(), getHardwareOverrides()]);
- const hardware = docker?.hardware ?? null;
- const effective = applyOverrides(hardware, overrides);
- return (
-
- );
-}
diff --git a/src/app/(app)/settings/layout.tsx b/src/app/(app)/settings/layout.tsx
index 64ecfe1..18798a6 100644
--- a/src/app/(app)/settings/layout.tsx
+++ b/src/app/(app)/settings/layout.tsx
@@ -1,14 +1,10 @@
-import { BotIcon, BoxesIcon, CpuIcon, DownloadIcon, KeyRoundIcon, TagIcon, TagsIcon } from "lucide-react";
+import { DownloadIcon, TagIcon, TagsIcon } from "lucide-react";
import { SettingsNav } from "./settings-nav";
const SECTIONS = [
{ href: "/settings/labels", label: "File labels", icon: },
{ href: "/settings/tags", label: "Tags", icon: },
{ href: "/settings/downloads", label: "Downloads", icon: },
- { href: "/settings/runtimes", label: "Runtimes", icon: },
- { href: "/settings/hardware", label: "Hardware", icon: },
- { href: "/settings/api-keys", label: "Runtime API keys", icon: },
- { href: "/settings/api-tokens", label: "API tokens", icon: },
];
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
diff --git a/src/app/(app)/settings/runtimes/page.tsx b/src/app/(app)/settings/runtimes/page.tsx
deleted file mode 100644
index 4ca438e..0000000
--- a/src/app/(app)/settings/runtimes/page.tsx
+++ /dev/null
@@ -1,12 +0,0 @@
-import type { Metadata } from "next";
-import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
-import { getWorkerStatus } from "@/lib/worker-status";
-import { RuntimesView } from "./runtimes-view";
-
-export const dynamic = "force-dynamic";
-export const metadata: Metadata = { title: "Runtimes · Settings" };
-
-export default async function RuntimesPage() {
- const [runtimes, docker, worker] = await Promise.all([listRuntimes(), getDockerInfo(), getWorkerStatus()]);
- return ;
-}
diff --git a/src/app/(app)/settings/runtimes/runtime-form.tsx b/src/app/(app)/settings/runtimes/runtime-form.tsx
deleted file mode 100644
index 7c9de93..0000000
--- a/src/app/(app)/settings/runtimes/runtime-form.tsx
+++ /dev/null
@@ -1,220 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { ArgsEditor } from "@/components/args-editor";
-import { Button } from "@/components/ui/button";
-import { Checkbox } from "@/components/ui/checkbox";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { NativeSelect } from "@/components/ui/native-select";
-import { RUNTIME_ACCELERATORS, type RuntimeAccelerator, type RuntimeEngine } from "@/lib/db/schema";
-import { argsToRows, rowsToArgs } from "@/lib/extra-args";
-import { ACCELERATOR_DEVICES, ACCELERATOR_LABEL, formatEnvLines, parseEnvLines, type RuntimeInput, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
-import { cn } from "@/lib/utils";
-
-const ENGINES: { id: RuntimeEngine; label: string; hint: string }[] = [
- { id: "llama.cpp", label: "llama.cpp-compatible", hint: "llama-server command line, GGUF models" },
- { id: "vllm", label: "vLLM-compatible", hint: "vllm serve command line, safetensors models" },
-];
-
-const textareaClass =
- "min-h-20 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 font-mono text-xs outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30";
-
-/** Create/edit a runtime. Validates locally with the same rules as the server. */
-export function RuntimeForm({
- initial,
- submitLabel,
- onSubmit,
- onCancel,
-}: {
- initial: RuntimeInput;
- submitLabel: string;
- onSubmit: (value: RuntimeInput) => Promise;
- onCancel: () => void;
-}) {
- const [name, setName] = useState(initial.name);
- const [engine, setEngine] = useState(initial.engine);
- const [accelerator, setAccelerator] = useState(initial.accelerator ?? "cpu");
- const [image, setImage] = useState(initial.image);
- const [description, setDescription] = useState(initial.description ?? "");
- const [engineName, setEngineName] = useState(initial.engineName ?? "");
- const [envText, setEnvText] = useState(formatEnvLines(initial.env ?? {}));
- const [argRows, setArgRows] = useState(() => argsToRows(initial.extraArgs ?? []));
- const [devicesText, setDevicesText] = useState((initial.devices ?? []).join(", "));
- const [shm, setShm] = useState(initial.shmSizeMb != null ? String(initial.shmSizeMb) : "");
- const [numa, setNuma] = useState(!!initial.numaTuning);
- const [error, setError] = useState(null);
- const [saving, setSaving] = useState(false);
-
- async function submit(e: React.FormEvent) {
- e.preventDefault();
- let value: RuntimeInput;
- try {
- value = validateRuntime({
- name,
- engine,
- accelerator,
- image,
- description,
- engineName,
- env: parseEnvLines(envText),
- extraArgs: rowsToArgs(argRows),
- devices: devicesText.split(/[,\s]+/),
- shmSizeMb: shm.trim() ? Number(shm) : null,
- numaTuning: numa,
- });
- } catch (err) {
- setError(err instanceof RuntimeValidationError ? err.message : String(err));
- return;
- }
- setError(null);
- setSaving(true);
- try {
- await onSubmit(value);
- } finally {
- setSaving(false);
- }
- }
-
- return (
-
-
-
-
-
Engine type
-
- {ENGINES.map((e) => (
- setEngine(e.id)}
- className={cn(
- "flex flex-col items-start rounded-lg border px-3 py-2 text-left text-sm transition-colors",
- engine === e.id ? "border-primary bg-primary/5" : "hover:bg-muted/50",
- )}
- >
- {e.label}
- {e.hint}
-
- ))}
-
-
- Decides how Kaname builds the command line. Forks with the same CLI (e.g. patched vLLM builds) use the same type.
-
-
-
-
-
Runs on
-
{
- const next = e.target.value as RuntimeAccelerator;
- setAccelerator(next);
- // Suggest the device nodes the accelerator needs.
- if (!devicesText.trim()) setDevicesText(ACCELERATOR_DEVICES[next].join(", "));
- }}
- >
- {RUNTIME_ACCELERATORS.map((a) => (
-
- {ACCELERATOR_LABEL[a]}
-
- ))}
-
-
- {accelerator === "nvidia"
- ? "GPUs are requested from Docker (NVIDIA Container Toolkit on the host); each deployment picks which ones."
- : accelerator === "dri"
- ? "Intel and AMD GPUs are passed in as /dev/dri (Vulkan, Intel SYCL, vLLM XPU). The image must be built for it."
- : accelerator === "rocm"
- ? "AMD GPUs with ROCm: /dev/kfd and /dev/dri are passed in."
- : "CPU and RAM only."}
-
-
-
-
- Description
- setDescription(e.target.value)} maxLength={2000} />
-
-
-
-
Engine name
-
setEngineName(e.target.value)} maxLength={60} placeholder={engine} spellCheck={false} />
-
For forks: recorded with every benchmark next to the version the server reports, e.g. vllm-radiance.
-
-
-
-
Environment
-
setEnvText(e.target.value)}
- spellCheck={false}
- className={textareaClass}
- placeholder={"VLLM_CPU_KVCACHE_SPACE=4"}
- />
- One KEY=value per line.
-
-
-
Extra arguments
-
-
Added to every deployment's command; a deployment can override them.
-
-
-
-
-
- setNuma(v === true)} className="mt-0.5" />
-
- NUMA tuning
-
- Adds CAP_SYS_NICE and seccomp=unconfined, as vLLM recommends for its CPU build. This relaxes
- the container's isolation; leave it off unless you need the extra speed.
-
-
-
-
- {error && {error}
}
-
-
- Cancel
-
-
- {saving ? "Saving…" : submitLabel}
-
-
-
- );
-}
diff --git a/src/app/(app)/settings/runtimes/runtimes-view.tsx b/src/app/(app)/settings/runtimes/runtimes-view.tsx
deleted file mode 100644
index b3d5331..0000000
--- a/src/app/(app)/settings/runtimes/runtimes-view.tsx
+++ /dev/null
@@ -1,381 +0,0 @@
-"use client";
-
-import { ChevronDownIcon, CopyIcon, DownloadCloudIcon, PencilIcon, PlusIcon, ServerIcon, Trash2Icon } from "lucide-react";
-import { useRouter } from "next/navigation";
-import { useEffect, useState } from "react";
-import { toast } from "sonner";
-import { LocalTime } from "@/components/local-time";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
-} from "@/components/ui/alert-dialog";
-import { Button } from "@/components/ui/button";
-import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuGroup,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { Progress } from "@/components/ui/progress";
-import type { DockerHostInfo, runtimes } from "@/lib/db/schema";
-import { formatBytes, percent } from "@/lib/format";
-import { ACCELERATOR_LABEL, RUNTIME_PRESETS, type RuntimeInput } from "@/lib/runtimes-shared";
-import { cn } from "@/lib/utils";
-import { RuntimeForm } from "./runtime-form";
-
-type Runtime = typeof runtimes.$inferSelect;
-
-const FEATURE_LABEL: Record = {
- avx2: "AVX2",
- avx512f: "AVX-512",
- avx512_bf16: "AVX-512 BF16",
- avx512_vnni: "AVX-512 VNNI",
- avx512bw: "AVX-512 BW",
- amx_bf16: "AMX BF16",
- amx_int8: "AMX INT8",
- f16c: "F16C",
- fma: "FMA",
-};
-
-async function send(url: string, method: string, body?: unknown): Promise {
- const res = await fetch(url, {
- method,
- headers: body ? { "Content-Type": "application/json" } : undefined,
- body: body ? JSON.stringify(body) : undefined,
- });
- if (res.ok) return true;
- const json = await res.json().catch(() => ({}));
- toast.error(json.error?.message ?? `Request failed (${res.status})`);
- return false;
-}
-
-const toInput = (r: Runtime): RuntimeInput => ({
- name: r.name,
- engine: r.engine,
- accelerator: r.accelerator,
- image: r.image,
- description: r.description,
- engineName: r.engineName,
- env: r.env,
- extraArgs: r.extraArgs,
- devices: r.devices,
- shmSizeMb: r.shmSizeMb,
- numaTuning: r.numaTuning,
-});
-
-export function RuntimesView({ runtimes, docker, workerOnline }: { runtimes: Runtime[]; docker: DockerHostInfo | null; workerOnline: boolean }) {
- const router = useRouter();
- const [creating, setCreating] = useState<(RuntimeInput & { preset?: string }) | null>(null);
- const [editing, setEditing] = useState(null);
- const anyPulling = runtimes.some((r) => r.imageState === "pulling" || (r.pullRequestedAt && (!r.pullStartedAt || r.pullRequestedAt > r.pullStartedAt)));
-
- // While a pull runs, refresh the server data every 2 s for its progress.
- useEffect(() => {
- if (!anyPulling) return;
- const t = setInterval(() => router.refresh(), 2_000);
- return () => clearInterval(t);
- }, [anyPulling, router]);
-
- return (
-
-
-
-
-
- Runtimes
-
- Container images that serve models: official llama.cpp and vLLM builds, or your own forks from any registry. Kaname
- only starts images registered here, with the models mounted read-only.
-
-
-
- }>
-
- Add runtime
-
-
-
-
- From a preset
- {RUNTIME_PRESETS.map((p) => (
- setCreating({ ...p, name: p.name, preset: p.id })} className="flex-col items-start gap-0">
- {p.name}
- {p.summary}
-
- ))}
-
-
- setCreating({ name: "", engine: "vllm", image: "" })}>Custom image (fork)…
-
-
-
-
-
- {creating && (
-
- setCreating(null)}
- onSubmit={async (value) => {
- const ok = await send("/api/runtimes", "POST", { ...value, preset: creating.preset });
- if (ok) {
- toast.success(`Runtime "${value.name}" added`);
- setCreating(null);
- router.refresh();
- }
- return ok;
- }}
- />
-
- )}
- {runtimes.length === 0 && !creating && No runtimes yet. Add one from a preset.
}
- {runtimes.map((r) =>
- editing === r.id ? (
-
- setEditing(null)}
- onSubmit={async (value) => {
- const ok = await send(`/api/runtimes/${r.id}`, "PUT", value);
- if (ok) {
- setEditing(null);
- router.refresh();
- }
- return ok;
- }}
- />
-
- ) : (
- setEditing(r.id)}
- onDuplicate={() => setCreating({ ...toInput(r), name: `${r.name} (copy)` })}
- />
- ),
- )}
-
-
-
- );
-}
-
-function HostCard({ docker, workerOnline }: { docker: DockerHostInfo | null; workerOnline: boolean }) {
- return (
-
-
-
-
- Docker host
-
-
- {!workerOnline
- ? "The worker is offline; these facts may be outdated."
- : !docker
- ? "Not connected. Runtimes need the worker to reach Docker through the socket proxy (DOCKER_HOST)."
- : docker.connected
- ? `Docker ${docker.serverVersion} on ${docker.os} (${docker.architecture})`
- : `Can't reach Docker: ${docker.error}`}
-
-
- {docker && (
-
-
- CPU
-
- {docker.cpuModel ?? "unknown"}
- {docker.cpus != null && · {docker.cpus} threads }
-
- Features
-
- {docker.cpuFeatures.length === 0 ? (
- unknown
- ) : (
- docker.cpuFeatures.map((f) => (
-
- {FEATURE_LABEL[f] ?? f}
-
- ))
- )}
-
- Memory
- {docker.memoryBytes != null ? formatBytes(docker.memoryBytes) : "unknown"}
- GPUs
-
- {docker.gpus && docker.gpus.length > 0 ? (
- docker.gpus.map((g) => (
-
- {g.index}: {g.name} · {formatBytes(g.memoryMb * 2 ** 20)} · driver {g.driver}
-
- ))
- ) : docker.nvidia ? (
-
- {docker.gpuError ? `NVIDIA runtime found, but listing GPUs failed: ${docker.gpuError}` : "NVIDIA runtime found, no GPUs listed."}
-
- ) : (
-
- No NVIDIA GPUs (no NVIDIA runtime in Docker). Intel/AMD GPUs aren't listed; pass /dev/dri to a runtime to use them.
-
- )}
-
- Network
-
- {docker.network ?? "not detected (set KANAME_DOCKER_NETWORK)"}
-
- Models
-
- {docker.modelsSource ? `${docker.modelsSource.source} (${docker.modelsSource.type}, mounted read-only)` : "not detected (set KANAME_MODELS_SOURCE)"}
-
- Checked
-
-
-
-
-
- )}
-
- );
-}
-
-function ImageState({ r }: { r: Runtime }) {
- const requested = !!r.pullRequestedAt && (!r.pullStartedAt || r.pullRequestedAt > r.pullStartedAt);
- if (r.imageState === "pulling" || requested) {
- const p = r.pullProgress;
- return (
-
-
- {p ? `${p.status} · ${formatBytes(p.doneBytes)}${p.totalBytes ? ` / ${formatBytes(p.totalBytes)}` : ""}` : "Pull queued…"}
-
-
-
- );
- }
- if (r.imageState === "present") {
- return (
-
- Pulled · {r.imageSize != null ? formatBytes(r.imageSize) : "?"}
- {r.imageCreated && (
-
- {" "}
- · built
-
- )}
- {r.imageDigest && (
-
- {" "}
- · {r.imageDigest.slice(0, 19)}…
-
- )}
-
- );
- }
- if (r.imageState === "failed") return Pull failed: {r.pullError} ;
- if (r.imageState === "missing") return Not pulled yet ;
- return Not checked yet ;
-}
-
-function RuntimeRow({
- runtime: r,
- dockerReady,
- onEdit,
- onDuplicate,
-}: {
- runtime: Runtime;
- dockerReady: boolean;
- onEdit: () => void;
- onDuplicate: () => void;
-}) {
- const router = useRouter();
- const pulling = r.imageState === "pulling";
- const envCount = Object.keys(r.env).length;
-
- return (
-
-
-
-
- {r.name}
- {r.engine === "vllm" ? "vLLM" : "llama.cpp"}
- {r.accelerator !== "cpu" && (
- {ACCELERATOR_LABEL[r.accelerator]}
- )}
- {r.numaTuning && NUMA tuning }
-
-
{r.image}
- {r.description &&
{r.description}
}
-
-
-
{
- if (await send(`/api/runtimes/${r.id}/pull`, "POST")) router.refresh();
- }}
- >
-
- {r.imageState === "present" ? "Update" : "Pull"}
-
-
-
-
-
-
-
-
- }>
-
-
-
-
- Delete runtime “{r.name}”?
- The pulled image stays in Docker; remove it there if you need the space.
-
-
- Cancel
- {
- if (await send(`/api/runtimes/${r.id}`, "DELETE")) router.refresh();
- }}
- >
- Delete
-
-
-
-
-
-
-
-
-
- {envCount > 0 && `${envCount} env var${envCount === 1 ? "" : "s"}`}
- {r.extraArgs.length > 0 && `${envCount > 0 ? " · " : ""}${r.extraArgs.join(" ")}`}
- {r.shmSizeMb != null && ` · shm ${r.shmSizeMb} MiB`}
- {r.devices.length > 0 && ` · ${r.devices.join(", ")}`}
-
-
-
- );
-}
diff --git a/src/app/api/api-keys/[id]/route.ts b/src/app/api/api-keys/[id]/route.ts
deleted file mode 100644
index 1ec8887..0000000
--- a/src/app/api/api-keys/[id]/route.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { ApiKeyError, deleteApiKey, revealApiKey } from "@/lib/api-keys";
-
-export const dynamic = "force-dynamic";
-
-/** The key's value ("show key" in Settings). */
-export const GET = withAuth>(async (_req, { params }) => {
- const { id } = await params;
- try {
- return NextResponse.json({ key: await revealApiKey(id) }, { headers: { "Cache-Control": "no-store" } });
- } catch (err) {
- if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
-
-/** Remove a key; running deployments keep accepting it until they restart. */
-export const DELETE = withAuth>(async (_req, { params }) => {
- const { id } = await params;
- try {
- await deleteApiKey(id);
- return new NextResponse(null, { status: 204 });
- } catch (err) {
- if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/api-keys/route.ts b/src/app/api/api-keys/route.ts
deleted file mode 100644
index b4bd39b..0000000
--- a/src/app/api/api-keys/route.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { ApiKeyBody, ApiKeyError, createApiKey, listApiKeys } from "@/lib/api-keys";
-
-export const dynamic = "force-dynamic";
-
-/** Keys without their values (only the last characters). */
-export const GET = withAuth(async () => NextResponse.json(await listApiKeys()));
-
-/** Add a key (generated when `key` is missing); the response carries the full key once. */
-export const POST = withAuth(async (req) => {
- try {
- return NextResponse.json(await createApiKey(ApiKeyBody.parse(await req.json())), { status: 201 });
- } catch (err) {
- if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/api-tokens/[id]/route.ts b/src/app/api/api-tokens/[id]/route.ts
deleted file mode 100644
index e19d4eb..0000000
--- a/src/app/api/api-tokens/[id]/route.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { NextResponse } from "next/server";
-import { z } from "zod";
-import { withAuth } from "@/lib/api-auth";
-import { apiError } from "@/lib/api-errors";
-import { deleteToken, revokeToken, TokenError, updateTokenScopes } from "@/lib/api-tokens";
-
-/** Revoke a token: it stops working immediately. */
-export const POST = withAuth>(async (_req, { params }) => {
- try {
- await revokeToken((await params).id);
- return NextResponse.json({ ok: true });
- } catch (err) {
- if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
- throw err;
- }
-});
-
-/** Change an active token's scopes. */
-export const PATCH = withAuth>(async (req, { params }) => {
- try {
- const { scopes } = z.object({ scopes: z.array(z.string()).max(20) }).parse(await req.json());
- await updateTokenScopes((await params).id, scopes);
- return NextResponse.json({ ok: true });
- } catch (err) {
- if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
- if (err instanceof z.ZodError) return apiError(400, "invalid_request", "scopes must be a list of scope names.");
- throw err;
- }
-});
-
-/** Delete a revoked token (frees its name). */
-export const DELETE = withAuth>(async (_req, { params }) => {
- try {
- await deleteToken((await params).id);
- return new NextResponse(null, { status: 204 });
- } catch (err) {
- if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
- throw err;
- }
-});
diff --git a/src/app/api/api-tokens/route.ts b/src/app/api/api-tokens/route.ts
deleted file mode 100644
index c055324..0000000
--- a/src/app/api/api-tokens/route.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { NextResponse } from "next/server";
-import { z } from "zod";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { createToken, listTokens, TokenError } from "@/lib/api-tokens";
-
-export const dynamic = "force-dynamic";
-
-/** API tokens for machine clients (Settings → API tokens). Never includes the tokens themselves. */
-export const GET = withAuth(async () => NextResponse.json(await listTokens()));
-
-const Body = z.object({ name: z.string().max(40), scopes: z.array(z.string()).min(1).max(10) });
-
-/** Create a token. The response is the only time the token is shown. */
-export const POST = withAuth(async (req) => {
- try {
- const body = Body.parse(await req.json());
- return NextResponse.json(await createToken(body.name, body.scopes), { status: 201, headers: { "Cache-Control": "no-store" } });
- } catch (err) {
- if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/benchmarks/[id]/approve/route.ts b/src/app/api/benchmarks/[id]/approve/route.ts
deleted file mode 100644
index cf432e0..0000000
--- a/src/app/api/benchmarks/[id]/approve/route.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { approveBenchmark, BenchmarkError } from "@/lib/benchmarks";
-
-/** Let a benchmark run an API token asked for. */
-export const POST = withAuth>(async (_req, { params }) => {
- try {
- const id = (await params).id;
- await approveBenchmark(id);
- return NextResponse.json({ ok: true });
- } catch (err) {
- if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/benchmarks/[id]/reject/route.ts b/src/app/api/benchmarks/[id]/reject/route.ts
deleted file mode 100644
index 2e4c8e1..0000000
--- a/src/app/api/benchmarks/[id]/reject/route.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { BenchmarkError, rejectBenchmark } from "@/lib/benchmarks";
-
-/** Turn down a benchmark run an API token asked for. */
-export const POST = withAuth>(async (_req, { params }) => {
- try {
- const id = (await params).id;
- await rejectBenchmark(id);
- return NextResponse.json({ ok: true });
- } catch (err) {
- if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/benchmarks/[id]/results/route.ts b/src/app/api/benchmarks/[id]/results/route.ts
index 324af73..0ef6af0 100644
--- a/src/app/api/benchmarks/[id]/results/route.ts
+++ b/src/app/api/benchmarks/[id]/results/route.ts
@@ -4,6 +4,7 @@ import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { AB_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
import { getBenchmark } from "@/lib/benchmarks";
+import { modelName } from "@/lib/benchmark-view";
export const dynamic = "force-dynamic";
@@ -24,6 +25,6 @@ export const GET = withAuth>(async
delete data.endpoint_a;
delete data.endpoint_b;
const json = JSON.stringify(data, null, 2);
- const name = `betterbench-${ab ? "ab-" : ""}${run.snapshot.deploymentName.replace(/[^\w.-]+/g, "-")}-${run.id.slice(-6).toLowerCase()}.json`;
+ const name = `betterbench-${ab ? "ab-" : ""}${modelName(run.snapshot).split("/").pop()!.replace(/[^\w.-]+/g, "-")}-${run.id.slice(-6).toLowerCase()}.json`;
return new Response(json, { headers: { "Content-Type": "application/json", "Content-Disposition": `attachment; filename="${name}"` } });
});
diff --git a/src/app/api/benchmarks/route.ts b/src/app/api/benchmarks/route.ts
index ed6a874..28533a7 100644
--- a/src/app/api/benchmarks/route.ts
+++ b/src/app/api/benchmarks/route.ts
@@ -5,13 +5,13 @@ import { BenchmarkBody, BenchmarkError, createBenchmark, listBenchmarks } from "
export const dynamic = "force-dynamic";
-/** All runs, newest first; `?deployment=` or `?model=` narrows them. */
+/** All runs, newest first; `?endpoint=` or `?model=` narrows them. */
export const GET = withAuth(async (req) => {
const sp = new URL(req.url).searchParams;
- return NextResponse.json(await listBenchmarks({ deploymentId: sp.get("deployment") ?? undefined, modelId: sp.get("model") ?? undefined }));
+ return NextResponse.json(await listBenchmarks({ endpointId: sp.get("endpoint") ?? undefined, modelId: sp.get("model") ?? undefined }));
});
-/** Queue a BetterBench run against a running deployment. */
+/** Queue a benchmark run against an endpoint. */
export const POST = withAuth(async (req) => {
try {
return NextResponse.json(await createBenchmark(BenchmarkBody.parse(await req.json())), { status: 201 });
diff --git a/src/app/api/deployments/[id]/approve/route.ts b/src/app/api/deployments/[id]/approve/route.ts
deleted file mode 100644
index cfe2671..0000000
--- a/src/app/api/deployments/[id]/approve/route.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { DeploymentError, setDesiredState } from "@/lib/deployments";
-
-/** Let the start of a deployment an API token asked for. */
-export const POST = withAuth>(async (_req, { params }) => {
- try {
- const id = (await params).id;
- await setDesiredState(id, "running");
- return NextResponse.json({ ok: true });
- } catch (err) {
- if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/deployments/[id]/chat/route.ts b/src/app/api/deployments/[id]/chat/route.ts
deleted file mode 100644
index 0d71a54..0000000
--- a/src/app/api/deployments/[id]/chat/route.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { z } from "zod";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { apiKeyValues } from "@/lib/api-keys";
-import { ENGINE_PORT } from "@/lib/deploy-command";
-import { getDeployment } from "@/lib/deployments";
-
-export const dynamic = "force-dynamic";
-
-const Body = z.object({
- messages: z.array(z.object({ role: z.enum(["system", "user", "assistant"]), content: z.string().max(100_000) })).min(1).max(100),
- maxTokens: z.number().int().min(1).max(8192).default(256),
-});
-
-/**
- * Smoke-test chat: forwards to the container's OpenAI-compatible API over the Docker network and
- * streams the server-sent events back unchanged.
- */
-export const POST = withAuth>(async (req, { params }) => {
- try {
- const d = await getDeployment((await params).id);
- if (!d) return apiError(404, "not_found", "Deployment not found.");
- if (d.state !== "running" || !d.containerName) return apiError(409, "not_running", "The deployment isn't running.");
- const { messages, maxTokens } = Body.parse(await req.json());
- // Any key works; keys added after the deployment started aren't known to it yet, so prefer the oldest.
- const [key] = d.options.requireApiKey ? await apiKeyValues() : [];
- const upstream = await fetch(`http://${d.containerName}:${ENGINE_PORT[d.engine]}/v1/chat/completions`, {
- method: "POST",
- headers: { "Content-Type": "application/json", ...(key ? { Authorization: `Bearer ${key}` } : {}) },
- body: JSON.stringify({ model: d.repoId, messages, max_tokens: maxTokens, stream: true, stream_options: { include_usage: true } }),
- signal: req.signal,
- }).catch((err: Error) => {
- throw new Error(`Can't reach the deployment (${err.message}). The web app must be on the same Docker network.`);
- });
- if (!upstream.ok || !upstream.body) {
- const text = await upstream.text().catch(() => "");
- if (upstream.status === 401) return apiError(502, "upstream", "The model server rejected Kaname's API key. Restart the deployment to pick up changed keys.");
- return apiError(502, "upstream", `The model server answered ${upstream.status}: ${text.slice(0, 500)}`);
- }
- return new Response(upstream.body, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-store" } });
- } catch (err) {
- if (err instanceof Error && err.message.startsWith("Can't reach")) return apiError(502, "unreachable", err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/deployments/[id]/logs/route.ts b/src/app/api/deployments/[id]/logs/route.ts
deleted file mode 100644
index 6cfdbef..0000000
--- a/src/app/api/deployments/[id]/logs/route.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { listDeploymentLogs } from "@/lib/deployments";
-
-export const dynamic = "force-dynamic";
-
-/** Log lines after `?after=` (first call: the last 500). */
-export const GET = withAuth>(async (req, { params }) => {
- const after = Number(new URL(req.url).searchParams.get("after") ?? 0) || 0;
- return NextResponse.json(await listDeploymentLogs((await params).id, after));
-});
diff --git a/src/app/api/deployments/[id]/protect/route.ts b/src/app/api/deployments/[id]/protect/route.ts
deleted file mode 100644
index 062366e..0000000
--- a/src/app/api/deployments/[id]/protect/route.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { NextResponse } from "next/server";
-import { z } from "zod";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { DeploymentError, setProtected } from "@/lib/deployments";
-
-const Body = z.object({ protected: z.boolean() });
-
-/** Protect a deployment from agents (or lift it). */
-export const POST = withAuth>(async (req, { params }) => {
- try {
- const { protected: value } = Body.parse(await req.json());
- await setProtected((await params).id, value);
- return NextResponse.json({ protected: value });
- } catch (err) {
- if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/deployments/[id]/reject/route.ts b/src/app/api/deployments/[id]/reject/route.ts
deleted file mode 100644
index 5d75b6c..0000000
--- a/src/app/api/deployments/[id]/reject/route.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { DeploymentError, rejectStart } from "@/lib/deployments";
-
-/** Turn down the start of a deployment an API token asked for. */
-export const POST = withAuth>(async (_req, { params }) => {
- try {
- const id = (await params).id;
- await rejectStart(id);
- return NextResponse.json({ ok: true });
- } catch (err) {
- if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/deployments/[id]/route.ts b/src/app/api/deployments/[id]/route.ts
deleted file mode 100644
index 51f5934..0000000
--- a/src/app/api/deployments/[id]/route.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { DeploymentBody, DeploymentError, getDeployment, requestDelete, updateDeployment } from "@/lib/deployments";
-
-export const dynamic = "force-dynamic";
-
-export const GET = withAuth>(async (_req, { params }) => {
- const d = await getDeployment((await params).id);
- return d ? NextResponse.json(d) : apiError(404, "not_found", "Deployment not found.");
-});
-
-export const PUT = withAuth>(async (req, { params }) => {
- try {
- await updateDeployment((await params).id, DeploymentBody.parse(await req.json()));
- return new NextResponse(null, { status: 204 });
- } catch (err) {
- if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
-
-/** Stop the container (if running) and delete the deployment. */
-export const DELETE = withAuth>(async (_req, { params }) => {
- try {
- await requestDelete((await params).id);
- return new NextResponse(null, { status: 202 });
- } catch (err) {
- if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/deployments/[id]/start/route.ts b/src/app/api/deployments/[id]/start/route.ts
deleted file mode 100644
index 239b110..0000000
--- a/src/app/api/deployments/[id]/start/route.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { DeploymentError, setDesiredState } from "@/lib/deployments";
-
-export const POST = withAuth>(async (_req, { params }) => {
- try {
- await setDesiredState((await params).id, "running");
- return new NextResponse(null, { status: 202 });
- } catch (err) {
- if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/deployments/[id]/stop/route.ts b/src/app/api/deployments/[id]/stop/route.ts
deleted file mode 100644
index 0dc97b9..0000000
--- a/src/app/api/deployments/[id]/stop/route.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { DeploymentError, setDesiredState } from "@/lib/deployments";
-
-export const POST = withAuth>(async (_req, { params }) => {
- try {
- await setDesiredState((await params).id, "stopped");
- return new NextResponse(null, { status: 202 });
- } catch (err) {
- if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/deployments/route.ts b/src/app/api/deployments/route.ts
deleted file mode 100644
index 5f547aa..0000000
--- a/src/app/api/deployments/route.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { NextResponse } from "next/server";
-import { z } from "zod";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { createDeployment, DeploymentBody, DeploymentError, listDeployments } from "@/lib/deployments";
-
-export const dynamic = "force-dynamic";
-
-export const GET = withAuth(async () => NextResponse.json(await listDeployments()));
-
-/** Create a deployment; `start: true` starts it right away. */
-export const POST = withAuth(async (req) => {
- try {
- const body = DeploymentBody.extend({ start: z.boolean().default(true) }).parse(await req.json());
- return NextResponse.json(await createDeployment(body, body.start), { status: 201 });
- } catch (err) {
- if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/endpoints/[id]/route.ts b/src/app/api/endpoints/[id]/route.ts
new file mode 100644
index 0000000..51452f9
--- /dev/null
+++ b/src/app/api/endpoints/[id]/route.ts
@@ -0,0 +1,32 @@
+import { NextResponse } from "next/server";
+import { withAuth } from "@/lib/api-auth";
+import { apiError, handleApiError } from "@/lib/api-errors";
+import { deleteEndpoint, EndpointError, getEndpoint, updateEndpoint } from "@/lib/endpoints";
+
+export const dynamic = "force-dynamic";
+
+const fail = (err: unknown) => (err instanceof EndpointError ? apiError(err.status, err.code, err.message) : handleApiError(err));
+
+export const GET = withAuth>(async (_req, { params }) => {
+ const e = await getEndpoint((await params).id);
+ return e ? NextResponse.json(e) : apiError(404, "not_found", "Endpoint not found.");
+});
+
+/** Change an endpoint; leave `apiKey` out to keep the stored key, send "" to remove it. */
+export const PATCH = withAuth>(async (req, { params }) => {
+ try {
+ return NextResponse.json(await updateEndpoint((await params).id, await req.json()));
+ } catch (err) {
+ return fail(err);
+ }
+});
+
+/** Delete an endpoint; its runs stay (with their snapshot). */
+export const DELETE = withAuth>(async (_req, { params }) => {
+ try {
+ await deleteEndpoint((await params).id);
+ return new NextResponse(null, { status: 204 });
+ } catch (err) {
+ return fail(err);
+ }
+});
diff --git a/src/app/api/endpoints/[id]/test/route.ts b/src/app/api/endpoints/[id]/test/route.ts
new file mode 100644
index 0000000..a87ee44
--- /dev/null
+++ b/src/app/api/endpoints/[id]/test/route.ts
@@ -0,0 +1,17 @@
+import { NextResponse } from "next/server";
+import { withAuth } from "@/lib/api-auth";
+import { apiError, handleApiError } from "@/lib/api-errors";
+import { EndpointError, testEndpoint } from "@/lib/endpoints";
+
+export const dynamic = "force-dynamic";
+
+/** Test a saved endpoint (stores the result), or, with a body, the form's unsaved values for it. */
+export const POST = withAuth>(async (req, { params }) => {
+ try {
+ const text = await req.text();
+ return NextResponse.json(await testEndpoint((await params).id, text ? JSON.parse(text) : undefined));
+ } catch (err) {
+ if (err instanceof EndpointError) return apiError(err.status, err.code, err.message);
+ return handleApiError(err);
+ }
+});
diff --git a/src/app/api/endpoints/route.ts b/src/app/api/endpoints/route.ts
new file mode 100644
index 0000000..82d0747
--- /dev/null
+++ b/src/app/api/endpoints/route.ts
@@ -0,0 +1,18 @@
+import { NextResponse } from "next/server";
+import { withAuth } from "@/lib/api-auth";
+import { apiError, handleApiError } from "@/lib/api-errors";
+import { createEndpoint, EndpointError, listEndpoints } from "@/lib/endpoints";
+
+export const dynamic = "force-dynamic";
+
+/** All endpoints (never their API keys). */
+export const GET = withAuth(async () => NextResponse.json(await listEndpoints()));
+
+export const POST = withAuth(async (req) => {
+ try {
+ return NextResponse.json(await createEndpoint(await req.json()), { status: 201 });
+ } catch (err) {
+ if (err instanceof EndpointError) return apiError(err.status, err.code, err.message);
+ return handleApiError(err);
+ }
+});
diff --git a/src/app/api/endpoints/test/route.ts b/src/app/api/endpoints/test/route.ts
new file mode 100644
index 0000000..4dc11c9
--- /dev/null
+++ b/src/app/api/endpoints/test/route.ts
@@ -0,0 +1,16 @@
+import { NextResponse } from "next/server";
+import { withAuth } from "@/lib/api-auth";
+import { apiError, handleApiError } from "@/lib/api-errors";
+import { EndpointError, testEndpoint } from "@/lib/endpoints";
+
+export const dynamic = "force-dynamic";
+
+/** Test a new endpoint's form values before saving. */
+export const POST = withAuth(async (req) => {
+ try {
+ return NextResponse.json(await testEndpoint(null, await req.json()));
+ } catch (err) {
+ if (err instanceof EndpointError) return apiError(err.status, err.code, err.message);
+ return handleApiError(err);
+ }
+});
diff --git a/src/app/api/jobs/[id]/approve/route.ts b/src/app/api/jobs/[id]/approve/route.ts
deleted file mode 100644
index 89b8e56..0000000
--- a/src/app/api/jobs/[id]/approve/route.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { NextResponse } from "next/server";
-import { approveJob } from "@/lib/agent-downloads";
-import { withAuth } from "@/lib/api-auth";
-import { apiError } from "@/lib/api-errors";
-import { JobError } from "@/lib/jobs";
-
-/** Let a download requested through the API start. */
-export const POST = withAuth>(async (_req, { params }) => {
- const { id } = await params;
- try {
- await approveJob(id);
- return NextResponse.json({ ok: true });
- } catch (err) {
- if (err instanceof JobError) return apiError(err.status, err.code, err.message);
- throw err;
- }
-});
diff --git a/src/app/api/jobs/[id]/reject/route.ts b/src/app/api/jobs/[id]/reject/route.ts
deleted file mode 100644
index dae3c8f..0000000
--- a/src/app/api/jobs/[id]/reject/route.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { NextResponse } from "next/server";
-import { rejectJob } from "@/lib/agent-downloads";
-import { withAuth } from "@/lib/api-auth";
-import { apiError } from "@/lib/api-errors";
-import { JobError } from "@/lib/jobs";
-
-/** Turn down a download requested through the API (a model only it added leaves the library). */
-export const POST = withAuth>(async (_req, { params }) => {
- const { id } = await params;
- try {
- return NextResponse.json(await rejectJob(id));
- } catch (err) {
- if (err instanceof JobError) return apiError(err.status, err.code, err.message);
- throw err;
- }
-});
diff --git a/src/app/api/runtimes/[id]/pull/route.ts b/src/app/api/runtimes/[id]/pull/route.ts
deleted file mode 100644
index f01aea7..0000000
--- a/src/app/api/runtimes/[id]/pull/route.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { requestPull, RuntimeError } from "@/lib/runtimes";
-
-/** Ask the worker to pull the image (again; updates moving tags like :server). */
-export const POST = withAuth>(async (_req, { params }) => {
- const { id } = await params;
- try {
- await requestPull(id);
- return new NextResponse(null, { status: 202 });
- } catch (err) {
- if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/runtimes/[id]/route.ts b/src/app/api/runtimes/[id]/route.ts
deleted file mode 100644
index 83945ba..0000000
--- a/src/app/api/runtimes/[id]/route.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { deleteRuntime, RuntimeBody, RuntimeError, updateRuntime } from "@/lib/runtimes";
-
-export const PUT = withAuth>(async (req, { params }) => {
- const { id } = await params;
- try {
- return NextResponse.json(await updateRuntime(id, RuntimeBody.parse(await req.json())));
- } catch (err) {
- if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
-
-export const DELETE = withAuth>(async (_req, { params }) => {
- const { id } = await params;
- try {
- await deleteRuntime(id);
- return new NextResponse(null, { status: 204 });
- } catch (err) {
- if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/runtimes/route.ts b/src/app/api/runtimes/route.ts
deleted file mode 100644
index d17bff4..0000000
--- a/src/app/api/runtimes/route.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { NextResponse } from "next/server";
-import { z } from "zod";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { createRuntime, getDockerInfo, listRuntimes, RuntimeBody, RuntimeError } from "@/lib/runtimes";
-
-export const dynamic = "force-dynamic";
-
-
-/** Runtimes plus the Docker facts the worker reported. */
-export const GET = withAuth(async () => NextResponse.json({ runtimes: await listRuntimes(), docker: await getDockerInfo() }));
-
-export const POST = withAuth(async (req) => {
- try {
- const body = RuntimeBody.extend({ preset: z.string().optional() }).parse(await req.json());
- return NextResponse.json(await createRuntime(body), { status: 201 });
- } catch (err) {
- if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/settings/agent/route.ts b/src/app/api/settings/agent/route.ts
deleted file mode 100644
index eb57a25..0000000
--- a/src/app/api/settings/agent/route.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { NextResponse } from "next/server";
-import { z } from "zod";
-import { APPROVAL_MODES } from "@/lib/agent-guardrails";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { getGuardrails, saveGuardrails, SettingsError } from "@/lib/settings";
-
-export const dynamic = "force-dynamic";
-
-/** Guardrails for downloads requested through the API. */
-export const GET = withAuth(async () => NextResponse.json(await getGuardrails()));
-
-const Body = z
- .object({
- approvalMode: z.enum(APPROVAL_MODES),
- maxRequestBytes: z.number(),
- minFreeBytes: z.number(),
- maxOpenJobs: z.number().int(),
- allowedAuthors: z.array(z.string()).max(100),
- })
- .partial();
-
-export const PUT = withAuth(async (req) => {
- try {
- return NextResponse.json(await saveGuardrails(Body.parse(await req.json())));
- } catch (err) {
- if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/settings/hardware/route.ts b/src/app/api/settings/hardware/route.ts
deleted file mode 100644
index 9ee296f..0000000
--- a/src/app/api/settings/hardware/route.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { getHardwareOverrides, saveHardwareOverrides, SettingsError } from "@/lib/settings";
-
-export const dynamic = "force-dynamic";
-
-/** Manual hardware values for benchmark records (Settings → Hardware). */
-export const GET = withAuth(async () => NextResponse.json(await getHardwareOverrides()));
-
-export const PUT = withAuth(async (req) => {
- try {
- return NextResponse.json(await saveHardwareOverrides(await req.json()));
- } catch (err) {
- if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/settings/tuning/route.ts b/src/app/api/settings/tuning/route.ts
deleted file mode 100644
index 68bfaa3..0000000
--- a/src/app/api/settings/tuning/route.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { NextResponse } from "next/server";
-import { z } from "zod";
-import { APPROVAL_MODES } from "@/lib/agent-guardrails";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { getTuning, saveTuning, SettingsError } from "@/lib/settings";
-
-export const dynamic = "force-dynamic";
-
-/** Guardrails for deployments and benchmarks requested through the API. */
-export const GET = withAuth(async () => NextResponse.json(await getTuning()));
-
-const Body = z
- .object({
- approvalMode: z.enum(APPROVAL_MODES),
- maxAgentDeployments: z.number().int(),
- maxRunMinutes: z.number().int(),
- maxSweepMinutes: z.number().int(),
- maxSweepVariants: z.number().int(),
- allowedRuntimeIds: z.array(z.string().max(64)).max(100),
- allowedArgs: z.object({ "llama.cpp": z.array(z.string().max(80)).max(500), vllm: z.array(z.string().max(80)).max(500) }),
- hostPortRange: z.object({ from: z.number().int(), to: z.number().int() }).nullable(),
- maxMemoryMb: z.number().nullable(),
- maxCpus: z.number().nullable(),
- })
- .partial();
-
-export const PUT = withAuth(async (req) => {
- try {
- return NextResponse.json(await saveTuning(Body.parse(await req.json())));
- } catch (err) {
- if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/sweeps/[id]/approve/route.ts b/src/app/api/sweeps/[id]/approve/route.ts
deleted file mode 100644
index 02b5abc..0000000
--- a/src/app/api/sweeps/[id]/approve/route.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { decideSweep, SweepRequestError } from "@/lib/sweeps";
-
-/** Let a sweep an API token asked for. */
-export const POST = withAuth>(async (_req, { params }) => {
- try {
- const id = (await params).id;
- await decideSweep(id, true);
- return NextResponse.json({ ok: true });
- } catch (err) {
- if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/sweeps/[id]/cancel/route.ts b/src/app/api/sweeps/[id]/cancel/route.ts
deleted file mode 100644
index 3b6a402..0000000
--- a/src/app/api/sweeps/[id]/cancel/route.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { cancelSweep, SweepRequestError } from "@/lib/sweeps";
-
-export const POST = withAuth>(async (_req, { params }) => {
- try {
- await cancelSweep((await params).id);
- return new NextResponse(null, { status: 202 });
- } catch (err) {
- if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/sweeps/[id]/reject/route.ts b/src/app/api/sweeps/[id]/reject/route.ts
deleted file mode 100644
index a95e96a..0000000
--- a/src/app/api/sweeps/[id]/reject/route.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { decideSweep, SweepRequestError } from "@/lib/sweeps";
-
-/** Turn down a sweep an API token asked for. */
-export const POST = withAuth>(async (_req, { params }) => {
- try {
- const id = (await params).id;
- await decideSweep(id, false);
- return NextResponse.json({ ok: true });
- } catch (err) {
- if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/sweeps/[id]/route.ts b/src/app/api/sweeps/[id]/route.ts
deleted file mode 100644
index 54478ef..0000000
--- a/src/app/api/sweeps/[id]/route.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { deleteSweep, getSweep, SweepRequestError } from "@/lib/sweeps";
-
-export const dynamic = "force-dynamic";
-
-export const GET = withAuth>(async (_req, { params }) => {
- const s = await getSweep((await params).id);
- return s ? NextResponse.json(s) : apiError(404, "not_found", "Sweep not found.");
-});
-
-export const DELETE = withAuth>(async (_req, { params }) => {
- try {
- await deleteSweep((await params).id);
- return new NextResponse(null, { status: 204 });
- } catch (err) {
- if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/sweeps/route.ts b/src/app/api/sweeps/route.ts
deleted file mode 100644
index ca9c809..0000000
--- a/src/app/api/sweeps/route.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { NextResponse } from "next/server";
-import { withAuth } from "@/lib/api-auth";
-import { apiError, handleApiError } from "@/lib/api-errors";
-import { createSweep, listSweeps, SweepBody, SweepRequestError } from "@/lib/sweeps";
-
-export const dynamic = "force-dynamic";
-
-export const GET = withAuth(async () => NextResponse.json(await listSweeps()));
-
-/** Queue a sweep: one or two settings varied over a base deployment, one benchmark per variant. */
-export const POST = withAuth(async (req) => {
- try {
- return NextResponse.json(await createSweep(SweepBody.parse(await req.json())), { status: 201 });
- } catch (err) {
- if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message);
- return handleApiError(err);
- }
-});
diff --git a/src/app/api/v1/benchmarks/[id]/cancel/route.ts b/src/app/api/v1/benchmarks/[id]/cancel/route.ts
deleted file mode 100644
index 24c64e4..0000000
--- a/src/app/api/v1/benchmarks/[id]/cancel/route.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { act } from "@/lib/agent-activity";
-import { ownRun } from "@/lib/agent-runs";
-import { withToken } from "@/lib/api-tokens";
-import { v1Catch, v1Json } from "@/lib/api-v1";
-import { cancelBenchmark } from "@/lib/benchmarks";
-
-/** Cancel a run this token started. */
-export const POST = withToken>("benchmarks:run", async (_req, { params, token }) => {
- try {
- const id = (await params).id;
- await act(token, "benchmark.cancel", { type: "benchmark", id }, async () => {
- await ownRun(token, id);
- await cancelBenchmark(id);
- return { id };
- });
- return v1Json({ id, cancelled: true });
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/benchmarks/[id]/route.ts b/src/app/api/v1/benchmarks/[id]/route.ts
deleted file mode 100644
index 5731674..0000000
--- a/src/app/api/v1/benchmarks/[id]/route.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { runSettled, runView } from "@/lib/agent-runs";
-import { withToken } from "@/lib/api-tokens";
-import { v1Catch, v1Error, v1Json } from "@/lib/api-v1";
-import { getBenchmark } from "@/lib/benchmarks";
-import { parseWait, waitFor } from "@/lib/wait";
-
-export const dynamic = "force-dynamic";
-
-/**
- * A run's state and compact result (headline numbers, setup, resources). ?wait= (max 900) blocks
- * until it is finished or waits for approval; ?full=1 adds BetterBench's full summary.
- */
-export const GET = withToken>("benchmarks:read", async (req, { params, token }) => {
- try {
- const id = (await params).id;
- const q = new URL(req.url).searchParams;
- const { value: run, waitedS, timedOut } = await waitFor(() => getBenchmark(id), (r) => !r || runSettled(r.state), parseWait(q), { signal: req.signal });
- if (!run) return v1Error(404, "not_found", "No benchmark run with this id.");
- return v1Json({ ...runView(run, token, q.get("full") === "1"), ...(waitedS ? { waitedSeconds: waitedS, timedOut } : {}) });
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/benchmarks/compare/route.ts b/src/app/api/v1/benchmarks/compare/route.ts
deleted file mode 100644
index c1bcc65..0000000
--- a/src/app/api/v1/benchmarks/compare/route.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { compareRuns } from "@/lib/agent-runs";
-import { withToken } from "@/lib/api-tokens";
-import { v1Catch, v1Error, v1Json } from "@/lib/api-v1";
-
-export const dynamic = "force-dynamic";
-
-/** ?ids=a,b,c (2–16 runs): headline numbers side by side, the setup values that differ, and the shared ones. */
-export const GET = withToken("benchmarks:read", async (req) => {
- try {
- const ids = (new URL(req.url).searchParams.get("ids") ?? "").split(",").map((s) => s.trim()).filter(Boolean).slice(0, 16);
- if (ids.length < 2) return v1Error(400, "invalid_request", "Pass at least two run ids: ?ids=,");
- return v1Json(await compareRuns(ids));
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/benchmarks/route.ts b/src/app/api/v1/benchmarks/route.ts
deleted file mode 100644
index baf5557..0000000
--- a/src/app/api/v1/benchmarks/route.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { act } from "@/lib/agent-activity";
-import { AgentRunBody, listRunsFor, requestRun, runView } from "@/lib/agent-runs";
-import { withToken } from "@/lib/api-tokens";
-import { v1Catch, v1Json } from "@/lib/api-v1";
-
-export const dynamic = "force-dynamic";
-
-/** Recent runs, newest first: ?deployment=, ?requested_by=, ?limit=N (max 50). */
-export const GET = withToken("benchmarks:read", async (req, { token }) => {
- try {
- const q = new URL(req.url).searchParams;
- const limit = Math.min(50, Math.max(1, Number(q.get("limit")) || 20));
- const runs = await listRunsFor({ deploymentId: q.get("deployment") ?? undefined, requestedBy: q.get("requested_by") ?? undefined, limit });
- return v1Json({ count: runs.length, runs: runs.map((r) => runView(r, token)) });
- } catch (err) {
- return v1Catch(err);
- }
-});
-
-/** Queue a speed run (kind "run"), a paired A/B ("ab") or the quality eval ("eval") on the token's own running deployment(s). */
-export const POST = withToken("benchmarks:run", async (req, { token }) => {
- try {
- const body = AgentRunBody.parse(await req.json());
- const r = await act(token, `benchmark.${body.kind}`, { type: "benchmark" }, () => requestRun(token, body));
- return v1Json(
- {
- ...r,
- message:
- r.state === "pending_approval"
- ? "Requested; it waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop."
- : `Queued; GET /api/v1/benchmarks/${r.id}?wait=900 for the result (stopped after ${r.timeLimitMinutes} min).`,
- },
- 201,
- );
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/deployments/[id]/route.ts b/src/app/api/v1/deployments/[id]/route.ts
deleted file mode 100644
index 6d280d2..0000000
--- a/src/app/api/v1/deployments/[id]/route.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { act } from "@/lib/agent-activity";
-import { AgentDeploymentPatch, deleteAgentDeployment, deploymentSettled, deploymentView, updateAgentDeployment } from "@/lib/agent-deployments";
-import { withToken } from "@/lib/api-tokens";
-import { v1Catch, v1Error, v1Json } from "@/lib/api-v1";
-import { getDeployment, listDeploymentLogs } from "@/lib/deployments";
-import { parseWait, waitFor } from "@/lib/wait";
-
-export const dynamic = "force-dynamic";
-
-const MAX_LOG = 200;
-
-/**
- * State, endpoint, options, live usage. ?wait= (max 900) blocks until it is settled (running,
- * stopped, failed or waiting for approval); ?log=N adds the last N log lines.
- */
-export const GET = withToken>("deployments:read", async (req, { params, token }) => {
- try {
- const id = (await params).id;
- const q = new URL(req.url).searchParams;
- const { value: d, waitedS, timedOut } = await waitFor(
- () => getDeployment(id),
- (x) => !x || deploymentSettled(x) || !!x.startRequestedAt,
- parseWait(q),
- { signal: req.signal },
- );
- if (!d) return v1Error(404, "not_found", "No deployment with this id.");
- const n = Math.min(MAX_LOG, Math.max(0, Number(q.get("log")) || 0));
- const log = n > 0 ? (await listDeploymentLogs(id, 0, n)).map((l) => `${new Date(l.ts).toISOString()} [${l.stream}] ${l.line}`) : undefined;
- return v1Json({ ...deploymentView(d, token), ...(waitedS ? { waitedSeconds: waitedS, timedOut } : {}), ...(log ? { log } : {}) });
- } catch (err) {
- return v1Catch(err);
- }
-});
-
-/** Change an own, stopped deployment (fields left out stay). Returns the new command and estimates. */
-export const PATCH = withToken>("deployments:write", async (req, { params, token }) => {
- try {
- const id = (await params).id;
- const patch = AgentDeploymentPatch.parse(await req.json());
- const preview = await act(token, "deployment.update", { type: "deployment", id }, async () => ({ id, ...(await updateAgentDeployment(token, id, patch)) }));
- return v1Json({ ...preview, deployment: deploymentView((await getDeployment(id))!, token) });
- } catch (err) {
- return v1Catch(err);
- }
-});
-
-/** Delete an own deployment (the container is stopped and removed). */
-export const DELETE = withToken>("deployments:write", async (_req, { params, token }) => {
- try {
- const id = (await params).id;
- await act(token, "deployment.delete", { type: "deployment", id }, async () => {
- await deleteAgentDeployment(token, id);
- return { id };
- });
- return v1Json({ id, deleted: true });
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/deployments/[id]/start/route.ts b/src/app/api/v1/deployments/[id]/start/route.ts
deleted file mode 100644
index c5791c9..0000000
--- a/src/app/api/v1/deployments/[id]/start/route.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { act } from "@/lib/agent-activity";
-import { startAgentDeployment } from "@/lib/agent-deployments";
-import { withToken } from "@/lib/api-tokens";
-import { v1Catch, v1Json } from "@/lib/api-v1";
-
-/** Start an own deployment; with approval mode "approve" it waits for the user. */
-export const POST = withToken>("deployments:write", async (_req, { params, token }) => {
- try {
- const id = (await params).id;
- const r = await act(token, "deployment.start", { type: "deployment", id }, async () => ({ id, ...(await startAgentDeployment(token, id)) }));
- return v1Json({
- ...r,
- message:
- r.state === "pending_approval"
- ? "The start waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop."
- : `Starting; GET /api/v1/deployments/${id}?wait=600 until it is running.`,
- });
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/deployments/[id]/stop/route.ts b/src/app/api/v1/deployments/[id]/stop/route.ts
deleted file mode 100644
index 0c5c7bf..0000000
--- a/src/app/api/v1/deployments/[id]/stop/route.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { act } from "@/lib/agent-activity";
-import { stopAgentDeployment } from "@/lib/agent-deployments";
-import { withToken } from "@/lib/api-tokens";
-import { v1Catch, v1Json } from "@/lib/api-v1";
-
-/** Stop an own deployment (no approval needed). */
-export const POST = withToken>("deployments:write", async (_req, { params, token }) => {
- try {
- const id = (await params).id;
- await act(token, "deployment.stop", { type: "deployment", id }, async () => {
- await stopAgentDeployment(token, id);
- return { id };
- });
- return v1Json({ id, state: "stopping", message: `Stopping; GET /api/v1/deployments/${id}?wait=60 if you need to know it is stopped.` });
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/deployments/route.ts b/src/app/api/v1/deployments/route.ts
deleted file mode 100644
index 4fe38db..0000000
--- a/src/app/api/v1/deployments/route.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { act } from "@/lib/agent-activity";
-import { AgentDeploymentBody, createAgentDeployment, deploymentView } from "@/lib/agent-deployments";
-import { withToken } from "@/lib/api-tokens";
-import { v1Catch, v1Json } from "@/lib/api-v1";
-import { listDeployments } from "@/lib/deployments";
-
-export const dynamic = "force-dynamic";
-
-/** All deployments (agents may only change their own: "mine": true). ?mine=1 lists only those. */
-export const GET = withToken("deployments:read", async (req, { token }) => {
- try {
- const mine = new URL(req.url).searchParams.get("mine") === "1";
- const rows = (await listDeployments()).filter((d) => !d.sweepId && (!mine || d.requestedByTokenId === token.id));
- return v1Json({ count: rows.length, deployments: rows.map((d) => deploymentView(d, token)) });
- } catch (err) {
- return v1Catch(err);
- }
-});
-
-/**
- * Create a deployment (and start it unless start: false). dryRun: true only validates and returns the
- * command and estimates. Same validation and command as the UI, plus the agent guardrails.
- */
-export const POST = withToken("deployments:write", async (req, { token }) => {
- try {
- const body = AgentDeploymentBody.parse(await req.json());
- if (body.dryRun) return v1Json(await createAgentDeployment(token, body));
- const r = await act(token, "deployment.create", { type: "deployment" }, () => createAgentDeployment(token, body));
- return v1Json(
- {
- ...r,
- message:
- r.state === "pending_approval"
- ? "Created; the start waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop."
- : r.state === "starting"
- ? `Created and starting; GET /api/v1/deployments/${r.id}?wait=600 until it is running.`
- : "Created (stopped).",
- },
- 201,
- );
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/disk/route.ts b/src/app/api/v1/disk/route.ts
deleted file mode 100644
index bb3a9e2..0000000
--- a/src/app/api/v1/disk/route.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { reservedBytes } from "@/lib/agent-downloads";
-import { withToken } from "@/lib/api-tokens";
-import { size, v1Catch, v1Json } from "@/lib/api-v1";
-import { getGuardrails } from "@/lib/settings";
-import { getWorkerStatus } from "@/lib/worker-status";
-
-export const dynamic = "force-dynamic";
-
-/**
- * Space on the models folder (reported by the worker every few seconds), what open downloads
- * still need, and how much an agent request may use before hitting the minimum-free guardrail.
- */
-export const GET = withToken("models:read", async () => {
- try {
- const [w, reserved, g] = await Promise.all([getWorkerStatus(), reservedBytes(), getGuardrails()]);
- const free = w.online ? w.modelsDirFreeBytes : null;
- const total = w.online ? w.modelsDirTotalBytes : null;
- const available = free == null ? null : Math.max(0, free - reserved - g.minFreeBytes);
- return v1Json({
- workerOnline: w.online,
- freeBytes: free,
- totalBytes: total,
- usedBytes: free != null && total != null ? total - free : null,
- reservedBytes: reserved,
- minFreeBytes: g.minFreeBytes,
- availableForRequestsBytes: available,
- free: size(free),
- total: size(total),
- availableForRequests: size(available),
- });
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/downloads/route.ts b/src/app/api/v1/downloads/route.ts
deleted file mode 100644
index 69751b8..0000000
--- a/src/app/api/v1/downloads/route.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { z } from "zod";
-import { act } from "@/lib/agent-activity";
-import { requestDownload } from "@/lib/agent-downloads";
-import { withToken } from "@/lib/api-tokens";
-import { size, v1Catch, v1Json } from "@/lib/api-v1";
-import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client";
-
-export const dynamic = "force-dynamic";
-
-const Body = z
- .object({
- repoId: z.string().trim().regex(REPO_ID_RE, 'must be "org/name"'),
- sha: z.string().trim().regex(SHA_RE, "must be the full 40-character commit SHA from GET /api/v1/hub/lookup"),
- revision: z.string().trim().min(1).max(255).optional(),
- quant: z.string().trim().min(1).max(64).optional(),
- include: z.array(z.string().trim().min(1).max(1024)).min(1).max(100).optional(),
- tags: z.array(z.string()).max(20).optional(),
- })
- .strict()
- .refine((b) => !!b.quant !== !!b.include, { message: 'pass exactly one of "quant" (e.g. "Q4_K_M") or "include" (globs)' });
-
-/**
- * Request a download, within the guardrails. 201: queued or waiting for approval; 200: the same
- * repo + commit + files was requested before, nothing new was queued.
- */
-export const POST = withToken("downloads:create", async (req, { token }) => {
- try {
- const body = Body.parse(await req.json());
- const r = await act(token, "download.request", { type: "model" }, async () => {
- const out = await requestDownload(token, body);
- return { ...out, id: out.modelId };
- });
- return v1Json(
- {
- created: r.created,
- modelId: r.modelId,
- jobId: r.jobId,
- state: r.state,
- requestedBytes: r.requestedBytes,
- requestedSize: size(r.requestedBytes),
- files: r.files,
- message: r.message.replace("{jobId}", r.jobId ?? "{jobId}"),
- },
- r.created ? 201 : 200,
- );
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/hub/lookup/route.ts b/src/app/api/v1/hub/lookup/route.ts
deleted file mode 100644
index c3246ab..0000000
--- a/src/app/api/v1/hub/lookup/route.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { eq } from "drizzle-orm";
-import { quantSummary } from "@/lib/agent-selection";
-import { withToken } from "@/lib/api-tokens";
-import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1";
-import { db } from "@/lib/db/client";
-import { models } from "@/lib/db/schema";
-import { lookupRepo, normalizeRepoInput } from "@/lib/hub/lookup";
-
-export const dynamic = "force-dynamic";
-
-/** Files listed inline up to this count; more with ?files=all. */
-const FILE_LIMIT = 200;
-
-/**
- * Resolve a Hub repo (+ revision, default main) to its commit SHA, with the quants and files and
- * their sizes: what a download request needs. The same lookup the Add model dialog uses.
- */
-export const GET = withToken("models:read", async (req) => {
- try {
- const url = new URL(req.url);
- const repo = url.searchParams.get("repo")?.trim();
- if (!repo) return v1Error(400, "invalid_request", 'Pass the repo as ?repo=org/name, e.g. ?repo=unsloth/Qwen3-8B-GGUF.');
- const { repoId, revision: urlRevision } = normalizeRepoInput(repo);
- const revision = url.searchParams.get("revision")?.trim() || urlRevision || "main";
- const r = await lookupRepo(repoId, revision);
- const all = url.searchParams.get("files") === "all";
- const model = r.existingModelId
- ? await db().query.models.findFirst({ columns: { id: true, pinnedSha: true, status: true }, where: eq(models.id, r.existingModelId) })
- : null;
- return v1Json({
- repoId: r.repoId,
- revision: r.revision,
- sha: r.sha,
- gated: r.gated,
- lastModified: r.lastModified,
- inLibrary: model ? { modelId: model.id, pinnedSha: model.pinnedSha, status: model.status } : null,
- quants: quantSummary(r.files).map((q) => ({ ...q, size: size(q.bytes) })),
- fileCount: r.files.length,
- totalBytes: r.files.reduce((s, f) => s + f.size, 0),
- files: (all ? r.files : r.files.slice(0, FILE_LIMIT)).map((f) => ({ path: f.path, bytes: f.size })),
- filesTruncated: !all && r.files.length > FILE_LIMIT,
- next: 'POST /api/v1/downloads with {"repoId", "sha", "quant"} (or "include": [globs]).',
- });
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/jobs/[id]/route.ts b/src/app/api/v1/jobs/[id]/route.ts
deleted file mode 100644
index d5b51d9..0000000
--- a/src/app/api/v1/jobs/[id]/route.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { withToken } from "@/lib/api-tokens";
-import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1";
-import { getJob, listJobFiles, listJobLogs } from "@/lib/jobs";
-import { parseWait, waitFor } from "@/lib/wait";
-
-export const dynamic = "force-dynamic";
-
-const MAX_LOG = 200;
-
-const NEXT: Record = {
- pending_approval: "Waiting for the user to approve it. Don't retry or poll; tell the user and stop.",
- queued: "Waiting for a free download slot; GET with ?wait=900 instead of polling.",
- downloading: "Downloading; GET with ?wait=900 instead of polling.",
- verifying: "Checking the downloaded files.",
- completed: "Done.",
- failed: "Failed; see error. Tell the user; retrying the same request returns this job.",
- cancelled: "Cancelled or rejected by the user. Don't request it again unless the user asks.",
- interrupted: "Interrupted by a Kaname restart; the user can resume it.",
-};
-
-const SETTLED = new Set(["pending_approval", "completed", "failed", "cancelled", "interrupted"]);
-
-/**
- * Job state with per-file progress. ?wait= (max 900) blocks until it is finished or waits for
- * approval. The hf log only with ?log=N (last N lines, max 200).
- */
-export const GET = withToken>("models:read", async (req, { params }) => {
- try {
- const id = (await params).id;
- const q = new URL(req.url).searchParams;
- const { value: job, waitedS, timedOut } = await waitFor(() => getJob(id), (j) => !j || SETTLED.has(j.state), parseWait(q), { signal: req.signal });
- if (!job) return v1Error(404, "not_found", "No job with this id.");
- const n = Math.min(MAX_LOG, Math.max(0, Number(q.get("log")) || 0));
- const files = await listJobFiles(id);
- const log = n > 0 ? (await listJobLogs(id, 0, n)).map((l) => `${new Date(l.ts).toISOString()} [${l.stream}] ${l.line}`) : undefined;
- return v1Json({
- id: job.id,
- modelId: job.modelId,
- repoId: job.repoId,
- kind: job.kind,
- purpose: job.purpose,
- state: job.state,
- cancelRequested: job.cancelRequested,
- requestedBy: job.requestedBy,
- progress: {
- doneBytes: job.doneBytes,
- totalBytes: job.totalBytes,
- percent: job.totalBytes > 0 ? Math.round((job.doneBytes / job.totalBytes) * 1000) / 10 : 0,
- done: size(job.doneBytes),
- total: size(job.totalBytes),
- speedBytesPerSecond: job.speedBps,
- etaSeconds: job.etaSeconds,
- },
- error: job.errorCode || job.errorMessage ? { code: job.errorCode, message: job.errorMessage } : null,
- files: files.map((f) => ({ path: f.path, state: f.state, doneBytes: f.doneBytes, totalBytes: f.expectedBytes })),
- createdAt: new Date(job.createdAt).toISOString(),
- startedAt: job.startedAt ? new Date(job.startedAt).toISOString() : null,
- finishedAt: job.finishedAt ? new Date(job.finishedAt).toISOString() : null,
- next: NEXT[job.state] ?? null,
- ...(waitedS ? { waitedSeconds: waitedS, timedOut } : {}),
- ...(log ? { log } : {}),
- });
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/models/[id]/route.ts b/src/app/api/v1/models/[id]/route.ts
deleted file mode 100644
index 5958f62..0000000
--- a/src/app/api/v1/models/[id]/route.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { withToken } from "@/lib/api-tokens";
-import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1";
-import { listModelJobs } from "@/lib/jobs";
-import { getModel } from "@/lib/library";
-
-export const dynamic = "force-dynamic";
-
-/** One model: status, pinned commit, selected files and its latest job. */
-export const GET = withToken>("models:read", async (_req, { params }) => {
- try {
- const data = await getModel((await params).id);
- if (!data) return v1Error(404, "not_found", "No model with this id. List models with GET /api/v1/models.");
- const { model, files } = data;
- const selected = files.filter((f) => f.selected);
- const onDisk = selected.filter((f) => f.state === "present" || f.state === "verified").reduce((s, f) => s + f.size, 0);
- const [job] = await listModelJobs(model.id, 1);
- return v1Json({
- id: model.id,
- repoId: model.repoId,
- status: model.status,
- trackedRevision: model.trackedRevision,
- pinnedSha: model.pinnedSha,
- requestedBy: model.requestedBy,
- onDiskBytes: onDisk,
- onDisk: size(onDisk),
- files: selected.map((f) => ({ path: f.path, bytes: f.size, state: f.state })),
- latestJob: job ? { id: job.id, kind: job.kind, state: job.state, requestedBy: job.requestedBy } : null,
- createdAt: model.createdAt.toISOString(),
- downloadedAt: model.downloadedAt?.toISOString() ?? null,
- });
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/models/route.ts b/src/app/api/v1/models/route.ts
deleted file mode 100644
index c02fe84..0000000
--- a/src/app/api/v1/models/route.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { withToken } from "@/lib/api-tokens";
-import { parseModelFilters } from "@/lib/api-v1-filters";
-import { size, v1Catch, v1Json } from "@/lib/api-v1";
-import { listLibrary } from "@/lib/library";
-import { matchesFilters, matchesQuery, type SearchableModel } from "@/lib/search";
-
-export const dynamic = "force-dynamic";
-
-/**
- * The local library, filtered like the library page: ?q= (all terms must match) and facets
- * author, family, quant, tag, status, requested_by (repeat or comma-separate values).
- * Status values: pending, downloading, ready, incomplete, failed, deleting, pending_approval,
- * update_available, repo_missing, commit_missing.
- */
-export const GET = withToken("models:read", async (req) => {
- try {
- const { query, filters } = parseModelFilters(new URL(req.url).searchParams);
- const rows = await listLibrary();
- const out = rows
- .filter((r) => {
- const m: SearchableModel = {
- repoId: r.repoId,
- author: r.author,
- families: r.families,
- baseModels: r.baseModels,
- architecture: r.architecture,
- quants: r.quants,
- tags: r.tags.map((t) => t.name),
- hubTags: r.hubTags,
- pipelineTag: r.pipelineTag,
- license: r.license,
- status: r.status,
- hubStatus: r.hubState && r.hubState !== "available" ? r.hubState : r.updateAvailable ? "update_available" : null,
- requestedBy: r.requestedBy,
- pendingApproval: r.pendingApproval,
- };
- return matchesQuery(m, query) && matchesFilters(m, filters);
- })
- .map((r) => ({
- id: r.id,
- repoId: r.repoId,
- status: r.status,
- pendingApproval: r.pendingApproval,
- pinnedSha: r.pinnedSha,
- quants: r.quants,
- tags: r.tags.map((t) => t.name),
- selectedFiles: r.fileCount,
- selectedBytes: r.totalBytes,
- onDiskBytes: r.presentBytes,
- onDisk: size(r.presentBytes),
- updateAvailable: r.updateAvailable,
- hubState: r.hubState,
- requestedBy: r.requestedBy,
- createdAt: r.createdAt.toISOString(),
- downloadedAt: r.downloadedAt?.toISOString() ?? null,
- }));
- return v1Json({ count: out.length, models: out });
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/route.ts b/src/app/api/v1/route.ts
deleted file mode 100644
index 55eda71..0000000
--- a/src/app/api/v1/route.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { withToken } from "@/lib/api-tokens";
-import { size, v1Json } from "@/lib/api-v1";
-import { getGuardrails, getTuning } from "@/lib/settings";
-
-export const dynamic = "force-dynamic";
-
-/** Who am I, what may I do, and within which limits. Any valid token. */
-export const GET = withToken(null, async (_req, { token }) => {
- const [g, t] = await Promise.all([getGuardrails(), getTuning()]);
- return v1Json({
- token: { name: token.name, scopes: token.scopes },
- guardrails: {
- approvalMode: g.approvalMode,
- maxRequestBytes: g.maxRequestBytes,
- maxRequestSize: size(g.maxRequestBytes),
- minFreeBytes: g.minFreeBytes,
- minFreeSize: size(g.minFreeBytes),
- maxOpenAgentJobs: g.maxOpenJobs,
- allowedAuthors: g.allowedAuthors,
- },
- deploymentGuardrails: {
- approvalMode: t.approvalMode,
- maxAgentDeployments: t.maxAgentDeployments,
- oneRunAtATime: true,
- maxRunMinutes: t.maxRunMinutes,
- maxSweepMinutes: t.maxSweepMinutes,
- maxSweepVariants: t.maxSweepVariants,
- allowedRuntimeIds: t.allowedRuntimeIds,
- hostPortRange: t.hostPortRange,
- maxMemoryMb: t.maxMemoryMb,
- maxCpus: t.maxCpus,
- ownDeploymentsOnly: true,
- protectedDeploymentsUntouchable: true,
- },
- endpoints: [
- "GET /api/v1/hub/lookup?repo=org/name[&revision=main][&files=all]",
- "GET /api/v1/models[?q=&author=&family=&quant=&tag=&status=&requested_by=]",
- "GET /api/v1/models/{id}",
- "POST /api/v1/downloads {repoId, sha, quant | include[], tags?, revision?}",
- "GET /api/v1/jobs/{id}[?wait=900][&log=50]",
- "GET /api/v1/disk",
- "GET /api/v1/runtimes",
- "GET /api/v1/deployments[?mine=1]",
- "POST /api/v1/deployments {runtimeId, modelId, options, cpus?, memoryMb?, hostPort?, name?, start?, dryRun?}",
- "GET /api/v1/deployments/{id}[?wait=600][&log=50]",
- "PATCH /api/v1/deployments/{id} {options?, cpus?, memoryMb?, hostPort?, name?}",
- "POST /api/v1/deployments/{id}/start | /stop",
- "DELETE /api/v1/deployments/{id}",
- "GET /api/v1/benchmarks[?deployment=&requested_by=&limit=]",
- "POST /api/v1/benchmarks {kind: run|ab, deploymentId, deploymentBId?, quick?, passes?, phases?, label?, description?}",
- "GET /api/v1/benchmarks/{id}[?wait=900][&full=1]",
- "POST /api/v1/benchmarks/{id}/cancel",
- "GET /api/v1/benchmarks/compare?ids=a,b",
- "POST /api/v1/sweeps {baseDeploymentId, params: [{key, values}], quick?, passes?, phases?, label?}",
- "GET /api/v1/sweeps/{id}[?wait=900]",
- "POST /api/v1/sweeps/{id}/cancel",
- ],
- });
-});
diff --git a/src/app/api/v1/runtimes/route.ts b/src/app/api/v1/runtimes/route.ts
deleted file mode 100644
index 4f086c8..0000000
--- a/src/app/api/v1/runtimes/route.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { withToken } from "@/lib/api-tokens";
-import { v1Catch, v1Json } from "@/lib/api-v1";
-import { effectiveHardware } from "@/lib/benchmark-snapshot";
-import { listRuntimes } from "@/lib/runtimes";
-import { getTuning } from "@/lib/settings";
-
-export const dynamic = "force-dynamic";
-
-/** Runtimes with a pulled image, what they serve, whether agents may use them; plus the host's GPUs. */
-export const GET = withToken("deployments:read", async () => {
- try {
- const [rts, g, { hardware }] = await Promise.all([listRuntimes(), getTuning(), effectiveHardware()]);
- return v1Json({
- runtimes: rts
- .filter((r) => r.imageState === "present")
- .map((r) => ({
- id: r.id,
- name: r.name,
- engine: r.engine,
- engineName: r.engineName ?? r.engine,
- accelerator: r.accelerator,
- image: r.image,
- digest: r.imageDigest,
- serves: r.engine === "llama.cpp" ? "GGUF files (options.modelFile = the .gguf path)" : 'safetensors repos (options.modelFile = "")',
- allowed: g.allowedRuntimeIds.length === 0 || g.allowedRuntimeIds.includes(r.id),
- allowedExtraArgs: g.allowedArgs[r.engine],
- })),
- gpus: (hardware?.gpus ?? []).map((x) => ({ vendor: x.vendor, name: x.name, vramMb: x.vramMb })),
- });
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/sweeps/[id]/cancel/route.ts b/src/app/api/v1/sweeps/[id]/cancel/route.ts
deleted file mode 100644
index 2714018..0000000
--- a/src/app/api/v1/sweeps/[id]/cancel/route.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { act } from "@/lib/agent-activity";
-import { ownSweep } from "@/lib/agent-runs";
-import { withToken } from "@/lib/api-tokens";
-import { v1Catch, v1Json } from "@/lib/api-v1";
-import { cancelSweep } from "@/lib/sweeps";
-
-/** Cancel a sweep this token started (its current variant's deployment is removed). */
-export const POST = withToken>("benchmarks:run", async (_req, { params, token }) => {
- try {
- const id = (await params).id;
- await act(token, "sweep.cancel", { type: "sweep", id }, async () => {
- await ownSweep(token, id);
- await cancelSweep(id);
- return { id };
- });
- return v1Json({ id, cancelled: true });
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/sweeps/[id]/route.ts b/src/app/api/v1/sweeps/[id]/route.ts
deleted file mode 100644
index 0363568..0000000
--- a/src/app/api/v1/sweeps/[id]/route.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { runSettled, sweepView } from "@/lib/agent-runs";
-import { withToken } from "@/lib/api-tokens";
-import { v1Catch, v1Error, v1Json } from "@/lib/api-v1";
-import { getSweep } from "@/lib/sweeps";
-import { parseWait, waitFor } from "@/lib/wait";
-
-export const dynamic = "force-dynamic";
-
-/** A sweep with each variant's headline numbers and setup. ?wait= (max 900) blocks until it is finished or waits for approval. */
-export const GET = withToken>("benchmarks:read", async (req, { params, token }) => {
- try {
- const id = (await params).id;
- const { value, waitedS, timedOut } = await waitFor(() => getSweep(id), (s) => !s || runSettled(s.sweep.state), parseWait(new URL(req.url).searchParams), { signal: req.signal });
- if (!value) return v1Error(404, "not_found", "No sweep with this id.");
- return v1Json({ ...sweepView(value, token), ...(waitedS ? { waitedSeconds: waitedS, timedOut } : {}) });
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/app/api/v1/sweeps/route.ts b/src/app/api/v1/sweeps/route.ts
deleted file mode 100644
index e31e741..0000000
--- a/src/app/api/v1/sweeps/route.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { act } from "@/lib/agent-activity";
-import { AgentSweepBody, requestSweep } from "@/lib/agent-runs";
-import { withToken } from "@/lib/api-tokens";
-import { v1Catch, v1Json } from "@/lib/api-v1";
-
-export const dynamic = "force-dynamic";
-
-/**
- * Queue a sweep: one or two settings varied from the token's own base deployment. Each variant is
- * deployed, benchmarked and removed again, one after another.
- */
-export const POST = withToken("benchmarks:run", async (req, { token }) => {
- try {
- const body = AgentSweepBody.parse(await req.json());
- const r = await act(token, "sweep.create", { type: "sweep" }, () => requestSweep(token, body));
- return v1Json(
- {
- ...r,
- message:
- r.state === "pending_approval"
- ? "Requested; it waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop."
- : `Queued (${r.variants} variants, stopped after ${r.timeLimitMinutes} min); GET /api/v1/sweeps/${r.id}?wait=900 for progress.`,
- },
- 201,
- );
- } catch (err) {
- return v1Catch(err);
- }
-});
diff --git a/src/components/app-nav.tsx b/src/components/app-nav.tsx
index 5f6b277..88efe35 100644
--- a/src/components/app-nav.tsx
+++ b/src/components/app-nav.tsx
@@ -1,6 +1,6 @@
"use client";
-import { GaugeIcon, LibraryIcon, RocketIcon, SettingsIcon } from "lucide-react";
+import { GaugeIcon, LibraryIcon, ServerIcon, SettingsIcon } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
@@ -10,9 +10,9 @@ const LINKS = [
href: "/",
label: "Library",
icon: LibraryIcon,
- active: (p: string) => !["/settings", "/deployments", "/benchmarks"].some((x) => p.startsWith(x)),
+ active: (p: string) => !["/settings", "/endpoints", "/benchmarks"].some((x) => p.startsWith(x)),
},
- { href: "/deployments", label: "Deployments", icon: RocketIcon, active: (p: string) => p.startsWith("/deployments") },
+ { href: "/endpoints", label: "Endpoints", icon: ServerIcon, active: (p: string) => p.startsWith("/endpoints") },
{ href: "/benchmarks", label: "Benchmarks", icon: GaugeIcon, active: (p: string) => p.startsWith("/benchmarks") },
{ href: "/settings", label: "Settings", icon: SettingsIcon, active: (p: string) => p.startsWith("/settings") },
];
diff --git a/src/components/approval-bar.tsx b/src/components/approval-bar.tsx
deleted file mode 100644
index 1c654f0..0000000
--- a/src/components/approval-bar.tsx
+++ /dev/null
@@ -1,100 +0,0 @@
-"use client";
-
-import { BotIcon, CheckIcon, XIcon } from "lucide-react";
-import { useRouter } from "next/navigation";
-import { useState } from "react";
-import { approveJob, rejectJob } from "@/components/job-actions";
-import { Button } from "@/components/ui/button";
-import { toast } from "sonner";
-import { formatBytes } from "@/lib/format";
-
-/** A download requested through the API that waits for approval: who asked, how much, approve/reject. */
-export function ApprovalBar({ job, onRemoved }: { job: { id: string; requestedBy: string | null; totalBytes: number; purpose: string | null }; onRemoved?: () => void }) {
- const router = useRouter();
- const [busy, setBusy] = useState(false);
-
- async function run(fn: () => Promise) {
- setBusy(true);
- try {
- await fn();
- router.refresh();
- } finally {
- setBusy(false);
- }
- }
-
- return (
-
-
-
-
- {job.requestedBy ?? "An API token"} asks to download {formatBytes(job.totalBytes)}
- {job.purpose === "add" ? " of additional files" : ""}. It starts once you approve it.
-
-
-
- run(() => approveJob(job.id))}>
-
- Approve
-
-
- run(async () => {
- const r = await rejectJob(job.id);
- if (r?.removedModel) onRemoved?.();
- })
- }
- >
-
- Reject
-
-
-
- );
-}
-
-/** Something else an API token asked for (a deployment start, a run, a sweep): approve or reject. */
-export function AgentApprovalBar({ requestedBy, what, base }: { requestedBy: string | null; what: string; base: string }) {
- const router = useRouter();
- const [busy, setBusy] = useState(false);
-
- async function decide(kind: "approve" | "reject") {
- setBusy(true);
- try {
- const res = await fetch(`${base}/${kind}`, { method: "POST" });
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
- toast.error(body.error?.message ?? `Request failed (${res.status})`);
- return;
- }
- toast.success(kind === "approve" ? "Approved" : "Rejected");
- router.refresh();
- } finally {
- setBusy(false);
- }
- }
-
- return (
-
-
-
-
- {requestedBy ?? "An API token"} asks to {what}. It goes ahead once you approve it.
-
-
-
- decide("approve")}>
-
- Approve
-
- decide("reject")}>
-
- Reject
-
-
-
- );
-}
diff --git a/src/components/args-editor.tsx b/src/components/args-editor.tsx
deleted file mode 100644
index 09b1dd9..0000000
--- a/src/components/args-editor.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-"use client";
-
-import { PlusIcon, XIcon } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import type { ArgRow } from "@/lib/extra-args";
-
-const GENERIC = { flag: "--flag", value: "value (optional)" };
-
-/** Extra command-line arguments as flag/value rows (controlled). `placeholder` is the first row's example. */
-export function ArgsEditor({
- rows,
- onChange,
- placeholder = GENERIC,
- addLabel = "Add argument",
-}: {
- rows: ArgRow[];
- onChange: (rows: ArgRow[]) => void;
- placeholder?: { flag: string; value: string };
- addLabel?: string;
-}) {
- const set = (i: number, patch: Partial) => onChange(rows.map((r, j) => (j === i ? { ...r, ...patch } : r)));
- const single = (s: string) => s.replace(/[\r\n]/g, "");
-
- return (
-
- );
-}
diff --git a/src/components/benchmark-resources.tsx b/src/components/benchmark-resources.tsx
deleted file mode 100644
index 71e4297..0000000
--- a/src/components/benchmark-resources.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import type { ResourceStats } from "@/lib/db/schema";
-import { formatBytes } from "@/lib/format";
-
-const cores = (v: number | null) => (v == null ? "—" : v.toFixed(v >= 10 ? 0 : 1));
-const mib = (v: number | null | undefined) => (v == null ? "—" : formatBytes(v * 2 ** 20));
-const round = (v: number | null | undefined, unit: string) => (v == null ? "—" : `${Math.round(v)}${unit}`);
-
-function Cell({ label, value, note }: { label: string; value: string; note?: string }) {
- return (
-
- {label}
- {value}
- {note && {note} }
-
- );
-}
-
-/** Resource use sampled during a run: per deployment (A/B: both sides) and per GPU. */
-export function BenchmarkResources({ stats, names }: { stats: ResourceStats; names?: { a: string; b?: string } }) {
- if (stats.samples === 0 && stats.gpus.length === 0) return No resource samples were recorded.
;
- const multi = stats.containers.length > 1;
- return (
-
- {stats.containers.map((c) => (
-
- {multi &&
{c.side === "a" ? `A · ${names?.a ?? ""}` : `B · ${names?.b ?? ""}`} }
-
- |
- |
- {c.memPeakBytes != null && c.memLimitBytes ? (
- |
- ) : (
- |
- )}
-
-
- ))}
- {stats.gpus.map((g) => (
-
-
- GPU {g.index} · {g.name}
-
-
- |
- |
- |
- |
-
-
- ))}
-
- Sampled every ~2 s over {stats.seconds} s ({stats.samples} samples). RAM is the container's usage without page cache, like docker stats; GPU
- figures are for the whole GPU, so other work on it counts too.
-
-
- );
-}
diff --git a/src/components/deployment-state.tsx b/src/components/deployment-state.tsx
deleted file mode 100644
index efc2f7f..0000000
--- a/src/components/deployment-state.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { LoaderCircleIcon } from "lucide-react";
-import { cn } from "@/lib/utils";
-
-const STYLE: Record = {
- stopped: { label: "stopped", className: "border-foreground/15 text-muted-foreground" },
- starting: { label: "starting", className: "border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300" },
- running: { label: "running", className: "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300" },
- stopping: { label: "stopping", className: "border-foreground/15 text-muted-foreground" },
- failed: { label: "failed", className: "border-destructive/30 bg-destructive/10 text-destructive" },
-};
-
-/** Deployment state; shows "starting" as soon as a start was requested. */
-export function DeploymentStateBadge({ state, desiredState, className }: { state: string; desiredState: string; className?: string }) {
- const effective = desiredState === "running" && (state === "stopped" || state === "failed") ? "starting" : desiredState === "stopped" && (state === "running" || state === "starting") ? "stopping" : state;
- const s = STYLE[effective] ?? STYLE.stopped;
- return (
-
- {(effective === "starting" || effective === "stopping") && }
- {effective === "running" && }
- {s.label}
-
- );
-}
diff --git a/src/components/requested-by-badge.tsx b/src/components/requested-by-badge.tsx
deleted file mode 100644
index 674bcf2..0000000
--- a/src/components/requested-by-badge.tsx
+++ /dev/null
@@ -1,14 +0,0 @@
-import { BotIcon } from "lucide-react";
-import { Badge } from "@/components/ui/badge";
-import { cn } from "@/lib/utils";
-
-/** "requested by hermes": added or downloaded through the API with that token. */
-export function RequestedByBadge({ name, className }: { name: string | null | undefined; className?: string }) {
- if (!name) return null;
- return (
-
-
- {name}
-
- );
-}
diff --git a/src/components/user-menu.tsx b/src/components/user-menu.tsx
index 0ccbc88..5f12bf3 100644
--- a/src/components/user-menu.tsx
+++ b/src/components/user-menu.tsx
@@ -1,6 +1,6 @@
"use client";
-import { BotIcon, BoxesIcon, CpuIcon, KeyRoundIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
+import { DownloadIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
import Link from "next/link";
import { useTheme } from "next-themes";
import { useTransition } from "react";
@@ -67,21 +67,9 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
Tags
- }>
-
- Runtimes
-
- }>
-
- Hardware
-
- }>
-
- Runtime API keys
-
- }>
-
- API tokens
+ }>
+
+ Downloads
diff --git a/src/lib/agent-activity.ts b/src/lib/agent-activity.ts
deleted file mode 100644
index 5c6655e..0000000
--- a/src/lib/agent-activity.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import "server-only";
-import { desc, eq } from "drizzle-orm";
-import type { TokenIdentity } from "@/lib/api-tokens";
-import { db } from "@/lib/db/client";
-import { agentActivity } from "@/lib/db/schema";
-
-export type ActivityOutcome = "ok" | "pending_approval" | "refused";
-
-/** Record what a token did (or was refused); never fails the request it belongs to. */
-export async function logActivity(
- token: TokenIdentity,
- action: string,
- x: { targetType?: string; targetId?: string | null; outcome: ActivityOutcome; code?: string | null; message?: string | null },
-): Promise {
- try {
- await db()
- .insert(agentActivity)
- .values({
- tokenId: token.id,
- tokenName: token.name,
- action,
- targetType: x.targetType ?? null,
- targetId: x.targetId ?? null,
- outcome: x.outcome,
- code: x.code ?? null,
- message: x.message?.slice(0, 500) ?? null,
- });
- } catch (err) {
- console.error("[agent-activity]", err);
- }
-}
-
-export type ActivityRow = typeof agentActivity.$inferSelect;
-
-export async function listActivity(tokenId: string, limit = 100): Promise {
- return db().select().from(agentActivity).where(eq(agentActivity.tokenId, tokenId)).orderBy(desc(agentActivity.createdAt)).limit(limit);
-}
-
-/** An error with a code and an HTTP status below 500: a refusal the agent caused, worth logging. */
-function refusal(err: unknown): { code: string; message: string } | null {
- const e = err as { code?: unknown; status?: unknown; message?: unknown };
- if (typeof e?.code === "string" && typeof e.status === "number" && e.status < 500) return { code: e.code, message: String(e.message ?? "") };
- if (err instanceof Error && err.name === "ZodError") return { code: "invalid_request", message: err.message.slice(0, 300) };
- return null;
-}
-
-/**
- * Run an agent action and record it: ok, pending approval (when the result's state says so) or
- * refused with the error code. The error is rethrown for the route to answer.
- */
-export async function act(token: TokenIdentity, action: string, target: { type: string; id?: string | null }, fn: () => Promise): Promise {
- try {
- const r = await fn();
- const { id, state } = r as { id?: unknown; state?: unknown };
- await logActivity(token, action, {
- targetType: target.type,
- targetId: target.id ?? (typeof id === "string" ? id : null),
- outcome: state === "pending_approval" ? "pending_approval" : "ok",
- });
- return r;
- } catch (err) {
- const why = refusal(err);
- if (why) await logActivity(token, action, { targetType: target.type, targetId: target.id ?? null, outcome: "refused", code: why.code, message: why.message });
- throw err;
- }
-}
diff --git a/src/lib/agent-deployments.ts b/src/lib/agent-deployments.ts
deleted file mode 100644
index 4e9c39d..0000000
--- a/src/lib/agent-deployments.ts
+++ /dev/null
@@ -1,293 +0,0 @@
-import "server-only";
-import { and, eq, inArray, isNotNull, isNull, ne, or, sql } from "drizzle-orm";
-import { z } from "zod";
-import { checkArgs, checkHostPort, checkLimits, checkStart, checkVram, type GpuLoad, TuningError, type TuningGuardrails } from "@/lib/agent-tuning";
-import type { TokenIdentity } from "@/lib/api-tokens";
-import { effectiveHardware } from "@/lib/benchmark-snapshot";
-import { db } from "@/lib/db/client";
-import { benchmarkRuns, benchmarkSweeps, type DeploymentOptions, deployments, models, type RuntimeAccelerator, runtimes } from "@/lib/db/schema";
-import { API_KEY_PLACEHOLDER, buildCommand, ENGINE_PORT, estimateMemoryMb, estimateVramMb, renderCommand } from "@/lib/deploy-command";
-import {
- createDeployment,
- DeploymentBody,
- DeploymentError,
- type DeploymentInput,
- type DeploymentRow,
- deploymentFileBytes,
- getDeployment,
- requestDelete,
- setDesiredState,
- updateDeployment,
- validateDeployment,
-} from "@/lib/deployments";
-import { getDockerInfo } from "@/lib/runtimes";
-import { getTuning } from "@/lib/settings";
-
-// Deployments through the API: the same validation, estimates and command as the UI, plus the agent
-// guardrails (runtime allowlist, argument allowlist, ports, caps, one GPU job at a time, protected
-// deployments, approval). Agents only change deployments their own token created.
-
-const RUN_OPEN = ["pending_approval", "queued", "running"] as const;
-
-/** Stored (already validated) options as request input; they're validated again on the way in. */
-const asInput = (o: DeploymentOptions) => o as DeploymentInput["options"];
-
-export const AgentDeploymentBody = z
- .object({
- name: z.string().trim().min(1).max(80).optional(),
- runtimeId: z.string().min(1),
- modelId: z.string().min(1),
- options: DeploymentBody.shape.options.strict(),
- cpus: z.number().min(0.1).max(1024).nullable().optional(),
- memoryMb: z.number().int().min(256).max(4_194_304).nullable().optional(),
- hostPort: z.number().int().min(1024).max(65_535).nullable().optional(),
- /** Start right away (default); with approval mode "approve" the start waits for the user. */
- start: z.boolean().default(true),
- /** Only validate and return the command and estimates; nothing is created. */
- dryRun: z.boolean().default(false),
- })
- .strict();
-export type AgentDeploymentInput = z.infer;
-
-export const AgentDeploymentPatch = z
- .object({
- name: z.string().trim().min(1).max(80).optional(),
- options: DeploymentBody.shape.options.partial().strict().optional(),
- cpus: z.number().min(0.1).max(1024).nullable().optional(),
- memoryMb: z.number().int().min(256).max(4_194_304).nullable().optional(),
- hostPort: z.number().int().min(1024).max(65_535).nullable().optional(),
- })
- .strict();
-
-/** Agent deployments, runs and sweeps that keep the GPU busy right now (all tokens). */
-export async function gpuLoad(selfId?: string): Promise {
- const notSelf = selfId ? ne(deployments.id, selfId) : undefined;
- const agentDep = and(isNotNull(deployments.requestedByTokenId), isNull(deployments.deleteRequestedAt), notSelf);
- const [[dep], [starting], [runs], [sweeps]] = await Promise.all([
- db()
- .select({ n: sql`count(*)` })
- .from(deployments)
- .where(and(agentDep, or(eq(deployments.desiredState, "running"), isNotNull(deployments.startRequestedAt), inArray(deployments.state, ["starting", "running"])))),
- db()
- .select({ n: sql`count(*)` })
- .from(deployments)
- .where(and(agentDep, eq(deployments.state, "starting"))),
- db()
- .select({ n: sql`count(*)` })
- .from(benchmarkRuns)
- .where(and(isNotNull(benchmarkRuns.requestedByTokenId), inArray(benchmarkRuns.state, [...RUN_OPEN]))),
- db()
- .select({ n: sql`count(*)` })
- .from(benchmarkSweeps)
- .where(and(isNotNull(benchmarkSweeps.requestedByTokenId), inArray(benchmarkSweeps.state, [...RUN_OPEN]))),
- ]);
- return { agentDeployments: Number(dep.n), agentStarting: Number(starting.n), agentRuns: Number(runs.n) + Number(sweeps.n) };
-}
-
-type Pool = { accelerator: RuntimeAccelerator; gpus: string[] | null };
-const sharesGpus = (a: Pool, b: Pool) =>
- a.accelerator !== "cpu" &&
- b.accelerator !== "cpu" &&
- (a.accelerator === "nvidia") === (b.accelerator === "nvidia") &&
- (a.accelerator !== "nvidia" || !a.gpus?.length || !b.gpus?.length || a.gpus.some((g) => b.gpus!.includes(g)));
-
-/** VRAM of the GPUs a deployment gets (NVIDIA: the picked ones or all; /dev/dri: Intel and AMD). */
-async function poolVramMb(pool: Pool): Promise {
- const { hardware, nvidia } = await effectiveHardware();
- if (pool.accelerator === "nvidia") {
- const gs = pool.gpus?.length ? nvidia.filter((g) => pool.gpus!.includes(g.uuid)) : nvidia;
- return gs.length ? gs.reduce((s, g) => s + g.memoryMb, 0) : null;
- }
- const gs = (hardware?.gpus ?? []).filter((g) => (pool.accelerator === "rocm" ? g.vendor === "amd" : g.vendor !== "nvidia"));
- return gs.length && gs.every((g) => g.vramMb) ? gs.reduce((s, g) => s + (g.vramMb ?? 0), 0) : null;
-}
-
-/** Estimated VRAM (null: can't tell) of a deployment's options. */
-async function vramOf(modelId: string, engine: "llama.cpp" | "vllm", options: DeploymentOptions, totalMb: number | null) {
- return estimateVramMb(await deploymentFileBytes(modelId, options, engine), options.contextSize, engine, options, totalMb);
-}
-
-/** Refuse a start that would crowd a running protected deployment on the same GPUs out of VRAM. */
-async function checkProtectedVram(self: { id?: string; modelId: string; engine: "llama.cpp" | "vllm"; accelerator: RuntimeAccelerator; options: DeploymentOptions }) {
- if (self.accelerator === "cpu") return;
- const pool: Pool = { accelerator: self.accelerator, gpus: self.options.gpus ?? null };
- const running = (
- await db()
- .select({ id: deployments.id, name: deployments.name, protected: deployments.protected, modelId: deployments.modelId, options: deployments.options, engine: runtimes.engine, accelerator: runtimes.accelerator })
- .from(deployments)
- .innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
- .where(and(isNull(deployments.deleteRequestedAt), inArray(deployments.state, ["starting", "running"]), self.id ? ne(deployments.id, self.id) : undefined))
- ).filter((d) => sharesGpus(pool, { accelerator: d.accelerator, gpus: d.options.gpus ?? null }));
- const protectedNames = running.filter((d) => d.protected).map((d) => d.name);
- if (protectedNames.length === 0) return;
- const totalMb = await poolVramMb(pool);
- checkVram({
- protectedNames,
- newMb: await vramOf(self.modelId, self.engine, self.options, totalMb),
- runningMb: await Promise.all(running.map(async (d) => (await vramOf(d.modelId, d.engine, d.options, totalMb)) ?? -1)),
- totalMb,
- });
-}
-
-async function runtimeFor(g: TuningGuardrails, runtimeId: string) {
- const rt = await db().query.runtimes.findFirst({ where: eq(runtimes.id, runtimeId) });
- if (!rt) throw new DeploymentError("not_found", "Runtime not found. List them with GET /api/v1/runtimes.", 404);
- if (g.allowedRuntimeIds.length && !g.allowedRuntimeIds.includes(rt.id)) {
- throw new TuningError("runtime_not_allowed", `runtime "${rt.name}" isn't on the agents' allowlist. Pick one from GET /api/v1/runtimes with "allowed": true.`, 403);
- }
- if (rt.imageState !== "present") throw new TuningError("runtime_not_pulled", `runtime "${rt.name}" has no pulled image; ask the user to pull it in Settings → Runtimes.`, 409);
- return rt;
-}
-
-/** The checked deployment: validated options, memory limit, estimates and the command it would run. */
-async function prepare(g: TuningGuardrails, input: { name: string; runtimeId: string; modelId: string; options: z.infer["options"]; cpus?: number | null; memoryMb?: number | null; hostPort?: number | null }, selfId?: string) {
- const rt = await runtimeFor(g, input.runtimeId);
- checkArgs(g, rt.engine, input.options.extraArgs);
- checkHostPort(g, input.hostPort);
- const options = await validateDeployment({ ...input, cpus: input.cpus ?? null, memoryMb: input.memoryMb ?? null, hostPort: input.hostPort ?? null }, selfId);
- const model = await db().query.models.findFirst({ columns: { repoId: true, localPath: true }, where: eq(models.id, input.modelId) });
- const fileBytes = await deploymentFileBytes(input.modelId, options, rt.engine);
- const docker = await getDockerInfo();
- const estimateMb = estimateMemoryMb(fileBytes, options.contextSize, rt.engine, { ...options, accelerator: rt.accelerator });
- const { memoryMb, cpus } = checkLimits(g, { memoryMb: input.memoryMb, cpus: input.cpus, estimateMb, hostMemoryMb: docker?.memoryBytes ? docker.memoryBytes / 2 ** 20 : null, hostCpus: docker?.cpus ?? null });
- const totalVram = rt.accelerator === "cpu" ? null : await poolVramMb({ accelerator: rt.accelerator, gpus: options.gpus ?? null });
- const vramMb = rt.accelerator === "cpu" ? null : estimateVramMb(fileBytes, options.contextSize, rt.engine, options, totalVram);
- const cmd = buildCommand({
- engine: rt.engine,
- options,
- model: { repoId: model?.repoId ?? "", localPath: model?.localPath ?? "" },
- runtime: rt,
- apiKeys: options.requireApiKey ? [API_KEY_PLACEHOLDER] : [],
- });
- return {
- rt,
- options,
- memoryMb,
- cpus,
- preview: {
- command: renderCommand(rt.image, cmd),
- estimates: { memoryMb: estimateMb, vramMb, gpuVramMb: totalVram },
- limits: { memoryMb, cpus },
- },
- };
-}
-
-/** Create (and by default start) a deployment for a token. */
-export async function createAgentDeployment(token: TokenIdentity, body: AgentDeploymentInput, g?: TuningGuardrails) {
- const guard = g ?? (await getTuning());
- const name = body.name ?? `${token.name} ${new Date().toISOString().slice(0, 16).replace("T", " ")}`;
- const p = await prepare(guard, { ...body, name });
- if (body.start) {
- checkStart(guard, await gpuLoad());
- await checkProtectedVram({ modelId: body.modelId, engine: p.rt.engine, accelerator: p.rt.accelerator, options: p.options });
- }
- if (body.dryRun) return { dryRun: true as const, created: false, id: null, state: "dry_run", ...p.preview };
- const pending = body.start && guard.approvalMode === "approve";
- const { id } = await createDeployment(
- { name, runtimeId: body.runtimeId, modelId: body.modelId, options: asInput(p.options), cpus: p.cpus, memoryMb: p.memoryMb, hostPort: body.hostPort ?? null },
- body.start,
- { requestedBy: { tokenId: token.id, name: token.name }, startPendingApproval: pending },
- );
- return { dryRun: false as const, created: true, id, state: pending ? "pending_approval" : body.start ? "starting" : "stopped", ...p.preview };
-}
-
-/** A deployment this token may change: its own, and not protected. */
-async function ownDeployment(token: TokenIdentity, id: string): Promise {
- const d = await getDeployment(id);
- if (!d) throw new DeploymentError("not_found", "No deployment with this id.", 404);
- if (d.protected) throw new TuningError("protected", `"${d.name}" is protected; agents can't change, stop, delete or benchmark it.`, 403);
- if (d.requestedByTokenId !== token.id) throw new TuningError("not_owner", `"${d.name}" wasn't created by this token; agents only change their own deployments.`, 403);
- return d;
-}
-
-/** Change an own, stopped deployment's launch options (fields left out stay). */
-export async function updateAgentDeployment(token: TokenIdentity, id: string, patch: z.infer) {
- const guard = await getTuning();
- const d = await ownDeployment(token, id);
- if (d.state !== "stopped" && d.state !== "failed") throw new DeploymentError("busy", "Stop the deployment first (POST …/stop), then change it.", 409);
- const input = {
- name: patch.name ?? d.name,
- runtimeId: d.runtimeId,
- modelId: d.modelId,
- options: asInput({ ...d.options, ...patch.options }),
- cpus: patch.cpus !== undefined ? patch.cpus : d.cpus,
- memoryMb: patch.memoryMb !== undefined ? patch.memoryMb : d.memoryMb,
- hostPort: patch.hostPort !== undefined ? patch.hostPort : d.hostPort,
- };
- // The memory limit follows the options unless the agent sets one: re-estimate when it was implicit.
- const p = await prepare(guard, { ...input, memoryMb: patch.memoryMb !== undefined ? patch.memoryMb : patch.options ? null : d.memoryMb }, id);
- await updateDeployment(id, { ...input, options: asInput(p.options), memoryMb: p.memoryMb, cpus: p.cpus });
- return p.preview;
-}
-
-/** Start an own deployment (waits for approval in mode "approve"). */
-export async function startAgentDeployment(token: TokenIdentity, id: string): Promise<{ state: string }> {
- const guard = await getTuning();
- const d = await ownDeployment(token, id);
- if (d.desiredState === "running") return { state: d.state };
- if (d.startRequestedAt) return { state: "pending_approval" };
- await runtimeFor(guard, d.runtimeId);
- checkStart(guard, await gpuLoad(id));
- await checkProtectedVram({ id, modelId: d.modelId, engine: d.engine, accelerator: d.accelerator, options: d.options });
- if (guard.approvalMode === "approve") {
- await db().update(deployments).set({ startRequestedAt: new Date() }).where(eq(deployments.id, id));
- return { state: "pending_approval" };
- }
- await setDesiredState(id, "running");
- return { state: "starting" };
-}
-
-export async function stopAgentDeployment(token: TokenIdentity, id: string): Promise {
- await ownDeployment(token, id);
- await setDesiredState(id, "stopped");
-}
-
-export async function deleteAgentDeployment(token: TokenIdentity, id: string): Promise {
- await ownDeployment(token, id);
- await requestDelete(id);
-}
-
-/** Compact deployment state for agents; the log only on request. */
-export function deploymentView(d: DeploymentRow, token: TokenIdentity) {
- const port = ENGINE_PORT[d.engine];
- const pending = !!d.startRequestedAt;
- const state = pending ? "pending_approval" : d.state;
- return {
- id: d.id,
- name: d.name,
- state,
- desiredState: d.desiredState,
- protected: d.protected,
- requestedBy: d.requestedBy,
- mine: d.requestedByTokenId === token.id,
- runtime: { id: d.runtimeId, name: d.runtimeName, engine: d.engine, accelerator: d.accelerator, image: d.runtimeImage },
- model: { id: d.modelId, repoId: d.repoId },
- options: d.options,
- limits: { cpus: d.cpus, memoryMb: d.memoryMb },
- hostPort: d.hostPort,
- endpoint: d.state === "running" && d.containerName ? `http://${d.containerName}:${port}/v1` : null,
- engine: d.engineInfo ? { version: d.engineInfo.version, slots: d.engineInfo.slots, contextSize: d.engineInfo.contextSize } : null,
- usage: d.stats ? { cpuPercent: Math.round(d.stats.cpuPercent), memoryBytes: d.stats.memoryBytes, memoryLimitBytes: d.stats.memoryLimitBytes, at: d.stats.at } : null,
- error: d.error,
- startedAt: d.startedAt?.toISOString() ?? null,
- readyAt: d.readyAt?.toISOString() ?? null,
- next: deploymentNext(state, d.desiredState),
- };
-}
-
-function deploymentNext(state: string, desired: string): string {
- if (state === "pending_approval") return "The start waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop.";
- if (state === "starting" || (desired === "running" && state === "stopped")) return "Starting (loading the model); GET this deployment with ?wait=600 instead of polling.";
- if (state === "running") return "Ready: benchmark it with POST /api/v1/benchmarks.";
- if (state === "failed") return "Failed to start; see error (and ?log=50). Change the options (PATCH) and start again, or tell the user.";
- if (state === "stopping") return "Stopping.";
- return "Stopped.";
-}
-
-/** Settled for ?wait=: not on the way between states. */
-export function deploymentSettled(v: { state: string; desiredState: string }): boolean {
- if (v.state === "starting" || v.state === "stopping") return false;
- if (v.desiredState === "running" && v.state === "stopped") return false;
- if (v.desiredState === "stopped" && v.state === "running") return false;
- return true;
-}
diff --git a/src/lib/agent-downloads.ts b/src/lib/agent-downloads.ts
deleted file mode 100644
index ed52fe3..0000000
--- a/src/lib/agent-downloads.ts
+++ /dev/null
@@ -1,180 +0,0 @@
-import "server-only";
-import { and, eq, inArray, isNotNull, ne, sql } from "drizzle-orm";
-import { checkAuthor, checkGuardrails, type Guardrails } from "@/lib/agent-guardrails";
-import { newPaths, resolveRequestPaths } from "@/lib/agent-selection";
-import type { TokenIdentity } from "@/lib/api-tokens";
-import { db } from "@/lib/db/client";
-import { jobs, modelFiles, models } from "@/lib/db/schema";
-import { lookupRepo } from "@/lib/hub/lookup";
-import { JobError, OPEN_STATES, queueDownload } from "@/lib/jobs";
-import { purgeModelRows } from "@/lib/model-purge";
-import { addFilesToModel, addModel, ModelError, restoreSelection } from "@/lib/models";
-import { escapeGlob } from "@/lib/selection";
-import { getGuardrails, getRecommendedRoles } from "@/lib/settings";
-import { addTag, normalizeTagName } from "@/lib/tags";
-import { getWorkerStatus } from "@/lib/worker-status";
-
-export type DownloadRequest = {
- repoId: string;
- sha: string;
- /** Branch to track for update checks (default "main"). */
- revision?: string;
- quant?: string;
- include?: string[];
- tags?: string[];
-};
-
-export type DownloadOutcome = {
- /** false: the same repo + commit + files was requested before; nothing new was queued. */
- created: boolean;
- modelId: string;
- jobId: string | null;
- state: string;
- requestedBytes: number;
- files: string[];
- message: string;
-};
-
-/** Bytes that open download jobs still have to fetch (pending approval included). */
-export async function reservedBytes(): Promise {
- const [r] = await db()
- .select({ n: sql`coalesce(sum(${jobs.totalBytes} - ${jobs.doneBytes}), 0)` })
- .from(jobs)
- .where(and(eq(jobs.kind, "download"), inArray(jobs.state, [...OPEN_STATES])));
- return Number(r.n);
-}
-
-/** API-requested jobs that are pending approval, queued or running (all tokens). */
-export async function openAgentJobs(): Promise {
- const [r] = await db()
- .select({ n: sql`count(*)` })
- .from(jobs)
- .where(and(isNotNull(jobs.requestedByTokenId), inArray(jobs.state, [...OPEN_STATES])));
- return Number(r.n);
-}
-
-function stateMessage(state: string, created: boolean): string {
- if (state === "pending_approval") {
- return `${created ? "Requested" : "Already requested"}; waiting for the user to approve it in Kaname. Do not retry or poll; tell the user and stop.`;
- }
- if (state === "queued" || state === "downloading" || state === "verifying") return `${created ? "Queued" : "Already queued"}; GET /api/v1/jobs/{jobId}?wait=900 until it is done.`;
- if (state === "completed") return "Already downloaded.";
- return `The last download ended as "${state}"; ask the user to retry it in Kaname.`;
-}
-
-/** Latest job of a model, for answers to repeated requests. */
-async function latestJob(modelId: string) {
- return db().query.jobs.findFirst({ columns: { id: true, state: true }, where: eq(jobs.modelId, modelId), orderBy: (j, { desc }) => desc(j.createdAt) });
-}
-
-/**
- * A download requested through the API. Checks the author allowlist, resolves the files at the
- * pinned commit, applies the guardrails, then uses the same addModel / addFilesToModel / queue path
- * as the UI. Repeating a request returns what exists instead of queueing a duplicate.
- */
-export async function requestDownload(token: TokenIdentity, req: DownloadRequest, guardrails?: Guardrails): Promise {
- const g = guardrails ?? (await getGuardrails());
- // The allowlist first, before anything goes to the Hub.
- checkAuthor(g, req.repoId);
- (req.tags ?? []).forEach(normalizeTagName); // validate before anything is written
-
- const hub = await lookupRepo(req.repoId, req.sha);
- const paths = resolveRequestPaths(hub.files, req, await getRecommendedRoles());
- const size = new Map(hub.files.map((f) => [f.path, f.size]));
- const requestedBy = { tokenId: token.id, name: token.name };
- const pendingApproval = g.approvalMode === "approve";
-
- const existing = await db().query.models.findFirst({ where: sql`lower(${models.repoId}) = lower(${hub.repoId})` });
- if (existing && existing.pinnedSha !== hub.sha) {
- throw new ModelError(
- "already_exists",
- `${existing.repoId} is already in the library, pinned to commit ${existing.pinnedSha}; you asked for ${hub.sha}. Updating a model is done by the user in Kaname, not through the API.`,
- 409,
- );
- }
-
- let add = paths;
- if (existing) {
- const selected = await db().select({ path: modelFiles.path }).from(modelFiles).where(and(eq(modelFiles.modelId, existing.id), eq(modelFiles.selected, true)));
- add = newPaths(paths, selected.map((f) => f.path));
- if (add.length === 0) {
- const job = await latestJob(existing.id);
- const state = job?.state ?? existing.status;
- return { created: false, modelId: existing.id, jobId: job?.id ?? null, state, requestedBytes: 0, files: paths, message: stateMessage(state, false) };
- }
- const open = await db().query.jobs.findFirst({ columns: { id: true, state: true }, where: and(eq(jobs.modelId, existing.id), inArray(jobs.state, [...OPEN_STATES])) });
- if (open) {
- throw new JobError("busy", `${existing.repoId} has a download that is still ${open.state.replace("_", " ")} (job ${open.id}). Request the other files once it has finished.`, 409);
- }
- }
-
- const requestBytes = add.reduce((s, p) => s + (size.get(p) ?? 0), 0);
- const worker = await getWorkerStatus();
- checkGuardrails(g, {
- repoId: hub.repoId,
- requestBytes,
- freeBytes: worker.online ? worker.modelsDirFreeBytes : null,
- reservedBytes: await reservedBytes(),
- openAgentJobs: await openAgentJobs(),
- });
-
- let modelId: string;
- let jobId: string;
- if (existing) {
- modelId = existing.id;
- ({ jobId } = await addFilesToModel(existing.id, add, { pendingApproval, requestedBy }));
- } else {
- ({ id: modelId } = await addModel({
- repoId: hub.repoId,
- revision: req.revision?.trim() || "main",
- sha: hub.sha,
- rule: { include: paths.map(escapeGlob), exclude: [] },
- requestedBy,
- }));
- ({ jobId } = await queueDownload(modelId, "initial", { pendingApproval, requestedBy }));
- }
- for (const tag of req.tags ?? []) await addTag(modelId, tag);
- const state = pendingApproval ? "pending_approval" : "queued";
- return { created: true, modelId, jobId, state, requestedBytes: requestBytes, files: paths, message: stateMessage(state, true) };
-}
-
-async function pendingJob(jobId: string) {
- const job = await db().query.jobs.findFirst({ where: eq(jobs.id, jobId) });
- if (!job) throw new JobError("not_found", "Job not found.", 404);
- if (job.state !== "pending_approval") throw new JobError("not_cancellable", `This job doesn't wait for approval (it is ${job.state}).`, 409);
- return job;
-}
-
-/** Let an API-requested download start. */
-export async function approveJob(jobId: string): Promise {
- const job = await pendingJob(jobId);
- const d = db();
- await d.batch([
- d.update(jobs).set({ state: "queued" }).where(and(eq(jobs.id, job.id), eq(jobs.state, "pending_approval"))),
- d.update(models).set({ status: "downloading" }).where(eq(models.id, job.modelId)),
- ]);
-}
-
-/**
- * Turn an API-requested download down. A new model that was only added by this request leaves the
- * library again; for added files, the model's previous selection is restored.
- */
-export async function rejectJob(jobId: string): Promise<{ removedModel: boolean }> {
- const job = await pendingJob(jobId);
- await db()
- .update(jobs)
- .set({ state: "cancelled", finishedAt: new Date(), errorMessage: "Rejected by the user." })
- .where(eq(jobs.id, job.id));
- if (job.purpose === "initial") {
- // Only this request ever touched the model: nothing on disk, so it leaves the library again.
- const [{ n }] = await db().select({ n: sql`count(*)` }).from(jobs).where(and(eq(jobs.modelId, job.modelId), ne(jobs.id, job.id)));
- if (Number(n) === 0) {
- await purgeModelRows(job.modelId);
- return { removedModel: true };
- }
- }
- // A pending job never changed the model's status, so only the selection needs restoring.
- if (job.result?.previousRule) await restoreSelection(job.modelId, job.result.previousRule);
- return { removedModel: false };
-}
-
diff --git a/src/lib/agent-guardrails.ts b/src/lib/agent-guardrails.ts
deleted file mode 100644
index ac444cd..0000000
--- a/src/lib/agent-guardrails.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-// Guardrails for downloads requested through the API (an autonomous agent, not a person in the
-// UI). Pure: settings parsing and the checks themselves; the request flow is in agent-downloads.ts.
-
-export const APPROVAL_MODES = ["approve", "auto"] as const;
-export type ApprovalMode = (typeof APPROVAL_MODES)[number];
-
-export type Guardrails = {
- /** approve: requests wait as "pending approval" until someone confirms them in the UI. */
- approvalMode: ApprovalMode;
- /** Largest download one request may add. */
- maxRequestBytes: number;
- /** Free space that must remain on the models folder after the download. */
- minFreeBytes: number;
- /** API-requested jobs that may be pending approval, queued or running at once (all tokens). */
- maxOpenJobs: number;
- /** Hub authors (orgs/users) the API may download from; empty = any. Case-insensitive. */
- allowedAuthors: string[];
-};
-
-const GB = 1_000_000_000;
-
-export const DEFAULT_GUARDRAILS: Guardrails = {
- approvalMode: "approve",
- maxRequestBytes: 60 * GB,
- minFreeBytes: 100 * GB,
- maxOpenJobs: 2,
- allowedAuthors: [],
-};
-
-export class GuardrailError extends Error {
- constructor(
- public code: "too_large" | "disk_space" | "disk_unknown" | "too_many_jobs" | "author_not_allowed",
- message: string,
- public status = 422,
- ) {
- super(message);
- }
-}
-
-const AUTHOR_RE = /^[A-Za-z0-9][\w.-]{0,95}$/;
-
-/** Stored value merged over the defaults; anything invalid falls back to the default. */
-export function parseGuardrails(v: unknown): Guardrails {
- const o = (v && typeof v === "object" ? v : {}) as Record;
- const num = (x: unknown, min: number, def: number) => (typeof x === "number" && Number.isFinite(x) && x >= min ? Math.round(x) : def);
- return {
- approvalMode: APPROVAL_MODES.includes(o.approvalMode as ApprovalMode) ? (o.approvalMode as ApprovalMode) : DEFAULT_GUARDRAILS.approvalMode,
- maxRequestBytes: num(o.maxRequestBytes, 1, DEFAULT_GUARDRAILS.maxRequestBytes),
- minFreeBytes: num(o.minFreeBytes, 0, DEFAULT_GUARDRAILS.minFreeBytes),
- maxOpenJobs: num(o.maxOpenJobs, 1, DEFAULT_GUARDRAILS.maxOpenJobs),
- allowedAuthors: Array.isArray(o.allowedAuthors) ? o.allowedAuthors.filter((a): a is string => typeof a === "string" && AUTHOR_RE.test(a)) : [],
- };
-}
-
-/** "unsloth, ggml-org Qwen" → ["unsloth", "ggml-org", "Qwen"]; throws on an invalid name. */
-export function parseAuthorList(text: string): string[] {
- const out: string[] = [];
- for (const a of text.split(/[\s,]+/).filter(Boolean)) {
- if (!AUTHOR_RE.test(a)) throw new Error(`"${a}" is not a valid Hugging Face user or organization name.`);
- if (!out.some((x) => x.toLowerCase() === a.toLowerCase())) out.push(a);
- }
- return out;
-}
-
-/** Plain GB (10^9), as the Hub and the settings use: "74.2 GB". */
-export function gb(bytes: number): string {
- return `${(bytes / GB).toFixed(1)} GB`;
-}
-
-export type GuardrailInput = {
- repoId: string;
- /** Bytes this request would download. */
- requestBytes: number;
- /** Free bytes on the models folder (worker heartbeat), or null if unknown. */
- freeBytes: number | null;
- /** Bytes other open jobs still have to download. */
- reservedBytes: number;
- /** API-requested jobs that are pending approval, queued or running right now. */
- openAgentJobs: number;
-};
-
-/** The author allowlist alone (checked before anything goes to the Hub). */
-export function checkAuthor(g: Guardrails, repoId: string): void {
- const author = repoId.split("/")[0];
- if (g.allowedAuthors.length > 0 && !g.allowedAuthors.some((a) => a.toLowerCase() === author.toLowerCase())) {
- throw new GuardrailError(
- "author_not_allowed",
- `author "${author}" is not on the allowlist (${g.allowedAuthors.join(", ")}). Pick a repo from one of these authors, or ask the user to extend the allowlist.`,
- 403,
- );
- }
-}
-
-/** Throws a GuardrailError with a message an agent can act on; returns normally if allowed. */
-export function checkGuardrails(g: Guardrails, x: GuardrailInput): void {
- checkAuthor(g, x.repoId);
- if (x.requestBytes > g.maxRequestBytes) {
- throw new GuardrailError(
- "too_large",
- `exceeds max size per request ${gb(g.maxRequestBytes)}: requested ${gb(x.requestBytes)}. Pick a smaller quant or fewer files.`,
- );
- }
- if (x.openAgentJobs >= g.maxOpenJobs) {
- throw new GuardrailError(
- "too_many_jobs",
- `too many agent downloads at once: ${x.openAgentJobs} pending or running, the limit is ${g.maxOpenJobs}. Wait until one has finished (or been approved and finished) before requesting another.`,
- 429,
- );
- }
- if (x.freeBytes == null) {
- throw new GuardrailError("disk_unknown", "free disk space is unknown (the Kaname worker is offline). Try again later.", 503);
- }
- const after = x.freeBytes - x.reservedBytes - x.requestBytes;
- if (after < g.minFreeBytes) {
- throw new GuardrailError(
- "disk_space",
- `not enough disk space: ${gb(x.requestBytes)} requested, ${gb(x.freeBytes)} free` +
- (x.reservedBytes > 0 ? ` (${gb(x.reservedBytes)} of it reserved by other downloads)` : "") +
- `, and at least ${gb(g.minFreeBytes)} must stay free (${gb(Math.max(0, after))} would be left). Pick a smaller quant or ask the user to free space.`,
- 507,
- );
- }
-}
-
-export function describeGuardrails(g: Guardrails): string {
- return [
- g.approvalMode === "approve" ? "requests wait for approval" : "downloads start immediately",
- `max ${gb(g.maxRequestBytes)} per request`,
- `${gb(g.minFreeBytes)} must stay free`,
- `max ${g.maxOpenJobs} agent jobs at once`,
- g.allowedAuthors.length ? `authors: ${g.allowedAuthors.join(", ")}` : "any author",
- ].join(" · ");
-}
diff --git a/src/lib/agent-runs.ts b/src/lib/agent-runs.ts
deleted file mode 100644
index ef7f357..0000000
--- a/src/lib/agent-runs.ts
+++ /dev/null
@@ -1,285 +0,0 @@
-import "server-only";
-import { and, desc, eq, or } from "drizzle-orm";
-import { z } from "zod";
-import { checkRun, TuningError, type TuningGuardrails } from "@/lib/agent-tuning";
-import { gpuLoad } from "@/lib/agent-deployments";
-import type { TokenIdentity } from "@/lib/api-tokens";
-import { metaRows } from "@/lib/benchmark-meta";
-import { headline } from "@/lib/benchmark-view";
-import { BENCHMARK_PHASES, type BenchmarkSummary, benchmarkRuns, QUALITY_SECTIONS, type QualityResult, type RunMeta } from "@/lib/db/schema";
-import { db } from "@/lib/db/client";
-import { BenchmarkBody, type BenchmarkRow, createBenchmark, getBenchmark, getBenchmarks } from "@/lib/benchmarks";
-import { getDeployment } from "@/lib/deployments";
-import { getTuning } from "@/lib/settings";
-import { MAX_SWEEP_PARAMS, splitValues } from "@/lib/sweep";
-import { createSweep, getSweep, type SweepRow } from "@/lib/sweeps";
-
-// Benchmark runs, A/B runs and sweeps through the API: on the token's own deployments only, one at a
-// time across all agents, with time limits and (by default) the user's approval.
-
-export const AgentRunBody = z
- .object({
- /** run: BetterBench speed; ab: paired A/B; eval: the quality eval (tool calling, coding, retrieval). */
- kind: z.enum(["run", "ab", "eval"]).default("run"),
- deploymentId: z.string().min(1),
- /** A/B: the second deployment (same model). */
- deploymentBId: z.string().min(1).optional(),
- label: z.string().trim().max(120).optional(),
- description: z.string().trim().max(4000).optional(),
- /** quick: 5 passes, a smoke check; full (default): 20 passes, comparable. */
- quick: z.boolean().default(false),
- passes: z.number().int().min(1).max(200).optional(),
- phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
- mdePct: z.number().min(0.1).max(50).optional(),
- maxPairs: z.number().int().min(12).max(2000).optional(),
- /** eval: which sections (default all). */
- sections: z.array(z.enum(QUALITY_SECTIONS)).max(3).optional(),
- })
- .strict();
-
-export const AgentSweepBody = z
- .object({
- baseDeploymentId: z.string().min(1),
- label: z.string().trim().max(80).optional(),
- /** One or two settings with their values, e.g. [{ key: "kvCache", values: ["f16", "q8_0"] }]. */
- params: z
- .array(z.object({ key: z.string().min(1).max(40), values: z.array(z.string().max(1024)).min(1).max(16) }).strict())
- .min(1)
- .max(MAX_SWEEP_PARAMS),
- quick: z.boolean().default(true),
- passes: z.number().int().min(1).max(200).optional(),
- phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
- /** Also run the quality eval on each variant. */
- quality: z.boolean().default(false),
- })
- .strict();
-
-/** A deployment this token may benchmark: its own, not protected, running. */
-async function benchmarkable(token: TokenIdentity, id: string, role: string) {
- const d = await getDeployment(id);
- if (!d) throw new TuningError("not_owner", `${role} not found.`, 404);
- if (d.protected) throw new TuningError("protected", `"${d.name}" is protected; agents can't benchmark it.`, 403);
- if (d.requestedByTokenId !== token.id) throw new TuningError("not_owner", `"${d.name}" wasn't created by this token; agents only benchmark their own deployments. Deploy the model yourself (POST /api/v1/deployments).`, 403);
- return d;
-}
-
-const requested = (token: TokenIdentity) => ({ tokenId: token.id, name: token.name });
-
-/** Queue a run or A/B against the token's own running deployment(s). */
-export async function requestRun(token: TokenIdentity, body: z.infer, g?: TuningGuardrails) {
- const guard = g ?? (await getTuning());
- await benchmarkable(token, body.deploymentId, body.kind === "ab" ? "Deployment A" : "The deployment");
- if (body.kind === "ab") {
- if (!body.deploymentBId) throw new TuningError("not_owner", "An A/B needs deploymentBId (your second deployment of the same model).", 400);
- await benchmarkable(token, body.deploymentBId, "Deployment B");
- }
- checkRun(await gpuLoad());
- const pending = guard.approvalMode === "approve";
- const row = await createBenchmark(
- BenchmarkBody.parse({
- deploymentId: body.deploymentId,
- deploymentBId: body.kind === "ab" ? body.deploymentBId : null,
- label: body.label ?? null,
- description: body.description ?? null,
- quick: body.quick,
- passes: body.passes ?? null,
- phases: body.phases,
- mdePct: body.mdePct ?? null,
- maxPairs: body.maxPairs ?? null,
- kind: body.kind,
- evalSections: body.sections,
- }),
- { requestedBy: requested(token), pendingApproval: pending, timeLimitS: guard.maxRunMinutes * 60 },
- );
- return { id: row.id, state: pending ? "pending_approval" : "queued", timeLimitMinutes: guard.maxRunMinutes };
-}
-
-/** Queue a sweep from the token's own base deployment (each variant deploys and is removed again). */
-export async function requestSweep(token: TokenIdentity, body: z.infer, g?: TuningGuardrails) {
- const guard = g ?? (await getTuning());
- const base = await benchmarkable(token, body.baseDeploymentId, "The base deployment");
- const load = await gpuLoad();
- checkRun(load);
- // Each variant starts its own deployment; an agent deployment still running would share the GPU.
- if (load.agentDeployments > 0) {
- throw new TuningError("gpu_busy", "an agent deployment is still running or waiting to start; a sweep deploys each variant itself. Stop yours first (POST /api/v1/deployments/{id}/stop).", 429);
- }
- const count = body.params.reduce((n, p) => n * splitValues(p.values.join(",")).length, 1);
- if (count > guard.maxSweepVariants) {
- throw new TuningError("too_many_variants", `That's ${count} variants; agents may run at most ${guard.maxSweepVariants} per sweep. Vary fewer values.`);
- }
- const pending = guard.approvalMode === "approve";
- const row = await createSweep(
- { baseDeploymentId: base.id, label: body.label ?? null, params: body.params, quick: body.quick, passes: body.passes ?? null, phases: body.phases, quality: body.quality },
- {
- requestedBy: requested(token),
- pendingApproval: pending,
- timeLimitS: guard.maxSweepMinutes * 60,
- runTimeLimitS: guard.maxRunMinutes * 60,
- maxVariants: guard.maxSweepVariants,
- },
- );
- return { id: row.id, state: pending ? "pending_approval" : "queued", variants: count, timeLimitMinutes: guard.maxSweepMinutes };
-}
-
-/** Cancel a run or sweep this token asked for. */
-export async function ownRun(token: TokenIdentity, id: string) {
- const run = await getBenchmark(id);
- if (!run) throw new TuningError("not_owner", "No benchmark run with this id.", 404);
- if (run.requestedByTokenId !== token.id) throw new TuningError("not_owner", "This run wasn't started by this token; agents only cancel their own runs.", 403);
- return run;
-}
-
-export async function ownSweep(token: TokenIdentity, id: string) {
- const s = await getSweep(id);
- if (!s) throw new TuningError("not_owner", "No sweep with this id.", 404);
- if (s.sweep.requestedByTokenId !== token.id) throw new TuningError("not_owner", "This sweep wasn't started by this token; agents only cancel their own sweeps.", 403);
- return s;
-}
-
-const r1 = (v: number | null | undefined) => (v == null ? null : Math.round(v * 10) / 10);
-
-/** The quality eval in short: overall score and per section. */
-export function qualityView(q: QualityResult | null | undefined) {
- if (!q) return null;
- return {
- evalSet: q.evalSet,
- score: q.score,
- sections: Object.fromEntries(q.sections.map((s) => [s.section, s.unsupported ? `n/a (${s.unsupported})` : `${s.passed}/${s.total}`])),
- };
-}
-
-/** Headline numbers + the setup (section 1 metadata) as key/value. */
-function compact(summary: BenchmarkSummary | null, meta: RunMeta | null, quality?: QualityResult | null) {
- const h = headline(summary);
- return {
- ...(quality ? { quality: qualityView(quality) } : {}),
- headline: {
- decodeTps: r1(h.decode),
- prefillTps: r1(h.prefill?.tps),
- prefillDepth: h.prefill?.depth ?? null,
- ttftMs: r1(h.ttftMs),
- peakParallelTps: r1(h.peak?.tps),
- peakParallelLevel: h.peak?.level ?? null,
- },
- setup: meta ? Object.fromEntries(metaRows(meta).map((r) => [r.key, r.value])) : null,
- };
-}
-
-const RUN_NEXT: Record = {
- pending_approval: "Waiting for the user's approval in Kaname. Don't retry or poll; tell the user and stop.",
- queued: "Queued (one benchmark at a time). GET it with ?wait=900 instead of polling.",
- running: "Running. GET it with ?wait=900 instead of polling.",
- completed: "Done. Compare runs with GET /api/v1/benchmarks/compare?ids=…",
- failed: "Failed; see error. Fix the cause before trying again.",
- cancelled: "Cancelled or rejected by the user (or by you).",
-};
-
-export const runSettled = (state: string) => state !== "queued" && state !== "running";
-
-/** Compact run state: headline numbers, setup, resources; the full summary with `full`. */
-export function runView(r: BenchmarkRow, token: TokenIdentity, full = false) {
- const res = r.resources;
- return {
- id: r.id,
- kind: r.kind,
- state: r.state,
- label: r.label,
- description: r.description,
- deploymentId: r.deploymentId,
- deploymentBId: r.deploymentBId,
- deployment: r.snapshot.deploymentName,
- requestedBy: r.requestedBy,
- mine: r.requestedByTokenId === token.id,
- settings: r.settings,
- phase: r.phase,
- error: r.error,
- timeLimitMinutes: r.timeLimitS ? Math.round(r.timeLimitS / 60) : null,
- startedAt: r.startedAt ? new Date(r.startedAt).toISOString() : null,
- finishedAt: r.finishedAt ? new Date(r.finishedAt).toISOString() : null,
- ...compact(r.summary, r.meta, r.quality),
- ...(r.kind === "eval" && r.quality && full ? { failed: r.quality.items.filter((i) => !i.pass) } : {}),
- ...(r.kind === "ab" && r.ab
- ? {
- ab: {
- pairs: r.ab.pairs,
- verdict: r.ab.decode_tps.verdict,
- decodeDiffPct: r1(r.ab.decode_tps.pct_diff),
- ciPct: [r1(r.ab.decode_tps.ci_low_pct), r1(r.ab.decode_tps.ci_high_pct)],
- significant: r.ab.decode_tps.significant,
- setupB: r.metaB ? Object.fromEntries(metaRows(r.metaB).map((x) => [x.key, x.value])) : null,
- },
- }
- : {}),
- resources: res
- ? {
- cpuAvgCores: r1(res.containers[0]?.cpuAvg),
- ramPeakBytes: res.containers[0]?.memPeakBytes ?? null,
- gpus: res.gpus.map((g) => ({ name: g.name, vramPeakMb: g.vramPeakMb, vramTotalMb: g.vramTotalMb, utilAvg: r1(g.utilAvg), powerAvgW: r1(g.powerAvgW), tempPeakC: r1(g.tempPeakC) })),
- }
- : null,
- next: RUN_NEXT[r.state] ?? null,
- ...(full ? { summary: r.summary } : {}),
- };
-}
-
-export function sweepView(data: NonNullable>>, token: TokenIdentity) {
- const s: SweepRow = data.sweep;
- return {
- id: s.id,
- state: s.state,
- label: s.label,
- baseDeploymentId: s.baseDeploymentId,
- params: s.params,
- settings: s.settings,
- requestedBy: s.requestedBy,
- mine: s.requestedByTokenId === token.id,
- error: s.error,
- timeLimitMinutes: s.timeLimitS ? Math.round(s.timeLimitS / 60) : null,
- variants: s.variants.map((v) => {
- const run = data.runs.find((r) => r.id === v.runId);
- const ev = data.runs.find((r) => r.id === v.evalRunId);
- return {
- label: v.label,
- overrides: v.overrides,
- state: v.state,
- runId: v.runId ?? null,
- evalRunId: v.evalRunId ?? null,
- error: v.error ?? null,
- ...compact(run?.summary ?? null, run?.meta ?? null, ev?.quality ?? null),
- };
- }),
- startedAt: s.startedAt?.toISOString() ?? null,
- finishedAt: s.finishedAt?.toISOString() ?? null,
- next: s.state === "pending_approval" ? RUN_NEXT.pending_approval : s.state === "queued" || s.state === "running" ? "Running variant by variant. GET it with ?wait=900 instead of polling." : null,
- };
-}
-
-/** Runs side by side: headline numbers and the setup keys whose values differ. */
-export async function compareRuns(ids: string[]) {
- const runs = await getBenchmarks(ids);
- const rows = runs.map((r) => ({ id: r.id, kind: r.kind, label: r.label ?? r.snapshot.deploymentName, state: r.state, ...compact(r.summary, r.meta, r.quality) }));
- const keys = [...new Set(rows.flatMap((r) => Object.keys(r.setup ?? {})))];
- const differs = keys.filter((k) => new Set(rows.map((r) => r.setup?.[k] ?? "")).size > 1);
- return {
- runs: rows.map((r) => ({ ...r, setup: undefined, differs: Object.fromEntries(differs.map((k) => [k, r.setup?.[k] ?? null])) })),
- same: Object.fromEntries(keys.filter((k) => !differs.includes(k)).map((k) => [k, rows[0]?.setup?.[k] ?? null])),
- note: "Headline: decode t/s (weighted), prefill t/s at the deepest prompt, TTFT p50 ms; quality: the eval score 0–100 (same evalSet only). Differences under ~2 % between separate speed runs are noise; use an A/B for small effects.",
- };
-}
-
-/** Recent runs, newest first, optionally of one deployment or token. */
-export async function listRunsFor(filter: { deploymentId?: string; requestedBy?: string; limit: number }) {
- const rows = await db()
- .select({ id: benchmarkRuns.id })
- .from(benchmarkRuns)
- .where(
- and(
- filter.deploymentId ? or(eq(benchmarkRuns.deploymentId, filter.deploymentId), eq(benchmarkRuns.deploymentBId, filter.deploymentId)) : undefined,
- filter.requestedBy ? eq(benchmarkRuns.requestedBy, filter.requestedBy.toLowerCase()) : undefined,
- ),
- )
- .orderBy(desc(benchmarkRuns.createdAt))
- .limit(filter.limit);
- return getBenchmarks(rows.map((r) => r.id));
-}
diff --git a/src/lib/agent-selection.ts b/src/lib/agent-selection.ts
deleted file mode 100644
index 94e6ef0..0000000
--- a/src/lib/agent-selection.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-// Which files an API download request means, from a quant name or include globs, the same way the
-// Add model dialog picks them. Pure.
-
-import { fileRole, type FileRole } from "@/lib/file-roles";
-import { recommendFiles } from "@/lib/recommend";
-import { matchesAny, quantGroup } from "@/lib/selection";
-
-type File = { path: string; size: number };
-
-export class SelectionError extends Error {
- code = "empty_selection";
- status = 400;
-}
-
-/** Quant group of a model-weight file (not mmproj/MTP/imatrix), e.g. "Q4_K_M", "UD-Q4_K_XL". */
-function weightQuant(path: string): string | null {
- return fileRole(path) === "model" ? quantGroup(path) : null;
-}
-
-/** Quants in a repo (model weights only) with file count and total size, in file order. */
-export function quantSummary(files: File[]): { quant: string; files: number; bytes: number }[] {
- const out = new Map();
- for (const f of files) {
- const q = weightQuant(f.path);
- if (!q) continue;
- const e = out.get(q) ?? { quant: q, files: 0, bytes: 0 };
- e.files++;
- e.bytes += f.size;
- out.set(q, e);
- }
- return [...out.values()];
-}
-
-/**
- * Paths for a request: the weight files of `quant` (all split parts) plus the companion files of the
- * recommended kinds (Settings → Downloads), or every file matching one of the `include` globs.
- */
-export function resolveRequestPaths(files: File[], req: { quant?: string; include?: string[] }, recommendedRoles: FileRole[]): string[] {
- if (req.quant) {
- const want = req.quant.trim().toLowerCase();
- const weights = files.filter((f) => weightQuant(f.path)?.toLowerCase() === want).map((f) => f.path);
- if (weights.length === 0) {
- const available = quantSummary(files).map((q) => q.quant);
- throw new SelectionError(
- available.length
- ? `quant "${req.quant}" not found in this repo. Available: ${available.join(", ")}.`
- : `quant "${req.quant}" not found: this repo has no GGUF quants. Use "include" globs instead (e.g. ["*.safetensors", "*.json"]).`,
- );
- }
- return [...new Set([...weights, ...recommendFiles(files, weights, recommendedRoles)])].sort();
- }
- const globs = req.include ?? [];
- const paths = files.filter((f) => matchesAny(f.path, globs)).map((f) => f.path);
- if (paths.length === 0) throw new SelectionError(`no file in this repo matches ${JSON.stringify(globs)}. Look up the repo to see its files.`);
- return paths.sort();
-}
-
-/** Files a request adds to what's already selected, for size checks and idempotency. */
-export function newPaths(requested: string[], selected: Iterable): string[] {
- const have = new Set(selected);
- return requested.filter((p) => !have.has(p));
-}
diff --git a/src/lib/agent-tuning.test.ts b/src/lib/agent-tuning.test.ts
deleted file mode 100644
index e6e20f1..0000000
--- a/src/lib/agent-tuning.test.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-import assert from "node:assert/strict";
-import { describe, it } from "node:test";
-import { checkArgs, checkHostPort, checkLimits, checkRun, checkStart, checkVram, DEFAULT_TUNING, overTime, parseFlagList, parseTuning, type TuningError } from "./agent-tuning";
-import { parseWait, waitFor } from "./wait";
-
-const g = DEFAULT_TUNING;
-const rejects = (fn: () => void, code: TuningError["code"], message?: RegExp) =>
- assert.throws(fn, (e: TuningError) => e.code === code && (!message || message.test(e.message)));
-
-describe("tuning guardrails: settings", () => {
- it("defaults: approve, 1 deployment, 30/180 min, 8 variants, no ports, no caps", () => {
- assert.deepEqual(parseTuning(null), DEFAULT_TUNING);
- assert.equal(g.approvalMode, "approve");
- assert.equal(g.maxAgentDeployments, 1);
- assert.equal(g.maxRunMinutes, 30);
- assert.equal(g.maxSweepMinutes, 180);
- assert.equal(g.maxSweepVariants, 8);
- assert.equal(g.hostPortRange, null);
- });
-
- it("falls back to defaults for invalid stored values and drops non-flags", () => {
- const t = parseTuning({ approvalMode: "yolo", maxAgentDeployments: 0, maxSweepVariants: 99, hostPortRange: { from: 9000, to: 80 }, allowedArgs: { "llama.cpp": ["--no-mmap", "rm -rf"], vllm: "x" } });
- assert.equal(t.approvalMode, "approve");
- assert.equal(t.maxAgentDeployments, 1);
- assert.equal(t.maxSweepVariants, 8);
- assert.equal(t.hostPortRange, null);
- assert.deepEqual(t.allowedArgs["llama.cpp"], ["--no-mmap"]);
- assert.deepEqual(t.allowedArgs.vllm, DEFAULT_TUNING.allowedArgs.vllm);
- assert.deepEqual(parseFlagList("--no-mmap, -ctk --mlock --no-mmap"), ["--no-mmap", "-ctk", "--mlock"]);
- assert.throws(() => parseFlagList("--ok /etc/passwd"), /isn't a flag/);
- });
-});
-
-describe("tuning guardrails: extra arguments", () => {
- it("passes allowlisted flags with values", () => {
- checkArgs(g, "llama.cpp", ["--no-mmap", "-ctk", "q8_0", "--override-tensor=blk\\..*_exps=CPU", "-n", "-1"]);
- checkArgs(g, "vllm", ["--kv-cache-dtype", "fp8", "--enable-prefix-caching"]);
- });
-
- it("refuses flags not on the engine's list, naming them", () => {
- rejects(() => checkArgs(g, "llama.cpp", ["--host", "0.0.0.0"]), "arg_not_allowed", /"--host"/);
- rejects(() => checkArgs(g, "llama.cpp", ["--api-key=x"]), "arg_not_allowed", /"--api-key"/);
- rejects(() => checkArgs(g, "llama.cpp", ["-m", "x.gguf"]), "arg_not_allowed", /"-m"/);
- rejects(() => checkArgs(g, "vllm", ["--trust-remote-code"]), "arg_not_allowed", /"--trust-remote-code"/);
- rejects(() => checkArgs(g, "vllm", ["--no-mmap"]), "arg_not_allowed", /on vllm/);
- });
-
- it("refuses paths, URLs and stray values", () => {
- rejects(() => checkArgs(g, "llama.cpp", ["--chat-template", "/etc/passwd"]), "arg_not_allowed", /path or URL/);
- rejects(() => checkArgs(g, "llama.cpp", ["--chat-template=../x"]), "arg_not_allowed", /path or URL/);
- rejects(() => checkArgs(g, "vllm", ["--compilation-config", "http://evil/x"]), "arg_not_allowed", /path or URL/);
- rejects(() => checkArgs(g, "llama.cpp", ["q8_0"]), "arg_not_allowed", /isn't a value of a flag/);
- rejects(() => checkArgs(g, "llama.cpp", ["--no-mmap=1", "extra"]), "arg_not_allowed", /isn't a value/);
- });
-});
-
-describe("tuning guardrails: ports and limits", () => {
- it("allows no host ports unless a range is set", () => {
- checkHostPort(g, null);
- rejects(() => checkHostPort(g, 18080), "port_not_allowed", /none configured/);
- const r = { ...g, hostPortRange: { from: 18000, to: 18099 } };
- checkHostPort(r, 18080);
- rejects(() => checkHostPort(r, 19000), "port_not_allowed", /18000–18099/);
- });
-
- it("applies the memory cap to the given limit or the estimate, and the CPU cap", () => {
- const capped = { ...g, maxMemoryMb: 16384, maxCpus: 8 };
- assert.deepEqual(checkLimits(capped, { memoryMb: null, cpus: null, estimateMb: 9000, hostMemoryMb: 65536, hostCpus: 32 }), { memoryMb: 9000, cpus: 8 });
- rejects(() => checkLimits(capped, { memoryMb: 20000, cpus: null, estimateMb: 9000, hostMemoryMb: 65536, hostCpus: 32 }), "limit_exceeded", /16384 MiB/);
- rejects(() => checkLimits(capped, { memoryMb: null, cpus: null, estimateMb: 30000, hostMemoryMb: 65536, hostCpus: 32 }), "limit_exceeded", /the estimate/);
- rejects(() => checkLimits(capped, { memoryMb: 1024, cpus: 12, estimateMb: 900, hostMemoryMb: 65536, hostCpus: 32 }), "limit_exceeded", /8 cores/);
- // Without caps, the host's size is the cap.
- rejects(() => checkLimits(g, { memoryMb: 70000, cpus: null, estimateMb: 1, hostMemoryMb: 65536, hostCpus: 32 }), "limit_exceeded");
- });
-});
-
-describe("tuning guardrails: one GPU job at a time", () => {
- const idle = { agentDeployments: 0, agentRuns: 0, agentStarting: 0 };
- it("lets a deployment start when nothing of an agent runs", () => {
- checkStart(g, idle);
- checkRun(idle);
- });
-
- it("refuses starts while an agent run is open or a deployment is loading, and over the count", () => {
- rejects(() => checkStart(g, { ...idle, agentRuns: 1 }), "gpu_busy", /benchmark or sweep/);
- rejects(() => checkStart(g, { ...idle, agentStarting: 1 }), "gpu_busy", /starting/);
- rejects(() => checkStart(g, { ...idle, agentDeployments: 1 }), "too_many_deployments", /the limit is 1/);
- checkStart({ ...g, maxAgentDeployments: 2 }, { ...idle, agentDeployments: 1 });
- });
-
- it("refuses a second run, and runs while a deployment is loading", () => {
- rejects(() => checkRun({ ...idle, agentRuns: 1 }), "gpu_busy", /only one at a time/);
- rejects(() => checkRun({ ...idle, agentStarting: 1 }), "gpu_busy", /still starting/);
- });
-});
-
-describe("tuning guardrails: protected deployments' VRAM", () => {
- it("ignores GPUs without protected deployments", () => {
- checkVram({ protectedNames: [], newMb: null, runningMb: [30000], totalMb: 32768 });
- });
-
- it("refuses what wouldn't fit next to a protected deployment", () => {
- checkVram({ protectedNames: ["prod"], newMb: 8000, runningMb: [20000], totalMb: 32768 });
- rejects(() => checkVram({ protectedNames: ["prod"], newMb: 12000, runningMb: [20000], totalMb: 32768 }), "vram_protected", /crowd protected deployment\(s\) prod/);
- });
-
- it("refuses when the need can't be estimated", () => {
- rejects(() => checkVram({ protectedNames: ["prod"], newMb: null, runningMb: [20000], totalMb: 32768 }), "vram_protected", /can't be estimated/);
- rejects(() => checkVram({ protectedNames: ["prod"], newMb: 1000, runningMb: [-1], totalMb: 32768 }), "vram_protected");
- rejects(() => checkVram({ protectedNames: ["prod"], newMb: 1000, runningMb: [], totalMb: null }), "vram_protected");
- });
-
- it("knows when a run or sweep is over its time limit", () => {
- const start = new Date(1_000_000);
- assert.equal(overTime(start, 60, 1_000_000 + 59_000), false);
- assert.equal(overTime(start, 60, 1_000_000 + 61_000), true);
- assert.equal(overTime(null, 60), false);
- assert.equal(overTime(start, null), false);
- });
-});
-
-describe("?wait=", () => {
- it("parses and caps the seconds", () => {
- assert.equal(parseWait(new URLSearchParams("wait=30")), 30);
- assert.equal(parseWait(new URLSearchParams("wait=5000")), 900);
- assert.equal(parseWait(new URLSearchParams("wait=-1")), 0);
- assert.equal(parseWait(new URLSearchParams("")), 0);
- });
-
- it("returns once the state settles", async () => {
- let n = 0;
- const r = await waitFor(async () => ++n, (v) => v >= 3, 5, { pollMs: 10 });
- assert.equal(r.value, 3);
- assert.equal(r.timedOut, false);
- });
-
- it("returns right away when already settled, and after the wait otherwise", async () => {
- let loads = 0;
- const now = await waitFor(async () => (loads++, "done"), () => true, 900, { pollMs: 10 });
- assert.equal(loads, 1);
- assert.equal(now.waitedS, 0);
- const t0 = Date.now();
- const late = await waitFor(async () => "running", () => false, 1, { pollMs: 50 });
- assert.ok(Date.now() - t0 >= 950);
- assert.equal(late.timedOut, true);
- });
-
- it("stops waiting when the client goes away", async () => {
- const ac = new AbortController();
- setTimeout(() => ac.abort(), 50);
- const t0 = Date.now();
- await waitFor(async () => "running", () => false, 30, { pollMs: 20, signal: ac.signal });
- assert.ok(Date.now() - t0 < 1000);
- });
-});
diff --git a/src/lib/agent-tuning.ts b/src/lib/agent-tuning.ts
deleted file mode 100644
index e692ad1..0000000
--- a/src/lib/agent-tuning.ts
+++ /dev/null
@@ -1,351 +0,0 @@
-// Guardrails for deployments and benchmarks requested through the API (an agent tuning launch
-// options, not a person in the UI). Pure: settings parsing and the checks; the request flows are in
-// agent-deployments.ts and agent-runs.ts.
-
-import { APPROVAL_MODES, type ApprovalMode } from "@/lib/agent-guardrails";
-import type { RuntimeEngine } from "@/lib/db/schema";
-
-/**
- * Extra arguments an agent may pass, per engine: tuning flags only. Not allowed (not listed): paths
- * and files (-m, --log-file, --chat-template-file, --slot-save-path, --download-dir), network and
- * auth (--host, --port, --api-key, --rpc, --ssl-*), anything that fetches or runs code from
- * elsewhere (-hf, --model-url, --trust-remote-code, --tokenizer, --speculative-config, --lora).
- * Docker-level options (devices, volumes, privileges, capabilities, network) aren't arguments at
- * all: they come from the runtime, which tokens can't change.
- */
-export const DEFAULT_ALLOWED_ARGS: Record = {
- "llama.cpp": [
- "--no-mmap",
- "--mlock",
- "--numa",
- "-fa",
- "--flash-attn",
- "-ctk",
- "--cache-type-k",
- "-ctv",
- "--cache-type-v",
- "-nkvo",
- "--no-kv-offload",
- "-kvu",
- "--kv-unified",
- "--no-kv-unified",
- "--swa-full",
- "-dt",
- "--defrag-thold",
- "-cb",
- "--cont-batching",
- "-nocb",
- "--no-cont-batching",
- "--cache-reuse",
- "--context-shift",
- "--no-context-shift",
- "-b",
- "--batch-size",
- "-ub",
- "--ubatch-size",
- "-t",
- "--threads",
- "-tb",
- "--threads-batch",
- "--prio",
- "--poll",
- "-sm",
- "--split-mode",
- "-ts",
- "--tensor-split",
- "-mg",
- "--main-gpu",
- "-ot",
- "--override-tensor",
- "--cpu-moe",
- "-cmoe",
- "--n-cpu-moe",
- "-ncmoe",
- "--rope-scaling",
- "--rope-scale",
- "--rope-freq-base",
- "--rope-freq-scale",
- "--yarn-orig-ctx",
- "--yarn-ext-factor",
- "--yarn-attn-factor",
- "--yarn-beta-slow",
- "--yarn-beta-fast",
- "--draft-max",
- "--draft-min",
- "--draft-p-min",
- "-ngld",
- "--gpu-layers-draft",
- "--spec-replace",
- "--jinja",
- "--no-jinja",
- "--chat-template",
- "--reasoning-format",
- "--reasoning-budget",
- "--slot-prompt-similarity",
- "--temp",
- "--top-k",
- "--top-p",
- "--min-p",
- "--repeat-penalty",
- "--presence-penalty",
- "-n",
- "--n-predict",
- "--threads-http",
- ],
- vllm: [
- "--kv-cache-dtype",
- "--max-num-batched-tokens",
- "--enable-chunked-prefill",
- "--no-enable-chunked-prefill",
- "--enable-prefix-caching",
- "--no-enable-prefix-caching",
- "--block-size",
- "--swap-space",
- "--cpu-offload-gb",
- "--enforce-eager",
- "--max-seq-len-to-capture",
- "--compilation-config",
- "-O",
- "--quantization",
- "-q",
- "--pipeline-parallel-size",
- "-pp",
- "--enable-expert-parallel",
- "--async-scheduling",
- "--enable-auto-tool-choice",
- "--tool-call-parser",
- "--reasoning-parser",
- "--max-logprobs",
- "--seed",
- "--override-generation-config",
- "--limit-mm-per-prompt",
- "--mm-processor-kwargs",
- "--disable-log-requests",
- "--disable-log-stats",
- ],
-};
-
-export type TuningGuardrails = {
- /** approve: agent starts, runs and sweeps wait as "pending approval" until someone confirms them. */
- approvalMode: ApprovalMode;
- /** Agent deployments running (or waiting to start) at once, all tokens together. */
- maxAgentDeployments: number;
- maxRunMinutes: number;
- maxSweepMinutes: number;
- maxSweepVariants: number;
- /** Runtime ids agents may use; empty = every runtime with a pulled image. */
- allowedRuntimeIds: string[];
- /** Extra argument flags agents may use, per engine. */
- allowedArgs: Record;
- /** Host ports agents may publish; null = none (Kaname reaches deployments over the Docker network). */
- hostPortRange: { from: number; to: number } | null;
- /** Caps for an agent deployment's limits; null = the host's size. Agent deployments always get a memory limit. */
- maxMemoryMb: number | null;
- maxCpus: number | null;
-};
-
-export const DEFAULT_TUNING: TuningGuardrails = {
- approvalMode: "approve",
- maxAgentDeployments: 1,
- maxRunMinutes: 30,
- maxSweepMinutes: 180,
- maxSweepVariants: 8,
- allowedRuntimeIds: [],
- allowedArgs: DEFAULT_ALLOWED_ARGS,
- hostPortRange: null,
- maxMemoryMb: null,
- maxCpus: null,
-};
-
-export const TUNING_KEY = "agent.tuning";
-
-export type TuningErrorCode =
- | "runtime_not_allowed"
- | "runtime_not_pulled"
- | "arg_not_allowed"
- | "port_not_allowed"
- | "limit_exceeded"
- | "too_many_deployments"
- | "gpu_busy"
- | "protected"
- | "not_owner"
- | "vram_protected"
- | "too_many_variants"
- | "approval_pending";
-
-export class TuningError extends Error {
- constructor(
- public code: TuningErrorCode,
- message: string,
- public status = 422,
- ) {
- super(message);
- }
-}
-
-const FLAG_RE = /^--?[A-Za-z][\w-]*$/;
-const int = (x: unknown, min: number, max: number, def: number) => (typeof x === "number" && Number.isInteger(x) && x >= min && x <= max ? x : def);
-const numOrNull = (x: unknown, min: number) => (typeof x === "number" && Number.isFinite(x) && x >= min ? x : null);
-
-/** Stored value merged over the defaults; anything invalid falls back to the default. */
-export function parseTuning(v: unknown): TuningGuardrails {
- const o = (v && typeof v === "object" ? v : {}) as Record;
- const args = (o.allowedArgs ?? {}) as Record;
- const flags = (x: unknown, def: string[]) => (Array.isArray(x) ? [...new Set(x.filter((f): f is string => typeof f === "string" && FLAG_RE.test(f)))] : def);
- const range = o.hostPortRange as { from?: unknown; to?: unknown } | null | undefined;
- const from = int(range?.from, 1024, 65_535, 0);
- const to = int(range?.to, 1024, 65_535, 0);
- return {
- approvalMode: APPROVAL_MODES.includes(o.approvalMode as ApprovalMode) ? (o.approvalMode as ApprovalMode) : DEFAULT_TUNING.approvalMode,
- maxAgentDeployments: int(o.maxAgentDeployments, 1, 16, DEFAULT_TUNING.maxAgentDeployments),
- maxRunMinutes: int(o.maxRunMinutes, 1, 24 * 60, DEFAULT_TUNING.maxRunMinutes),
- maxSweepMinutes: int(o.maxSweepMinutes, 1, 7 * 24 * 60, DEFAULT_TUNING.maxSweepMinutes),
- maxSweepVariants: int(o.maxSweepVariants, 2, 16, DEFAULT_TUNING.maxSweepVariants),
- allowedRuntimeIds: Array.isArray(o.allowedRuntimeIds) ? o.allowedRuntimeIds.filter((x): x is string => typeof x === "string" && x.length <= 64) : [],
- allowedArgs: { "llama.cpp": flags(args["llama.cpp"], DEFAULT_ALLOWED_ARGS["llama.cpp"]), vllm: flags(args.vllm, DEFAULT_ALLOWED_ARGS.vllm) },
- hostPortRange: from && to && from <= to ? { from, to } : null,
- maxMemoryMb: numOrNull(o.maxMemoryMb, 256),
- maxCpus: numOrNull(o.maxCpus, 0.1),
- };
-}
-
-/** "--no-mmap -ctk, --flash-attn" → flags; throws on something that isn't one. */
-export function parseFlagList(text: string): string[] {
- const out: string[] = [];
- for (const f of text.split(/[\s,]+/).filter(Boolean)) {
- if (!FLAG_RE.test(f)) throw new Error(`"${f}" isn't a flag (e.g. --no-mmap).`);
- if (!out.includes(f)) out.push(f);
- }
- return out;
-}
-
-/**
- * Extra arguments: every flag must be on the engine's allowlist, every value must follow a flag and
- * may not be a path or URL. The error names the offending argument.
- */
-export function checkArgs(g: TuningGuardrails, engine: RuntimeEngine, args: string[]): void {
- const allowed = g.allowedArgs[engine];
- let pending: string | null = null; // a flag still waiting for its value
- for (const raw of args) {
- const a = raw.trim();
- if (!a) continue;
- if (a.startsWith("-") && !/^-\d/.test(a)) {
- const flag = a.split("=")[0];
- if (!allowed.includes(flag)) {
- throw new TuningError(
- "arg_not_allowed",
- `extra argument "${flag}" isn't allowed for agents on ${engine}. The allowed flags are listed per runtime in GET /api/v1/runtimes (allowedExtraArgs); use the structured options (contextSize, gpuLayers, cacheTypeK, …) where there is one.`,
- 403,
- );
- }
- const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : null;
- if (value != null) checkValue(flag, value);
- pending = value == null ? flag : null;
- continue;
- }
- if (!pending) throw new TuningError("arg_not_allowed", `extra argument "${a}" isn't a value of a flag. Pass flags as "--flag value" or "--flag=value".`, 403);
- checkValue(pending, a);
- pending = null;
- }
-}
-
-function checkValue(flag: string, value: string) {
- if (/^[/~]|(^|[\\/])\.\.([\\/]|$)|:\/\//.test(value)) {
- throw new TuningError("arg_not_allowed", `value "${value}" of ${flag} looks like a path or URL; agents can't pass those.`, 403);
- }
-}
-
-/** A host port must be in the configured range (none configured: no host ports for agents). */
-export function checkHostPort(g: TuningGuardrails, port: number | null | undefined): void {
- if (port == null) return;
- const r = g.hostPortRange;
- if (!r) throw new TuningError("port_not_allowed", "agents can't publish host ports (none configured). Leave hostPort out; Kaname reaches the deployment itself.", 403);
- if (port < r.from || port > r.to) throw new TuningError("port_not_allowed", `host port ${port} is outside the range agents may use (${r.from}–${r.to}).`, 403);
-}
-
-/** Memory and CPU limits within the caps (null cap: the host's size). Returns the memory limit to use. */
-export function checkLimits(
- g: TuningGuardrails,
- x: { memoryMb: number | null | undefined; cpus: number | null | undefined; estimateMb: number; hostMemoryMb: number | null; hostCpus: number | null },
-): { memoryMb: number; cpus: number | null } {
- const memCap = g.maxMemoryMb ?? x.hostMemoryMb;
- const cpuCap = g.maxCpus ?? x.hostCpus;
- const memoryMb = x.memoryMb ?? x.estimateMb;
- if (memCap != null && memoryMb > memCap) {
- throw new TuningError(
- "limit_exceeded",
- `memory limit ${memoryMb} MiB exceeds the cap of ${Math.floor(memCap)} MiB for agent deployments${x.memoryMb == null ? " (the estimate for this model and context)" : ""}. Use a smaller quant or context, or ask the user to raise the cap.`,
- );
- }
- if (x.cpus != null && cpuCap != null && x.cpus > cpuCap) throw new TuningError("limit_exceeded", `CPU limit ${x.cpus} exceeds the cap of ${cpuCap} cores for agent deployments.`);
- return { memoryMb, cpus: x.cpus ?? (g.maxCpus ?? null) };
-}
-
-export type GpuLoad = {
- /** Agent deployments running, starting or waiting to start (all tokens), not counting `self`. */
- agentDeployments: number;
- /** Agent runs and sweeps pending approval, queued or running. */
- agentRuns: number;
- /** Agent deployments currently starting (loading weights). */
- agentStarting: number;
-};
-
-/** Starting an agent deployment: within the count, and nothing of an agent is being measured or loaded. */
-export function checkStart(g: TuningGuardrails, load: GpuLoad): void {
- if (load.agentRuns > 0) {
- throw new TuningError("gpu_busy", "an agent benchmark or sweep is pending or running; starting a deployment now would disturb it. Wait for it (GET …?wait=) and start afterwards.", 429);
- }
- if (load.agentStarting > 0) throw new TuningError("gpu_busy", "another agent deployment is starting; wait until it is running.", 429);
- if (load.agentDeployments >= g.maxAgentDeployments) {
- throw new TuningError(
- "too_many_deployments",
- `${load.agentDeployments} agent deployment(s) already running or waiting to start; the limit is ${g.maxAgentDeployments}. Stop one of yours first (POST /api/v1/deployments/{id}/stop).`,
- 429,
- );
- }
-}
-
-/** Starting a run or sweep: one agent run/sweep at a time, and no agent deployment still loading. */
-export function checkRun(load: GpuLoad): void {
- if (load.agentRuns > 0) throw new TuningError("gpu_busy", "an agent benchmark or sweep is already pending or running; only one at a time. Wait for it to finish (GET …?wait=).", 429);
- if (load.agentStarting > 0) throw new TuningError("gpu_busy", "an agent deployment is still starting; wait until it is running.", 429);
-}
-
-/**
- * Starting next to a running protected deployment on the same GPUs: the estimated VRAM of everything
- * running there plus the new deployment must fit, with a margin, so the protected one isn't pushed out.
- */
-export function checkVram(x: { protectedNames: string[]; newMb: number | null; runningMb: number[]; totalMb: number | null; marginMb?: number }): void {
- if (x.protectedNames.length === 0) return;
- const names = x.protectedNames.join(", ");
- if (x.newMb == null || x.totalMb == null || x.runningMb.some((m) => m < 0)) {
- throw new TuningError(
- "vram_protected",
- `protected deployment(s) ${names} run on these GPUs and the VRAM need can't be estimated (only some layers on the GPU, or VRAM unknown). Use gpuLayers "auto" or "all", or ask the user.`,
- 409,
- );
- }
- const margin = x.marginMb ?? 1024;
- const used = x.runningMb.reduce((s, m) => s + m, 0);
- if (used + x.newMb + margin > x.totalMb) {
- throw new TuningError(
- "vram_protected",
- `would crowd protected deployment(s) ${names} out of VRAM: about ${x.newMb} MiB needed, ${used} MiB in use of ${x.totalMb} MiB (keeping ${margin} MiB free). Use a smaller quant or context, or a quantized KV cache.`,
- 409,
- );
- }
-}
-
-/** Seconds since `startedAt` past the limit? */
-export const overTime = (startedAt: Date | null, limitS: number | null, now = Date.now()) => !!startedAt && !!limitS && now - startedAt.getTime() > limitS * 1000;
-
-export function describeTuning(g: TuningGuardrails): string {
- return [
- g.approvalMode === "approve" ? "starts, runs and sweeps wait for approval" : "starts, runs and sweeps go ahead",
- `max ${g.maxAgentDeployments} agent deployment(s)`,
- "one agent run/sweep at a time",
- `runs ≤ ${g.maxRunMinutes} min, sweeps ≤ ${g.maxSweepMinutes} min and ${g.maxSweepVariants} variants`,
- g.allowedRuntimeIds.length ? `${g.allowedRuntimeIds.length} allowed runtime(s)` : "any pulled runtime",
- g.hostPortRange ? `host ports ${g.hostPortRange.from}–${g.hostPortRange.to}` : "no host ports",
- ].join(" · ");
-}
diff --git a/src/lib/agent.test.ts b/src/lib/agent.test.ts
deleted file mode 100644
index 7507394..0000000
--- a/src/lib/agent.test.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { describe, it } from "node:test";
-import { checkAuthor, checkGuardrails, DEFAULT_GUARDRAILS, type GuardrailError, type GuardrailInput, parseAuthorList, parseGuardrails } from "./agent-guardrails";
-import { newPaths, quantSummary, resolveRequestPaths } from "./agent-selection";
-import { bearerToken, generateToken, hashToken, isScope } from "./api-token-core";
-import { parseModelFilters } from "./api-v1-filters";
-import { EMPTY_FILTERS, facetValues, matchesFilters, type SearchableModel } from "./search";
-
-const GB = 1e9;
-
-describe("API tokens", () => {
- it("generates kn_ tokens whose hash and prefix match", () => {
- const t = generateToken();
- assert.match(t.token, /^kn_[A-Za-z0-9_-]{43}$/);
- assert.equal(t.hash, hashToken(t.token));
- assert.ok(t.token.startsWith(t.prefix));
- assert.notEqual(generateToken().token, t.token);
- });
-
- it("reads only well-formed bearer headers", () => {
- const { token } = generateToken();
- assert.equal(bearerToken(`Bearer ${token}`), token);
- assert.equal(bearerToken(`bearer ${token} `), token);
- assert.equal(bearerToken(token), null);
- assert.equal(bearerToken("Bearer kn_short"), null);
- assert.equal(bearerToken("Basic abc"), null);
- assert.equal(bearerToken(null), null);
- });
-
- it("knows the scopes", () => {
- assert.ok(isScope("models:read"));
- assert.ok(isScope("downloads:create"));
- assert.ok(!isScope("models:delete"));
- assert.ok(!isScope("settings:write"));
- });
-});
-
-describe("guardrails", () => {
- const ok: GuardrailInput = { repoId: "unsloth/Qwen3-8B-GGUF", requestBytes: 5 * GB, freeBytes: 500 * GB, reservedBytes: 0, openAgentJobs: 0 };
- const rejects = (g: Partial, x: Partial, code: GuardrailError["code"], message: RegExp) =>
- assert.throws(
- () => checkGuardrails({ ...DEFAULT_GUARDRAILS, ...g }, { ...ok, ...x }),
- (err: GuardrailError) => err.code === code && message.test(err.message),
- );
-
- it("defaults: approve, 60 GB, 100 GB free, 2 jobs, any author", () => {
- assert.deepEqual(parseGuardrails(null), DEFAULT_GUARDRAILS);
- assert.equal(DEFAULT_GUARDRAILS.approvalMode, "approve");
- assert.equal(DEFAULT_GUARDRAILS.maxRequestBytes, 60 * GB);
- assert.equal(DEFAULT_GUARDRAILS.minFreeBytes, 100 * GB);
- assert.equal(DEFAULT_GUARDRAILS.maxOpenJobs, 2);
- assert.deepEqual(DEFAULT_GUARDRAILS.allowedAuthors, []);
- });
-
- it("falls back to defaults for invalid stored values", () => {
- const g = parseGuardrails({ approvalMode: "yolo", maxRequestBytes: -1, minFreeBytes: "x", maxOpenJobs: 0, allowedAuthors: ["ok", "../bad"] });
- assert.equal(g.approvalMode, "approve");
- assert.equal(g.maxRequestBytes, DEFAULT_GUARDRAILS.maxRequestBytes);
- assert.equal(g.minFreeBytes, DEFAULT_GUARDRAILS.minFreeBytes);
- assert.equal(g.maxOpenJobs, DEFAULT_GUARDRAILS.maxOpenJobs);
- assert.deepEqual(g.allowedAuthors, ["ok"]);
- });
-
- it("passes a request within all limits", () => {
- checkGuardrails(DEFAULT_GUARDRAILS, ok);
- });
-
- it("rejects requests over the max size, with both sizes in the message", () => {
- rejects({}, { requestBytes: 74.2 * GB }, "too_large", /exceeds max size per request 60\.0 GB: requested 74\.2 GB/);
- });
-
- it("rejects when the minimum free space would not remain", () => {
- rejects({}, { requestBytes: 20 * GB, freeBytes: 110 * GB }, "disk_space", /at least 100\.0 GB must stay free/);
- });
-
- it("counts space reserved by other open downloads", () => {
- checkGuardrails(DEFAULT_GUARDRAILS, { ...ok, requestBytes: 20 * GB, freeBytes: 130 * GB });
- rejects({}, { requestBytes: 20 * GB, freeBytes: 130 * GB, reservedBytes: 20 * GB }, "disk_space", /20\.0 GB of it reserved/);
- });
-
- it("rejects when free space is unknown (worker offline)", () => {
- rejects({}, { freeBytes: null }, "disk_unknown", /worker is offline/);
- });
-
- it("rejects when too many agent jobs are open", () => {
- rejects({}, { openAgentJobs: 2 }, "too_many_jobs", /2 pending or running, the limit is 2/);
- checkGuardrails({ ...DEFAULT_GUARDRAILS, maxOpenJobs: 3 }, { ...ok, openAgentJobs: 2 });
- });
-
- it("enforces the author allowlist case-insensitively", () => {
- const g = { allowedAuthors: ["unsloth", "ggml-org"] };
- checkAuthor({ ...DEFAULT_GUARDRAILS, ...g }, "Unsloth/x");
- rejects(g, { repoId: "TheBloke/x-GGUF" }, "author_not_allowed", /author "TheBloke" is not on the allowlist \(unsloth, ggml-org\)/);
- });
-
- it("parses the allowlist text", () => {
- assert.deepEqual(parseAuthorList("unsloth, ggml-org Qwen,unsloth"), ["unsloth", "ggml-org", "Qwen"]);
- assert.deepEqual(parseAuthorList(" "), []);
- assert.throws(() => parseAuthorList("ok, ../x"), /not a valid/);
- });
-});
-
-describe("request file selection", () => {
- const files = [
- { path: "Qwen3-8B-Q4_K_M.gguf", size: 5 * GB },
- { path: "Qwen3-8B-Q8_0.gguf", size: 8.7 * GB },
- { path: "mmproj-F16.gguf", size: 0.6 * GB },
- { path: "BF16/Qwen3-8B-BF16-00001-of-00002.gguf", size: 8 * GB },
- { path: "BF16/Qwen3-8B-BF16-00002-of-00002.gguf", size: 8 * GB },
- { path: "README.md", size: 1000 },
- ];
-
- it("summarizes quants (weights only, split parts together)", () => {
- assert.deepEqual(
- quantSummary(files).map((q) => [q.quant, q.files]),
- [
- ["Q4_K_M", 1],
- ["Q8_0", 1],
- ["BF16", 2],
- ],
- );
- });
-
- it("resolves a quant to its weights plus recommended companions", () => {
- assert.deepEqual(resolveRequestPaths(files, { quant: "q4_k_m" }, ["vision"]), ["Qwen3-8B-Q4_K_M.gguf", "mmproj-F16.gguf"]);
- assert.deepEqual(resolveRequestPaths(files, { quant: "Q4_K_M" }, []), ["Qwen3-8B-Q4_K_M.gguf"]);
- assert.deepEqual(resolveRequestPaths(files, { quant: "BF16" }, []), ["BF16/Qwen3-8B-BF16-00001-of-00002.gguf", "BF16/Qwen3-8B-BF16-00002-of-00002.gguf"]);
- });
-
- it("explains a missing quant with the available ones", () => {
- assert.throws(() => resolveRequestPaths(files, { quant: "Q2_K" }, []), /quant "Q2_K" not found in this repo\. Available: .*Q4_K_M/);
- assert.throws(() => resolveRequestPaths([{ path: "model.safetensors", size: 1 }], { quant: "Q4_K_M" }, []), /no GGUF quants\. Use "include"/);
- });
-
- it("resolves include globs and rejects ones that match nothing", () => {
- assert.deepEqual(resolveRequestPaths(files, { include: ["*Q8_0*", "README.md"] }, []), ["Qwen3-8B-Q8_0.gguf", "README.md"]);
- assert.throws(() => resolveRequestPaths(files, { include: ["*.safetensors"] }, []), /no file in this repo matches/);
- });
-
- it("finds what a request adds to the selection", () => {
- assert.deepEqual(newPaths(["a", "b", "c"], ["b"]), ["a", "c"]);
- assert.deepEqual(newPaths(["a"], ["a", "b"]), []);
- });
-});
-
-describe("GET /api/v1/models filters", () => {
- it("reads repeated and comma-separated values, requested_by → requester", () => {
- const { query, filters } = parseModelFilters(new URLSearchParams("q=qwen 8b&author=unsloth,bartowski&quant=Q4_K_M&quant=Q8_0&requested_by=hermes&status=pending_approval"));
- assert.equal(query, "qwen 8b");
- assert.deepEqual(filters, { ...EMPTY_FILTERS, author: ["unsloth", "bartowski"], quant: ["Q4_K_M", "Q8_0"], requester: ["hermes"], status: ["pending_approval"] });
- });
-
- it("filters by requester and pending approval like the library", () => {
- const m: SearchableModel = {
- repoId: "unsloth/Qwen3-8B-GGUF",
- author: "unsloth",
- families: ["Qwen"],
- baseModels: [],
- architecture: null,
- quants: ["Q4_K_M"],
- tags: [],
- hubTags: [],
- pipelineTag: null,
- license: null,
- status: "pending",
- hubStatus: null,
- requestedBy: "hermes",
- pendingApproval: true,
- };
- assert.deepEqual(facetValues(m, "status"), ["pending", "pending_approval"]);
- assert.ok(matchesFilters(m, { ...EMPTY_FILTERS, requester: ["Hermes"] }));
- assert.ok(!matchesFilters({ ...m, requestedBy: null }, { ...EMPTY_FILTERS, requester: ["hermes"] }));
- });
-});
-
-describe("proxy", () => {
- // The OIDC gate must skip exactly /api/v1 (bearer tokens), nothing that merely starts like it.
- const src = readFileSync(new URL("../proxy.ts", import.meta.url), "utf8");
- const matcher = JSON.parse(`"${src.match(/matcher: \["([^"]+)"\]/)![1]}"`) as string;
- const gated = (path: string) => new RegExp(`^${matcher}$`).test(path);
-
- it("leaves /api/v1 to token auth and gates everything else", () => {
- assert.ok(!gated("/api/v1"));
- assert.ok(!gated("/api/v1/models"));
- assert.ok(!gated("/api/v1/jobs/01ABC"));
- assert.ok(gated("/api/v1x"));
- assert.ok(gated("/api/models"));
- assert.ok(gated("/api/api-tokens"));
- assert.ok(gated("/settings/api-tokens"));
- });
-});
diff --git a/src/lib/api-keys.ts b/src/lib/api-keys.ts
deleted file mode 100644
index bc47a45..0000000
--- a/src/lib/api-keys.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import "server-only";
-import { randomBytes } from "node:crypto";
-import { asc, eq } from "drizzle-orm";
-import { z } from "zod";
-import { db } from "@/lib/db/client";
-import { apiKeys } from "@/lib/db/schema";
-
-export class ApiKeyError extends Error {
- constructor(
- public code: "invalid" | "not_found" | "conflict",
- message: string,
- public status: number,
- ) {
- super(message);
- }
-}
-
-// No whitespace or commas: llama.cpp takes several keys as one comma-separated list.
-export const ApiKeyBody = z.object({
- name: z.string().trim().min(1).max(80),
- key: z
- .string()
- .trim()
- .min(16, "at least 16 characters")
- .max(256)
- .regex(/^[\x21-\x7e]+$/, "printable characters without spaces")
- .refine((k) => !k.includes(","), "no commas")
- .optional(),
-});
-
-export const generateApiKey = () => `sk-kaname-${randomBytes(24).toString("base64url")}`;
-
-/** "…" plus the last 4 characters: enough to tell keys apart without showing them. */
-const mask = (key: string) => `…${key.slice(-4)}`;
-
-export type ApiKeyRow = { id: string; name: string; hint: string; createdAt: number };
-
-export async function listApiKeys(): Promise {
- const rows = await db().select().from(apiKeys).orderBy(asc(apiKeys.createdAt));
- return rows.map((r) => ({ id: r.id, name: r.name, hint: mask(r.key), createdAt: r.createdAt.getTime() }));
-}
-
-/** Returns the full key once, so the user can copy it. */
-export async function createApiKey(input: z.infer) {
- const key = input.key ?? generateApiKey();
- const clash = await db().query.apiKeys.findFirst({ columns: { id: true }, where: eq(apiKeys.key, key) });
- if (clash) throw new ApiKeyError("conflict", "This key already exists.", 409);
- const [row] = await db().insert(apiKeys).values({ name: input.name, key }).returning();
- return { id: row.id, name: row.name, key, hint: mask(key), createdAt: row.createdAt.getTime() };
-}
-
-export async function deleteApiKey(id: string) {
- const res = await db().delete(apiKeys).where(eq(apiKeys.id, id)).returning({ id: apiKeys.id });
- if (res.length === 0) throw new ApiKeyError("not_found", "API key not found.", 404);
-}
-
-/** All key values (for runtime containers and Kaname's own requests to them). */
-export async function apiKeyValues(): Promise {
- return (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt))).map((r) => r.key);
-}
-
-/** One key's value, for "show key" in Settings. */
-export async function revealApiKey(id: string): Promise {
- const row = await db().query.apiKeys.findFirst({ columns: { key: true }, where: eq(apiKeys.id, id) });
- if (!row) throw new ApiKeyError("not_found", "API key not found.", 404);
- return row.key;
-}
diff --git a/src/lib/api-token-core.ts b/src/lib/api-token-core.ts
deleted file mode 100644
index 35eca0d..0000000
--- a/src/lib/api-token-core.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-// API token format, hashing and scope checks. Pure (no DB), shared by the server code and tests.
-
-import { createHash, randomBytes } from "node:crypto";
-import { TOKEN_SCOPES, type TokenScope } from "@/lib/db/schema";
-
-/** "kn_" + 32 random bytes as base64url (43 chars). */
-export const TOKEN_PREFIX = "kn_";
-const TOKEN_RE = /^kn_[A-Za-z0-9_-]{43}$/;
-/** Characters of the token kept for display ("kn_AbCd…"). */
-const DISPLAY_CHARS = 7;
-
-export const TOKEN_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,39}$/;
-
-export function generateToken(): { token: string; prefix: string; hash: string } {
- const token = TOKEN_PREFIX + randomBytes(32).toString("base64url");
- return { token, prefix: token.slice(0, DISPLAY_CHARS), hash: hashToken(token) };
-}
-
-/** SHA-256 is enough: the tokens are 256 random bits, not passwords that need a slow hash. */
-export function hashToken(token: string): string {
- return createHash("sha256").update(token).digest("hex");
-}
-
-/** The token from an `Authorization: Bearer …` header, or null if it's missing or malformed. */
-export function bearerToken(header: string | null): string | null {
- const m = header?.match(/^Bearer\s+(\S+)\s*$/i);
- return m && TOKEN_RE.test(m[1]) ? m[1] : null;
-}
-
-export function isScope(v: unknown): v is TokenScope {
- return typeof v === "string" && (TOKEN_SCOPES as readonly string[]).includes(v);
-}
diff --git a/src/lib/api-tokens.ts b/src/lib/api-tokens.ts
deleted file mode 100644
index f9fe045..0000000
--- a/src/lib/api-tokens.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import "server-only";
-import { and, desc, eq, isNotNull, isNull } from "drizzle-orm";
-import { NextResponse } from "next/server";
-import { bearerToken, generateToken, hashToken, isScope, TOKEN_NAME_RE } from "@/lib/api-token-core";
-import { db } from "@/lib/db/client";
-import { apiTokens, type TokenScope } from "@/lib/db/schema";
-
-export class TokenError extends Error {
- constructor(
- public code: "invalid" | "exists" | "not_found",
- message: string,
- public status = 400,
- ) {
- super(message);
- }
-}
-
-export type ApiTokenRow = Omit;
-
-/** lastUsedAt is written at most this often per token, not on every request. */
-const TOUCH_MS = 60_000;
-
-export async function listTokens(): Promise {
- return db()
- .select({
- id: apiTokens.id,
- name: apiTokens.name,
- prefix: apiTokens.prefix,
- scopes: apiTokens.scopes,
- lastUsedAt: apiTokens.lastUsedAt,
- revokedAt: apiTokens.revokedAt,
- createdAt: apiTokens.createdAt,
- })
- .from(apiTokens)
- .orderBy(desc(apiTokens.createdAt));
-}
-
-/** Create a token; the plain token is returned only here and never stored. */
-export async function createToken(name: string, scopes: string[]): Promise<{ id: string; token: string }> {
- const n = name.trim().toLowerCase();
- if (!TOKEN_NAME_RE.test(n)) throw new TokenError("invalid", "Name: 1–40 characters, lowercase letters, digits, . _ - (e.g. hermes).");
- const s = [...new Set(scopes)];
- if (s.length === 0 || !s.every(isScope)) throw new TokenError("invalid", "Pick at least one valid scope.");
- if (await db().query.apiTokens.findFirst({ columns: { id: true }, where: eq(apiTokens.name, n) })) {
- throw new TokenError("exists", `A token named "${n}" already exists. Delete it first or pick another name.`, 409);
- }
- const t = generateToken();
- const [row] = await db().insert(apiTokens).values({ name: n, prefix: t.prefix, hash: t.hash, scopes: s as TokenScope[] }).returning({ id: apiTokens.id });
- return { id: row.id, token: t.token };
-}
-
-export async function revokeToken(id: string): Promise {
- const res = await db().update(apiTokens).set({ revokedAt: new Date() }).where(and(eq(apiTokens.id, id), isNull(apiTokens.revokedAt))).returning({ id: apiTokens.id });
- if (res.length === 0) throw new TokenError("not_found", "Token not found or already revoked.", 404);
-}
-
-/** Change what an active token may do (takes effect on its next request). */
-export async function updateTokenScopes(id: string, scopes: string[]): Promise {
- const s = [...new Set(scopes)];
- if (s.length === 0 || !s.every(isScope)) throw new TokenError("invalid", "Pick at least one valid scope.");
- const res = await db()
- .update(apiTokens)
- .set({ scopes: s as TokenScope[] })
- .where(and(eq(apiTokens.id, id), isNull(apiTokens.revokedAt)))
- .returning({ id: apiTokens.id });
- if (res.length === 0) throw new TokenError("not_found", "Token not found or revoked.", 404);
-}
-
-/** Only revoked tokens can be deleted (frees the name; "requested by" labels keep it). */
-export async function deleteToken(id: string): Promise {
- const res = await db().delete(apiTokens).where(and(eq(apiTokens.id, id), isNotNull(apiTokens.revokedAt))).returning({ id: apiTokens.id });
- if (res.length === 0) throw new TokenError("not_found", "Revoke the token before deleting it.", 409);
-}
-
-export type TokenIdentity = { id: string; name: string; scopes: TokenScope[] };
-
-/** The active token behind a request's bearer header, or null. */
-export async function tokenFromRequest(req: Request): Promise {
- const token = bearerToken(req.headers.get("authorization"));
- if (!token) return null;
- const row = await db().query.apiTokens.findFirst({ where: and(eq(apiTokens.hash, hashToken(token)), isNull(apiTokens.revokedAt)) });
- if (!row) return null;
- if (!row.lastUsedAt || Date.now() - row.lastUsedAt.getTime() > TOUCH_MS) {
- await db().update(apiTokens).set({ lastUsedAt: new Date() }).where(eq(apiTokens.id, row.id));
- }
- return { id: row.id, name: row.name, scopes: row.scopes };
-}
-
-function v1Error(status: number, code: string, message: string) {
- return NextResponse.json({ error: { code, message } }, { status, headers: status === 401 ? { "WWW-Authenticate": 'Bearer realm="kaname"' } : undefined });
-}
-
-type Handler = (req: Request, ctx: Ctx & { token: TokenIdentity }) => Promise | Response;
-
-/**
- * Wraps a /api/v1 route: requires `Authorization: Bearer ` with `scope` (null: any valid
- * token). Login sessions don't count here; the rest of the app is OIDC-only.
- */
-export function withToken(scope: TokenScope | null, handler: Handler) {
- return async (req: Request, ctx: Ctx) => {
- const token = await tokenFromRequest(req);
- if (!token) {
- return v1Error(401, "unauthorized", "Missing or invalid API token. Send it as \"Authorization: Bearer kn_…\"; tokens are created in Kaname under Settings → API tokens.");
- }
- if (scope && !token.scopes.includes(scope)) {
- return v1Error(403, "forbidden", `This token lacks the scope "${scope}" (it has: ${token.scopes.join(", ")}). Ask the user to grant it in Settings → API tokens.`);
- }
- return handler(req, { ...ctx, token });
- };
-}
diff --git a/src/lib/api-v1-agent.test.ts b/src/lib/api-v1-agent.test.ts
deleted file mode 100644
index d17a93f..0000000
--- a/src/lib/api-v1-agent.test.ts
+++ /dev/null
@@ -1,581 +0,0 @@
-// /api/v1 deployments and benchmarks end to end against a temporary SQLite database (no worker, no
-// Docker: deployment states are set directly). Scopes, ownership, protected deployments, every
-// guardrail rejection, approval, the activity log and ?wait=.
-// Runs with `--conditions=react-server` (see package.json) so "server-only" modules load.
-
-import assert from "node:assert/strict";
-import { mkdtempSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { after, before, beforeEach, describe, it } from "node:test";
-import { eq, isNotNull } from "drizzle-orm";
-
-const dir = mkdtempSync(join(tmpdir(), "kaname-agent-"));
-process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
-process.env.MODELS_DIR = join(dir, "models");
-
-const GiB = 2 ** 30;
-
-type Mods = {
- db: typeof import("./db/client");
- schema: typeof import("./db/schema");
- tokens: typeof import("./api-tokens");
- settings: typeof import("./settings");
- deployments: typeof import("./deployments");
- v1: typeof import("../app/api/v1/route");
- runtimes: typeof import("../app/api/v1/runtimes/route");
- deps: typeof import("../app/api/v1/deployments/route");
- dep: typeof import("../app/api/v1/deployments/[id]/route");
- start: typeof import("../app/api/v1/deployments/[id]/start/route");
- stop: typeof import("../app/api/v1/deployments/[id]/stop/route");
- runs: typeof import("../app/api/v1/benchmarks/route");
- run: typeof import("../app/api/v1/benchmarks/[id]/route");
- cancel: typeof import("../app/api/v1/benchmarks/[id]/cancel/route");
- compare: typeof import("../app/api/v1/benchmarks/compare/route");
- sweeps: typeof import("../app/api/v1/sweeps/route");
-};
-let M: Mods;
-let hermes: string; // all scopes
-let other: string; // all scopes, another agent
-let downloadsOnly: string; // the 0.10 scopes
-let modelId: string;
-let sycl: string; // llama.cpp on /dev/dri, pulled
-let notPulled: string;
-let userProtected: string; // the user's own, protected, running on the GPU
-
-type Res = { status: number; body: Record }; // eslint-disable-line @typescript-eslint/no-explicit-any
-const call = async (handler: (req: Request, ctx: never) => Promise, path: string, opts: { token?: string; method?: string; body?: unknown; params?: Record } = {}): Promise => {
- const req = new Request(`http://kaname.test${path}`, {
- method: opts.method ?? (opts.body ? "POST" : "GET"),
- headers: { ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}), "Content-Type": "application/json" },
- body: opts.body ? JSON.stringify(opts.body) : undefined,
- });
- const res = await handler(req, { params: Promise.resolve(opts.params ?? {}) } as never);
- return { status: res.status, body: (await res.json()) as Res["body"] };
-};
-
-const deployBody = (o: Record = {}) => ({
- runtimeId: sycl,
- modelId,
- options: { modelFile: "Small-Q4_K_M.gguf", contextSize: 8192, extraArgs: [] as string[], ...((o.options as object) ?? {}) },
- ...Object.fromEntries(Object.entries(o).filter(([k]) => k !== "options")),
-});
-const create = (o: Record = {}, token = hermes) => call(M.deps.POST, "/api/v1/deployments", { token, body: deployBody(o) });
-const setState = async (id: string, state: "running" | "stopped" | "starting", desired: "running" | "stopped" = state === "stopped" ? "stopped" : "running") => {
- await M.db
- .db()
- .update(M.schema.deployments)
- .set({ state, desiredState: desired, startRequestedAt: null, containerName: state === "running" ? `kaname-test-${id.slice(-6)}` : null })
- .where(eq(M.schema.deployments.id, id));
-};
-const tuning = (t: Record) => M.settings.saveTuning(t);
-
-before(async () => {
- const { runMigrations } = await import("./db/migrate");
- await runMigrations();
- M = {
- db: await import("./db/client"),
- schema: await import("./db/schema"),
- tokens: await import("./api-tokens"),
- settings: await import("./settings"),
- deployments: await import("./deployments"),
- v1: await import("../app/api/v1/route"),
- runtimes: await import("../app/api/v1/runtimes/route"),
- deps: await import("../app/api/v1/deployments/route"),
- dep: await import("../app/api/v1/deployments/[id]/route"),
- start: await import("../app/api/v1/deployments/[id]/start/route"),
- stop: await import("../app/api/v1/deployments/[id]/stop/route"),
- runs: await import("../app/api/v1/benchmarks/route"),
- run: await import("../app/api/v1/benchmarks/[id]/route"),
- cancel: await import("../app/api/v1/benchmarks/[id]/cancel/route"),
- compare: await import("../app/api/v1/benchmarks/compare/route"),
- sweeps: await import("../app/api/v1/sweeps/route"),
- } as Mods;
- const scopes = ["models:read", "downloads:create", "deployments:read", "deployments:write", "benchmarks:read", "benchmarks:run"];
- hermes = (await M.tokens.createToken("hermes", scopes)).token;
- other = (await M.tokens.createToken("other", scopes)).token;
- downloadsOnly = (await M.tokens.createToken("old", ["models:read", "downloads:create"])).token;
-
- const d = M.db.db();
- const s = M.schema;
- const now = new Date();
- await d.insert(s.workerState).values({
- id: "worker",
- startedAt: now,
- heartbeatAt: now,
- docker: {
- connected: true,
- error: null,
- serverVersion: "29",
- os: "Debian",
- architecture: "x86_64",
- cpus: 32,
- memoryBytes: 64 * GiB,
- cpuModel: null,
- cpuFeatures: [],
- network: "kaname_default",
- modelsSource: { type: "bind", source: "/srv/models" },
- hardware: {
- gpus: [{ vendor: "intel", pciAddress: "0000:03:00.0", name: "Intel Arc Pro B65", vramMb: 32768, driver: "xe", driverVersion: null, linkCurrent: null, linkMax: null, barMb: 32768, rebar: true }],
- p2p: null,
- cpu: { model: null, cores: 16, threads: 32 },
- memoryBytes: 64 * GiB,
- kernel: null,
- virtualization: { vm: true, hypervisor: "KVM/QEMU" },
- storage: null,
- checkedAt: now.toISOString(),
- },
- checkedAt: now.toISOString(),
- },
- });
- const [model] = await d.insert(s.models).values({ repoId: "unsloth/Test-GGUF", pinnedSha: "a".repeat(40), localPath: "unsloth/Test-GGUF", status: "ready" }).returning();
- modelId = model.id;
- await d.insert(s.modelFiles).values([
- { modelId, path: "Small-Q4_K_M.gguf", size: 4 * GiB, selected: true, state: "present" },
- { modelId, path: "Big-Q8_0.gguf", size: 20 * GiB, selected: true, state: "present" },
- ]);
- const [rt] = await d.insert(s.runtimes).values({ name: "llama.cpp (Intel SYCL)", engine: "llama.cpp", accelerator: "dri", image: "ghcr.io/ggml-org/llama.cpp:server-intel", imageState: "present" }).returning();
- sycl = rt.id;
- const [missing] = await d.insert(s.runtimes).values({ name: "vLLM (XPU)", engine: "vllm", accelerator: "dri", image: "vllm/vllm-openai-xpu:v0.31.0", imageState: "missing" }).returning();
- notPulled = missing.id;
- // The user's production deployment: 4 GiB model + KV at 32k ≈ 10 GiB of VRAM.
- const [prod] = await d
- .insert(s.deployments)
- .values({ name: "prod", runtimeId: sycl, modelId, options: { modelFile: "Small-Q4_K_M.gguf", contextSize: 32768, extraArgs: [] }, state: "running", desiredState: "running", protected: true })
- .returning();
- userProtected = prod.id;
-});
-
-after(() => {
- (globalThis as { __kanameDb?: { client?: { close(): void } } }).__kanameDb?.client?.close();
- try {
- rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
- } catch {
- // Windows may still hold the WAL file for a moment.
- }
-});
-
-/** Each test starts from: approval "approve", default limits, no agent deployments or runs. */
-beforeEach(async () => {
- if (!M) return;
- const d = M.db.db();
- const s = M.schema;
- await M.settings.saveTuning({ ...(await import("./agent-tuning")).DEFAULT_TUNING });
- await d.delete(s.deployments).where(isNotNull(s.deployments.requestedByTokenId));
- await d.delete(s.benchmarkRuns);
- await d.delete(s.benchmarkSweeps);
-});
-
-describe("scopes", () => {
- it("tokens from before 0.13 can't touch deployments or benchmarks", async () => {
- assert.equal((await call(M.deps.GET, "/api/v1/deployments", { token: downloadsOnly })).status, 403);
- assert.equal((await call(M.runtimes.GET, "/api/v1/runtimes", { token: downloadsOnly })).status, 403);
- const r = await call(M.deps.POST, "/api/v1/deployments", { token: downloadsOnly, body: deployBody() });
- assert.equal(r.status, 403);
- assert.match(r.body.error.message, /deployments:write/);
- assert.equal((await call(M.runs.GET, "/api/v1/benchmarks", { token: downloadsOnly })).status, 403);
- assert.equal((await call(M.runs.POST, "/api/v1/benchmarks", { token: downloadsOnly, body: { deploymentId: "x" } })).status, 403);
- assert.equal((await call(M.sweeps.POST, "/api/v1/sweeps", { token: downloadsOnly, body: {} })).status, 403);
- });
-
- it("read scopes don't allow writing", async () => {
- const reader = (await M.tokens.createToken("reader", ["deployments:read", "benchmarks:read"])).token;
- assert.equal((await call(M.deps.GET, "/api/v1/deployments", { token: reader })).status, 200);
- assert.equal((await call(M.deps.POST, "/api/v1/deployments", { token: reader, body: deployBody() })).status, 403);
- assert.equal((await call(M.start.POST, "/x", { token: reader, params: { id: userProtected } })).status, 403);
- assert.equal((await call(M.runs.POST, "/api/v1/benchmarks", { token: reader, body: { deploymentId: userProtected } })).status, 403);
- });
-
- it("lists pulled runtimes with what agents may use", async () => {
- const r = await call(M.runtimes.GET, "/api/v1/runtimes", { token: hermes });
- assert.equal(r.status, 200);
- assert.deepEqual(r.body.runtimes.map((x: { id: string }) => x.id), [sycl]);
- assert.ok(r.body.runtimes[0].allowedExtraArgs.includes("--no-mmap"));
- assert.equal(r.body.gpus[0].name, "Intel Arc Pro B65");
- });
-});
-
-describe("creating deployments", () => {
- it("dry run: the command and estimates, nothing created", async () => {
- const r = await create({ dryRun: true, options: { cacheTypeK: "q8_0", cacheTypeV: "q8_0" } });
- assert.equal(r.status, 200);
- assert.equal(r.body.dryRun, true);
- assert.match(r.body.command, /docker run .*llama\.cpp:server-intel .*-c 8192 .*-ctk q8_0/);
- assert.ok(r.body.estimates.vramMb > 4096 && r.body.estimates.vramMb < 32768);
- assert.equal(r.body.estimates.gpuVramMb, 32768);
- assert.ok(r.body.limits.memoryMb > 0);
- assert.equal((await call(M.deps.GET, "/api/v1/deployments?mine=1", { token: hermes })).body.count, 0);
- });
-
- it("waits for approval by default and records who asked", async () => {
- const r = await create();
- assert.equal(r.status, 201);
- assert.equal(r.body.state, "pending_approval");
- assert.match(r.body.message, /approval/);
- const d = await M.deployments.getDeployment(r.body.id);
- assert.equal(d?.desiredState, "stopped");
- assert.ok(d?.startRequestedAt);
- assert.equal(d?.requestedBy, "hermes");
- assert.ok(d?.memoryMb, "agent deployments always get a memory limit");
- const view = await call(M.dep.GET, "/x", { token: hermes, params: { id: r.body.id } });
- assert.equal(view.body.state, "pending_approval");
- assert.equal(view.body.mine, true);
- // The user approves (Start in the UI): it starts.
- await M.deployments.setDesiredState(r.body.id, "running");
- assert.equal((await M.deployments.getDeployment(r.body.id))?.desiredState, "running");
- });
-
- it("starts right away in automatic mode", async () => {
- await tuning({ approvalMode: "auto" });
- const r = await create();
- assert.equal(r.body.state, "starting");
- assert.equal((await M.deployments.getDeployment(r.body.id))?.desiredState, "running");
- });
-
- it("can be created stopped", async () => {
- const r = await create({ start: false });
- assert.equal(r.body.state, "stopped");
- });
-
- it("rejects unknown fields instead of ignoring them", async () => {
- const r = await create({ options: { gpuLayerz: "all" } });
- assert.equal(r.status, 400);
- assert.equal(r.body.error.code, "invalid_request");
- assert.match(r.body.error.message, /gpuLayerz/);
- });
-});
-
-describe("deployment guardrails", () => {
- it("runtime not pulled / not on the allowlist", async () => {
- const r = await create({ runtimeId: notPulled, options: { modelFile: "" } });
- assert.equal(r.body.error.code, "runtime_not_pulled");
- await tuning({ allowedRuntimeIds: ["something-else"] });
- const a = await create();
- assert.equal(a.status, 403);
- assert.equal(a.body.error.code, "runtime_not_allowed");
- });
-
- it("extra arguments outside the allowlist, naming the argument", async () => {
- const r = await create({ options: { extraArgs: ["--host", "0.0.0.0"] } });
- assert.equal(r.status, 403);
- assert.equal(r.body.error.code, "arg_not_allowed");
- assert.match(r.body.error.message, /"--host"/);
- const p = await create({ options: { extraArgs: ["--chat-template", "/models/../etc/passwd"] } });
- assert.equal(p.body.error.code, "arg_not_allowed");
- assert.equal((await create({ dryRun: true, options: { extraArgs: ["--no-mmap", "-ctk", "q8_0"] } })).status, 200);
- });
-
- it("host ports outside the configured range", async () => {
- const r = await create({ hostPort: 18080 });
- assert.equal(r.status, 403);
- assert.equal(r.body.error.code, "port_not_allowed");
- await tuning({ hostPortRange: { from: 18000, to: 18099 } });
- assert.equal((await create({ hostPort: 18080, dryRun: true })).status, 200);
- assert.equal((await create({ hostPort: 18100, dryRun: true })).body.error.code, "port_not_allowed");
- });
-
- it("memory and CPU caps", async () => {
- await tuning({ maxMemoryMb: 4096, maxCpus: 4 });
- const big = await create({ options: { modelFile: "Big-Q8_0.gguf" } });
- assert.equal(big.body.error.code, "limit_exceeded");
- assert.match(big.body.error.message, /the estimate/);
- assert.equal((await create({ memoryMb: 8192 })).body.error.code, "limit_exceeded");
- assert.equal((await create({ cpus: 8 })).body.error.code, "limit_exceeded");
- });
-
- it("one agent deployment at a time (pending ones count)", async () => {
- assert.equal((await create()).status, 201);
- const second = await create();
- assert.equal(second.status, 429);
- assert.equal(second.body.error.code, "too_many_deployments");
- // Creating a stopped one is fine; starting it isn't.
- const stopped = await create({ start: false });
- assert.equal(stopped.status, 201);
- const s = await call(M.start.POST, "/x", { token: hermes, params: { id: stopped.body.id } });
- assert.equal(s.body.error.code, "too_many_deployments");
- });
-
- it("no start while an agent deployment is still loading or an agent run is open", async () => {
- await tuning({ maxAgentDeployments: 3 });
- const a = await create();
- await setState(a.body.id, "starting");
- assert.equal((await create()).body.error.code, "gpu_busy");
- await setState(a.body.id, "running");
- await M.db.db().insert(M.schema.benchmarkRuns).values({
- deploymentId: a.body.id,
- modelId,
- settings: { quick: true, passes: null, warmup: null, phases: [] },
- snapshot: { deploymentName: "x", repoId: "x", runtimeName: "x", engine: "llama.cpp", image: "x", imageId: null, options: { modelFile: "", contextSize: 1, extraArgs: [] }, cpus: null, memoryMb: null, command: "" },
- state: "running",
- requestedByTokenId: "someone",
- requestedBy: "other",
- });
- const r = await create();
- assert.equal(r.body.error.code, "gpu_busy");
- assert.match(r.body.error.message, /benchmark or sweep/);
- });
-
- it("can't crowd a running protected deployment out of VRAM", async () => {
- await tuning({ approvalMode: "auto" });
- // prod ≈ 10 GiB; the 20 GB Q8_0 at 8k context needs ~22 GiB more: over 32 GiB.
- const big = await create({ options: { modelFile: "Big-Q8_0.gguf" } });
- assert.equal(big.status, 409);
- assert.equal(big.body.error.code, "vram_protected");
- assert.match(big.body.error.message, /prod/);
- // Partial offload can't be estimated next to a protected deployment.
- assert.equal((await create({ options: { gpuLayers: "20" } })).body.error.code, "vram_protected");
- // The small one fits.
- assert.equal((await create()).status, 201);
- });
-});
-
-describe("ownership and protection", () => {
- it("agents can't change, start, stop or delete the user's or another token's deployments", async () => {
- for (const [handler, method] of [
- [M.start.POST, "POST"],
- [M.stop.POST, "POST"],
- [M.dep.DELETE, "DELETE"],
- ] as const) {
- const r = await call(handler, "/x", { token: hermes, method, params: { id: userProtected } });
- assert.equal(r.status, 403);
- assert.equal(r.body.error.code, "protected");
- }
- const theirs = await create({ start: false }, other);
- const r = await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 4096 } }, params: { id: theirs.body.id } });
- assert.equal(r.body.error.code, "not_owner");
- assert.equal((await call(M.stop.POST, "/x", { token: hermes, params: { id: theirs.body.id } })).body.error.code, "not_owner");
- });
-
- it("not even their own once the user protects it", async () => {
- const mine = await create({ start: false });
- await M.deployments.setProtected(mine.body.id, true);
- const r = await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 4096 } }, params: { id: mine.body.id } });
- assert.equal(r.body.error.code, "protected");
- });
-
- it("edits, stops and deletes their own deployments", async () => {
- const mine = await create({ start: false });
- const p = await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 16384, extraArgs: ["--no-mmap"] } }, params: { id: mine.body.id } });
- assert.equal(p.status, 200);
- assert.equal(p.body.deployment.options.contextSize, 16384);
- assert.match(p.body.command, /-c 16384 .*--no-mmap/);
- // Changing a running deployment needs a stop first.
- await setState(mine.body.id, "running");
- assert.equal((await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 4096 } }, params: { id: mine.body.id } })).body.error.code, "busy");
- assert.equal((await call(M.stop.POST, "/x", { token: hermes, params: { id: mine.body.id } })).status, 200);
- assert.equal((await M.deployments.getDeployment(mine.body.id))?.desiredState, "stopped");
- assert.equal((await call(M.dep.DELETE, "/x", { token: hermes, method: "DELETE", params: { id: mine.body.id } })).status, 200);
- assert.equal(await M.deployments.getDeployment(mine.body.id), null);
- });
-});
-
-describe("benchmark runs and sweeps", () => {
- async function runningOwn(token = hermes) {
- const d = await create({ start: false }, token);
- await setState(d.body.id, "running");
- return d.body.id as string;
- }
-
- it("only on the token's own, unprotected deployments", async () => {
- const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: userProtected } });
- assert.equal(r.body.error.code, "protected");
- const theirs = await runningOwn(other);
- assert.equal((await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: theirs } })).body.error.code, "not_owner");
- });
-
- it("waits for approval, with the time limit, and one at a time", async () => {
- const id = await runningOwn();
- const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: id, quick: true, description: "baseline" } });
- assert.equal(r.status, 201);
- assert.equal(r.body.state, "pending_approval");
- const row = await M.db.db().query.benchmarkRuns.findFirst({ where: eq(M.schema.benchmarkRuns.id, r.body.id) });
- assert.equal(row?.timeLimitS, 30 * 60);
- assert.equal(row?.requestedBy, "hermes");
- const second = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: id } });
- assert.equal(second.status, 429);
- assert.equal(second.body.error.code, "gpu_busy");
- // Cancelling is for the token that started it.
- assert.equal((await call(M.cancel.POST, "/x", { token: other, params: { id: r.body.id } })).body.error.code, "not_owner");
- assert.equal((await call(M.cancel.POST, "/x", { token: hermes, params: { id: r.body.id } })).status, 200);
- const view = await call(M.run.GET, "/x", { token: hermes, params: { id: r.body.id } });
- assert.equal(view.body.state, "cancelled");
- });
-
- it("a stopped deployment can't be benchmarked", async () => {
- const d = await create({ start: false });
- const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: d.body.id } });
- assert.equal(r.status, 409);
- assert.match(r.body.error.message, /running server/);
- });
-
- it("sweeps: within the variant limit, with no agent deployment running", async () => {
- const base = await create({ start: false });
- const many = await call(M.sweeps.POST, "/api/v1/sweeps", {
- token: hermes,
- body: { baseDeploymentId: base.body.id, params: [{ key: "contextSize", values: ["1024", "2048", "4096"] }, { key: "kvCache", values: ["f16", "q8_0", "q4_0"] }] },
- });
- assert.equal(many.body.error.code, "too_many_variants");
- const running = await runningOwn();
- const busy = await call(M.sweeps.POST, "/api/v1/sweeps", { token: hermes, body: { baseDeploymentId: base.body.id, params: [{ key: "kvCache", values: ["f16", "q8_0"] }] } });
- assert.equal(busy.body.error.code, "gpu_busy");
- await setState(running, "stopped");
- const ok = await call(M.sweeps.POST, "/api/v1/sweeps", { token: hermes, body: { baseDeploymentId: base.body.id, params: [{ key: "kvCache", values: ["f16", "q8_0"] }] } });
- assert.equal(ok.status, 201);
- assert.equal(ok.body.state, "pending_approval");
- assert.equal(ok.body.variants, 2);
- const row = await M.db.db().query.benchmarkSweeps.findFirst({ where: eq(M.schema.benchmarkSweeps.id, ok.body.id) });
- assert.equal(row?.timeLimitS, 180 * 60);
- assert.equal(row?.runTimeLimitS, 30 * 60);
- });
-
- it("compares runs: headline numbers and what differs", async () => {
- const id = await runningOwn();
- const ids: string[] = [];
- for (const decode of [100, 120]) {
- const [r] = await M.db
- .db()
- .insert(M.schema.benchmarkRuns)
- .values({
- deploymentId: id,
- modelId,
- settings: { quick: false, passes: null, warmup: null, phases: [] },
- snapshot: { deploymentName: "x", repoId: "x", runtimeName: "x", engine: "llama.cpp", image: "x", imageId: null, options: { modelFile: "", contextSize: 1, extraArgs: [] }, cpus: null, memoryMb: null, command: "" },
- state: "completed",
- summary: { combined: { decode, ttft_p50: 50, itl_low1: null, update_p50: null, update_p99: null }, single: [], prefill: [], concurrency: [], phases: [], cacheHits: 0, betterbenchVersion: "0.6.1", corpusVersion: "1", passes: 20, quick: false },
- meta: {
- v: 1,
- gpus: [],
- p2p: "n/a",
- rebar: null,
- runtime: { image: "x", tag: null, digest: null, engine: "llama.cpp", engineName: "llama.cpp", engineVersion: "b1" },
- model: { repoId: "a/b", file: null, quant: "Q4_K_M", kvCache: decode === 100 ? "f16" : "q8_0" },
- contextSize: 8192,
- concurrency: 4,
- overridden: [],
- },
- })
- .returning();
- ids.push(r.id);
- }
- const c = await call(M.compare.GET, `/api/v1/benchmarks/compare?ids=${ids.join(",")}`, { token: hermes });
- assert.equal(c.status, 200);
- assert.deepEqual(c.body.runs.map((r: { headline: { decodeTps: number } }) => r.headline.decodeTps), [100, 120]);
- assert.deepEqual(Object.keys(c.body.runs[0].differs), ["model"]);
- assert.equal(c.body.same.ctx, "8,192");
- });
-});
-
-describe("?wait=", () => {
- it("returns as soon as a starting deployment is running", async () => {
- await tuning({ approvalMode: "auto" });
- const d = await create();
- await setState(d.body.id, "starting");
- setTimeout(() => void setState(d.body.id, "running"), 300);
- const t0 = Date.now();
- const r = await call(M.dep.GET, `/api/v1/deployments/${d.body.id}?wait=10`, { token: hermes, params: { id: d.body.id } });
- assert.equal(r.body.state, "running");
- assert.equal(r.body.timedOut, false);
- assert.ok(Date.now() - t0 < 5000);
- });
-
- it("gives up after the wait and says so", async () => {
- const d = await create({ start: false });
- await setState(d.body.id, "starting");
- const r = await call(M.dep.GET, `/api/v1/deployments/${d.body.id}?wait=1`, { token: hermes, params: { id: d.body.id } });
- assert.equal(r.body.state, "starting");
- assert.equal(r.body.timedOut, true);
- assert.equal(r.body.waitedSeconds, 1);
- });
-
- it("doesn't wait on something that waits for approval", async () => {
- const d = await create();
- const t0 = Date.now();
- const r = await call(M.dep.GET, `/api/v1/deployments/${d.body.id}?wait=60`, { token: hermes, params: { id: d.body.id } });
- assert.equal(r.body.state, "pending_approval");
- assert.ok(Date.now() - t0 < 2000);
- });
-
- it("waits on a run until it finishes", async () => {
- const dep = await create({ start: false });
- await setState(dep.body.id, "running");
- await tuning({ approvalMode: "auto" });
- const run = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: dep.body.id } });
- assert.equal(run.body.state, "queued");
- setTimeout(
- // A drizzle query only runs once it is awaited.
- async () => await M.db.db().update(M.schema.benchmarkRuns).set({ state: "completed", finishedAt: new Date() }).where(eq(M.schema.benchmarkRuns.id, run.body.id)),
- 300,
- );
- const r = await call(M.run.GET, `/api/v1/benchmarks/${run.body.id}?wait=10`, { token: hermes, params: { id: run.body.id } });
- assert.equal(r.body.state, "completed");
- });
-});
-
-describe("activity log", () => {
- it("records requests and refusals with the error code", async () => {
- await create();
- await create({ options: { extraArgs: ["--host", "x"] } });
- const tokenId = (await M.tokens.listTokens()).find((t) => t.name === "hermes")!.id;
- const rows = await (await import("./agent-activity")).listActivity(tokenId, 10);
- assert.equal(rows[0].outcome, "refused");
- assert.equal(rows[0].code, "arg_not_allowed");
- assert.equal(rows[1].action, "deployment.create");
- assert.equal(rows[1].outcome, "pending_approval");
- assert.equal(rows[1].targetType, "deployment");
- });
-});
-
-describe("the index", () => {
- it("shows the deployment guardrails and the new endpoints", async () => {
- const r = await call(M.v1.GET, "/api/v1", { token: hermes });
- assert.equal(r.body.deploymentGuardrails.maxAgentDeployments, 1);
- assert.equal(r.body.deploymentGuardrails.maxRunMinutes, 30);
- assert.ok(r.body.endpoints.some((e: string) => e.includes("/api/v1/deployments/{id}[?wait=600]")));
- });
-});
-
-describe("quality eval through the API", () => {
- it("requests an eval run on the token's own deployment and reads its score", async () => {
- const d = await create({ start: false });
- await setState(d.body.id, "running");
- const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { kind: "eval", deploymentId: d.body.id, sections: ["tools", "retrieval"] } });
- assert.equal(r.status, 201);
- assert.equal(r.body.state, "pending_approval");
- const row = await M.db.db().query.benchmarkRuns.findFirst({ where: eq(M.schema.benchmarkRuns.id, r.body.id) });
- assert.equal(row?.kind, "eval");
- assert.deepEqual(row?.settings.evalSections, ["tools", "retrieval"]);
- await M.db
- .db()
- .update(M.schema.benchmarkRuns)
- .set({
- state: "completed",
- quality: {
- evalSet: "kaname-eval-1",
- score: 75,
- sections: [
- { section: "tools", passed: 9, total: 12, score: 75, seconds: 20 },
- { section: "retrieval", passed: 0, total: 0, score: null, unsupported: "the context length is unknown", seconds: 0 },
- ],
- items: [{ section: "tools", id: "timer-12", pass: false, detail: "no tool call" }],
- config: { temperature: 0, seed: 1, thinking: false, contextTokens: null },
- },
- })
- .where(eq(M.schema.benchmarkRuns.id, r.body.id));
- const v = await call(M.run.GET, "/x", { token: hermes, params: { id: r.body.id } });
- assert.deepEqual(v.body.quality, { evalSet: "kaname-eval-1", score: 75, sections: { tools: "9/12", retrieval: "n/a (the context length is unknown)" } });
- const full = await call(M.run.GET, `/api/v1/benchmarks/${r.body.id}?full=1`, { token: hermes, params: { id: r.body.id } });
- assert.equal(full.body.failed[0].id, "timer-12");
- });
-
- it("refuses unknown sections, and sweeps can add the eval per variant", async () => {
- const d = await create({ start: false });
- await setState(d.body.id, "running");
- const bad = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { kind: "eval", deploymentId: d.body.id, sections: ["vibes"] } });
- assert.equal(bad.status, 400);
- await setState(d.body.id, "stopped");
- const s = await call(M.sweeps.POST, "/api/v1/sweeps", { token: hermes, body: { baseDeploymentId: d.body.id, quality: true, params: [{ key: "kvCache", values: ["f16", "q8_0"] }] } });
- assert.equal(s.status, 201);
- const row = await M.db.db().query.benchmarkSweeps.findFirst({ where: eq(M.schema.benchmarkSweeps.id, s.body.id) });
- assert.equal(row?.settings.quality, true);
- });
-});
diff --git a/src/lib/api-v1-filters.ts b/src/lib/api-v1-filters.ts
deleted file mode 100644
index 02e204d..0000000
--- a/src/lib/api-v1-filters.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-// Query-string filters for GET /api/v1/models, with the library's search semantics
-// (terms AND-ed in `q`; OR within a facet, AND across facets). Pure.
-
-import { EMPTY_FILTERS, type Facet, type Filters } from "@/lib/search";
-
-/** Query parameter per facet; each may repeat or hold a comma-separated list. */
-const PARAM: Record = {
- author: "author",
- family: "family",
- quant: "quant",
- tag: "tag",
- status: "status",
- requester: "requested_by",
-};
-
-export function parseModelFilters(params: URLSearchParams): { query: string; filters: Filters } {
- const filters = { ...EMPTY_FILTERS };
- for (const facet of Object.keys(PARAM) as Facet[]) {
- filters[facet] = params
- .getAll(PARAM[facet])
- .flatMap((v) => v.split(","))
- .map((v) => v.trim())
- .filter(Boolean);
- }
- return { query: params.get("q")?.trim() ?? "", filters };
-}
diff --git a/src/lib/api-v1.test.ts b/src/lib/api-v1.test.ts
deleted file mode 100644
index 77ec5e1..0000000
--- a/src/lib/api-v1.test.ts
+++ /dev/null
@@ -1,306 +0,0 @@
-// /api/v1 end to end against a temporary SQLite database and a stubbed Hugging Face API:
-// token auth, scopes, every guardrail rejection, idempotency, approve/reject.
-// Runs with `--conditions=react-server` (see package.json) so "server-only" modules load.
-
-import assert from "node:assert/strict";
-import { mkdtempSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { after, before, describe, it } from "node:test";
-
-const dir = mkdtempSync(join(tmpdir(), "kaname-api-"));
-process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
-process.env.MODELS_DIR = join(dir, "models");
-delete process.env.HF_TOKEN;
-
-const GB = 1e9;
-const SHA = { a: "a".repeat(40), b: "b".repeat(40), c: "c".repeat(40), d: "d".repeat(40) };
-
-/** Fake Hub: repo → commit + files. */
-const REPOS: Record = {
- "unsloth/Test-GGUF": {
- sha: SHA.a,
- files: [
- ["Test-Q4_K_M.gguf", 5 * GB],
- ["Test-Q8_0.gguf", 9 * GB],
- ["Test-F16.gguf", 70 * GB],
- ["README.md", 1000],
- ],
- },
- "unsloth/Other-GGUF": { sha: SHA.b, files: [["Other-Q4_K_M.gguf", 2 * GB]] },
- "ggml-org/Third-GGUF": { sha: SHA.c, files: [["Third-Q4_K_M.gguf", 3 * GB]] },
- "TheBloke/Old-GGUF": { sha: SHA.d, files: [["Old-Q4_K_M.gguf", 1 * GB]] },
-};
-
-const realFetch = globalThis.fetch;
-globalThis.fetch = (async (input: string | URL | Request) => {
- const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
- const m = url.pathname.match(/^\/api\/models\/([^/]+\/[^/]+)\/(revision|tree)\/([^/]+)/);
- // Like the Hub: repo ids are case-insensitive, the response has the canonical one.
- const id = m && Object.keys(REPOS).find((k) => k.toLowerCase() === decodeURIComponent(m[1]).toLowerCase());
- const repo = id && REPOS[id];
- if (!m || !id || !repo) return new Response("not found", { status: 404 });
- const rev = decodeURIComponent(m[3]);
- if (rev !== "main" && rev !== repo.sha) return new Response("", { status: 404, headers: { "x-error-code": "RevisionNotFound" } });
- if (m[2] === "revision") return Response.json({ id, sha: repo.sha, gated: false, private: false, tags: [] });
- return Response.json(repo.files.map(([path, size]) => ({ type: "file", path, size, oid: "0".repeat(40), lfs: { oid: "e".repeat(64), size } })));
-}) as typeof fetch;
-
-type Mods = {
- db: typeof import("./db/client");
- schema: typeof import("./db/schema");
- tokens: typeof import("./api-tokens");
- settings: typeof import("./settings");
- agent: typeof import("./agent-downloads");
- v1: typeof import("../app/api/v1/route");
- downloads: typeof import("../app/api/v1/downloads/route");
- job: typeof import("../app/api/v1/jobs/[id]/route");
- models: typeof import("../app/api/v1/models/route");
- disk: typeof import("../app/api/v1/disk/route");
-};
-let M: Mods;
-let full: string; // models:read + downloads:create
-let readOnly: string;
-
-const call = async (handler: (req: Request, ctx: never) => Promise, path: string, opts: { token?: string; body?: unknown; params?: Record } = {}) => {
- const req = new Request(`http://kaname.test${path}`, {
- method: opts.body ? "POST" : "GET",
- headers: { ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}), "Content-Type": "application/json" },
- body: opts.body ? JSON.stringify(opts.body) : undefined,
- });
- const res = await handler(req, { params: Promise.resolve(opts.params ?? {}) } as never);
- return { status: res.status, body: (await res.json()) as Record }; // eslint-disable-line @typescript-eslint/no-explicit-any
-};
-const request = (body: unknown, token = full) => call(M.downloads.POST, "/api/v1/downloads", { token, body });
-
-async function setFree(bytes: number) {
- const { db } = M.db;
- const now = new Date();
- await db()
- .insert(M.schema.workerState)
- .values({ id: "worker", startedAt: now, heartbeatAt: now, modelsDirFreeBytes: bytes, modelsDirTotalBytes: 2000 * GB })
- .onConflictDoUpdate({ target: M.schema.workerState.id, set: { heartbeatAt: now, modelsDirFreeBytes: bytes } });
-}
-
-before(async () => {
- const { runMigrations } = await import("./db/migrate");
- await runMigrations();
- M = {
- db: await import("./db/client"),
- schema: await import("./db/schema"),
- tokens: await import("./api-tokens"),
- settings: await import("./settings"),
- agent: await import("./agent-downloads"),
- v1: await import("../app/api/v1/route"),
- downloads: await import("../app/api/v1/downloads/route"),
- job: await import("../app/api/v1/jobs/[id]/route"),
- models: await import("../app/api/v1/models/route"),
- disk: await import("../app/api/v1/disk/route"),
- };
- full = (await M.tokens.createToken("hermes", ["models:read", "downloads:create"])).token;
- readOnly = (await M.tokens.createToken("reader", ["models:read"])).token;
- await setFree(500 * GB);
-});
-
-after(() => {
- globalThis.fetch = realFetch;
- // Close the database first; Windows can't delete an open file.
- (globalThis as { __kanameDb?: { client?: { close(): void } } }).__kanameDb?.client?.close();
- try {
- rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
- } catch {
- // Windows may still hold the WAL file for a moment; a leftover temp dir is harmless.
- }
-});
-
-describe("token auth", () => {
- it("rejects missing, malformed and unknown tokens with 401", async () => {
- assert.equal((await call(M.v1.GET, "/api/v1")).status, 401);
- assert.equal((await call(M.v1.GET, "/api/v1", { token: "kn_nope" })).status, 401);
- const unknown = (await import("./api-token-core")).generateToken().token;
- const r = await call(M.v1.GET, "/api/v1", { token: unknown });
- assert.equal(r.status, 401);
- assert.match(r.body.error.message, /Settings → API tokens/);
- });
-
- it("answers with the token's name, scopes and the guardrails", async () => {
- const r = await call(M.v1.GET, "/api/v1", { token: readOnly });
- assert.equal(r.status, 200);
- assert.deepEqual(r.body.token, { name: "reader", scopes: ["models:read"] });
- assert.equal(r.body.guardrails.approvalMode, "approve");
- assert.equal(r.body.guardrails.maxRequestSize, "60.0 GB");
- });
-
- it("enforces scopes with 403", async () => {
- const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q4_K_M" }, readOnly);
- assert.equal(r.status, 403);
- assert.match(r.body.error.message, /lacks the scope "downloads:create"/);
- assert.equal((await call(M.disk.GET, "/api/v1/disk", { token: readOnly })).status, 200);
- });
-
- it("records last use and stops accepting a revoked token", async () => {
- const t = await M.tokens.createToken("temp", ["models:read"]);
- assert.equal((await call(M.v1.GET, "/api/v1", { token: t.token })).status, 200);
- const row = (await M.tokens.listTokens()).find((x) => x.name === "temp")!;
- assert.ok(row.lastUsedAt);
- await M.tokens.revokeToken(t.id);
- assert.equal((await call(M.v1.GET, "/api/v1", { token: t.token })).status, 401);
- await M.tokens.deleteToken(t.id);
- });
-
- it("never stores the token itself", async () => {
- const rows = await M.db.db().select().from(M.schema.apiTokens);
- assert.ok(rows.every((r) => r.hash !== full && r.hash.length === 64 && !r.hash.startsWith("kn_")));
- });
-});
-
-describe("download requests", () => {
- let first: { modelId: string; jobId: string };
-
- it("validates the body", async () => {
- const r = await request({ repoId: "unsloth/Test-GGUF", sha: "main", quant: "Q4_K_M" });
- assert.equal(r.status, 400);
- assert.match(r.body.error.message, /40-character commit SHA/);
- assert.equal((await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a })).status, 400);
- assert.equal((await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q2_K" })).status, 400);
- });
-
- it("creates a model and a job that waits for approval, marked with the token name", async () => {
- const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q4_K_M", tags: ["agent"] });
- assert.equal(r.status, 201);
- assert.equal(r.body.state, "pending_approval");
- assert.equal(r.body.requestedSize, "5.0 GB");
- assert.deepEqual(r.body.files, ["Test-Q4_K_M.gguf"]);
- assert.match(r.body.message, /Do not retry/);
- first = { modelId: r.body.modelId, jobId: r.body.jobId };
-
- const job = await call(M.job.GET, `/api/v1/jobs/${first.jobId}`, { token: readOnly, params: { id: first.jobId } });
- assert.equal(job.body.state, "pending_approval");
- assert.equal(job.body.requestedBy, "hermes");
- assert.equal(job.body.log, undefined);
- assert.deepEqual(job.body.files.map((f: { path: string }) => f.path), ["Test-Q4_K_M.gguf"]);
-
- const model = await M.db.db().query.models.findFirst({ where: (m, { eq }) => eq(m.id, first.modelId) });
- assert.equal(model?.requestedBy, "hermes");
- assert.equal(model?.status, "pending"); // not "downloading" until approved
- });
-
- it("is idempotent: the same repo + commit + files returns the existing job", async () => {
- const r = await request({ repoId: "unsloth/test-gguf", sha: SHA.a, quant: "q4_k_m" });
- assert.equal(r.status, 200);
- assert.equal(r.body.created, false);
- assert.equal(r.body.jobId, first.jobId);
- const n = await M.db.db().select().from(M.schema.jobs);
- assert.equal(n.length, 1);
- });
-
- it("refuses other files while the model has an open job", async () => {
- const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q8_0" });
- assert.equal(r.status, 409);
- assert.match(r.body.error.message, /still pending approval/);
- });
-
- it("refuses a different commit of a model in the library", async () => {
- REPOS["unsloth/Test-GGUF"].sha = SHA.d;
- try {
- const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.d, quant: "Q4_K_M" });
- assert.equal(r.status, 409);
- assert.match(r.body.error.message, /pinned to commit a{40}.*Updating a model is done by the user/);
- } finally {
- REPOS["unsloth/Test-GGUF"].sha = SHA.a;
- }
- });
-
- it("rejects over the max agent jobs at once", async () => {
- const second = await request({ repoId: "unsloth/Other-GGUF", sha: SHA.b, quant: "Q4_K_M" });
- assert.equal(second.status, 201);
- const third = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
- assert.equal(third.status, 429);
- assert.equal(third.body.error.code, "too_many_jobs");
- assert.match(third.body.error.message, /2 pending or running, the limit is 2/);
- // Reject the second request again; the model it added leaves the library.
- assert.deepEqual(await M.agent.rejectJob(second.body.jobId), { removedModel: true });
- assert.equal(await M.db.db().query.models.findFirst({ where: (m, { eq }) => eq(m.id, second.body.modelId) }), undefined);
- });
-
- it("rejects requests over the max size", async () => {
- await M.settings.saveGuardrails({ maxOpenJobs: 10 });
- const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
- assert.equal(r.status, 201);
- await M.agent.rejectJob(r.body.jobId);
- await M.settings.saveGuardrails({ maxRequestBytes: 2.5 * GB });
- const big = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
- assert.equal(big.status, 422);
- assert.equal(big.body.error.message, "exceeds max size per request 2.5 GB: requested 3.0 GB. Pick a smaller quant or fewer files.");
- await M.settings.saveGuardrails({ maxRequestBytes: 60 * GB });
- });
-
- it("rejects when the minimum free space would not remain (counting reserved bytes)", async () => {
- await setFree(107 * GB); // 5 GB reserved by the pending first request
- const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
- assert.equal(r.status, 507);
- assert.equal(r.body.error.code, "disk_space");
- assert.match(r.body.error.message, /107\.0 GB free \(5\.0 GB of it reserved by other downloads\), and at least 100\.0 GB must stay free/);
- const disk = await call(M.disk.GET, "/api/v1/disk", { token: readOnly });
- assert.equal(disk.body.reservedBytes, 5 * GB);
- assert.equal(disk.body.availableForRequestsBytes, 2 * GB);
- await setFree(500 * GB);
- });
-
- it("rejects when the worker is offline (free space unknown)", async () => {
- const { db } = M.db;
- await db().update(M.schema.workerState).set({ heartbeatAt: new Date(0) });
- const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
- assert.equal(r.status, 503);
- assert.equal(r.body.error.code, "disk_unknown");
- await setFree(500 * GB);
- });
-
- it("rejects authors outside the allowlist before asking the Hub", async () => {
- await M.settings.saveGuardrails({ allowedAuthors: ["unsloth", "ggml-org"] });
- const r = await request({ repoId: "TheBloke/Old-GGUF", sha: SHA.d, quant: "Q4_K_M" });
- assert.equal(r.status, 403);
- assert.equal(r.body.error.code, "author_not_allowed");
- assert.match(r.body.error.message, /author "TheBloke" is not on the allowlist \(unsloth, ggml-org\)/);
- await M.settings.saveGuardrails({ allowedAuthors: [] });
- });
-
- it("approve queues the job; the model then shows as downloading", async () => {
- await M.agent.approveJob(first.jobId);
- const job = await call(M.job.GET, `/api/v1/jobs/${first.jobId}?log=5`, { token: readOnly, params: { id: first.jobId } });
- assert.equal(job.body.state, "queued");
- assert.ok(Array.isArray(job.body.log));
- await assert.rejects(M.agent.approveJob(first.jobId), /doesn't wait for approval/);
- });
-
- it("extra files of a finished model are added; rejecting restores the selection", async () => {
- const { db } = M.db;
- await db().update(M.schema.jobs).set({ state: "completed", finishedAt: new Date() }).where((await import("drizzle-orm")).eq(M.schema.jobs.id, first.jobId));
- const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q8_0" });
- assert.equal(r.status, 201);
- assert.equal(r.body.requestedSize, "9.0 GB");
- const selected = async () =>
- (await db().query.modelFiles.findMany({ where: (f, { and, eq }) => and(eq(f.modelId, first.modelId), eq(f.selected, true)) })).map((f) => f.path).sort();
- assert.deepEqual(await selected(), ["Test-Q4_K_M.gguf", "Test-Q8_0.gguf"]);
- assert.deepEqual(await M.agent.rejectJob(r.body.jobId), { removedModel: false });
- assert.deepEqual(await selected(), ["Test-Q4_K_M.gguf"]);
- });
-
- it("auto approval queues right away", async () => {
- await M.settings.saveGuardrails({ approvalMode: "auto" });
- const r = await request({ repoId: "unsloth/Other-GGUF", sha: SHA.b, include: ["*.gguf"] });
- assert.equal(r.status, 201);
- assert.equal(r.body.state, "queued");
- await M.settings.saveGuardrails({ approvalMode: "approve" });
- });
-
- it("lists models with the library filters, including requested_by", async () => {
- const all = await call(M.models.GET, "/api/v1/models", { token: readOnly });
- assert.equal(all.body.count, 2);
- const mine = await call(M.models.GET, "/api/v1/models?requested_by=hermes&quant=Q4_K_M&author=unsloth", { token: readOnly });
- assert.deepEqual(mine.body.models.map((m: { repoId: string }) => m.repoId).sort(), ["unsloth/Other-GGUF", "unsloth/Test-GGUF"]);
- assert.equal(mine.body.models[0].requestedBy, "hermes");
- const none = await call(M.models.GET, "/api/v1/models?requested_by=someone-else", { token: readOnly });
- assert.equal(none.body.count, 0);
- });
-});
diff --git a/src/lib/api-v1.ts b/src/lib/api-v1.ts
deleted file mode 100644
index f9eb83f..0000000
--- a/src/lib/api-v1.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import "server-only";
-import { NextResponse } from "next/server";
-import { z } from "zod";
-import { GuardrailError } from "@/lib/agent-guardrails";
-import { SelectionError } from "@/lib/agent-selection";
-import { TuningError } from "@/lib/agent-tuning";
-import { BenchmarkError } from "@/lib/benchmarks";
-import { DeploymentError } from "@/lib/deployments";
-import { SweepRequestError } from "@/lib/sweeps";
-import { HubError } from "@/lib/hub/client";
-import { JobError } from "@/lib/jobs";
-import { ModelError } from "@/lib/models";
-import { TagError } from "@/lib/tags";
-
-// Shared by the /api/v1 routes: compact JSON for an agent to read, errors as
-// { error: { code, message } } with a message that says what to do next.
-
-export function v1Json(data: unknown, status = 200) {
- return NextResponse.json(data, { status, headers: { "Cache-Control": "no-store" } });
-}
-
-export function v1Error(status: number, code: string, message: string) {
- return v1Json({ error: { code, message } }, status);
-}
-
-const HUB_STATUS: Partial> = {
- invalid_repo_id: 400,
- repo_not_found: 404,
- revision_not_found: 404,
- gated_no_token: 403,
- gated_no_access: 403,
- rate_limited: 429,
- network: 502,
-};
-
-/** Known errors → JSON; anything else is logged and becomes a generic 500 (no stack traces). */
-export function v1Catch(err: unknown) {
- if (err instanceof GuardrailError || err instanceof TuningError) return v1Error(err.status, err.code, err.message);
- if (err instanceof DeploymentError || err instanceof BenchmarkError || err instanceof SweepRequestError) return v1Error(err.status, err.code, err.message);
- if (err instanceof SelectionError) return v1Error(err.status, err.code, err.message);
- if (err instanceof ModelError || err instanceof JobError || err instanceof TagError) return v1Error(err.status, err.code, err.message);
- if (err instanceof HubError) return v1Error(HUB_STATUS[err.code] ?? 502, err.code, err.message);
- if (err instanceof z.ZodError) {
- return v1Error(400, "invalid_request", err.issues.map((i) => `${i.path.join(".") || "body"}: ${i.message}`).join("; "));
- }
- if (err instanceof SyntaxError) return v1Error(400, "invalid_json", "The request body is not valid JSON.");
- console.error("[api/v1]", err);
- return v1Error(500, "internal", "Internal error in Kaname. Tell the user; retrying won't help.");
-}
-
-/** "74.2 GB" next to byte counts, so a reader doesn't have to convert. */
-export function size(bytes: number | null | undefined): string | null {
- return bytes == null ? null : `${(bytes / 1e9).toFixed(1)} GB`;
-}
diff --git a/src/lib/benchmark-meta.test.ts b/src/lib/benchmark-meta.test.ts
index 77c46bc..2f19bbf 100644
--- a/src/lib/benchmark-meta.test.ts
+++ b/src/lib/benchmark-meta.test.ts
@@ -1,217 +1,105 @@
import assert from "node:assert/strict";
import { hostname, userInfo } from "node:os";
import { describe, it } from "node:test";
-import { argValue, buildRunMeta, gpuLabel, gpusUsed, imageTag, kvCacheOf, metaNotes, metaRows, modelLabel, quantOf, withLoadLinks } from "./benchmark-meta";
-import type { DeploymentOptions, HardwareGpu, HostHardware } from "./db/schema";
-import { applyOverrides, formatLinkPair, linkGen, parseLinkText, rebarFrom, systemSummary, systemSummaryText, validateOverrides } from "./hardware";
+import { endpointRunMeta, endpointSystem, gpuLabel, imageTag, metaNotes, metaRows, modelLabel, pcieLabel, quantFromName } from "./benchmark-meta";
+import type { EndpointHardware, EndpointSnapshot } from "./db/schema";
+import { formatLinkPair, parseLinkText, systemSummaryText } from "./hardware";
-const intel: HardwareGpu = {
- vendor: "intel",
- pciAddress: "0000:03:00.0",
- name: "Intel Arc Pro B65",
- vramMb: 32768,
- driver: "xe",
- driverVersion: "kernel 6.17.1",
- linkCurrent: { gen: 4, width: 8 },
- linkMax: { gen: 5, width: 16 },
- barMb: 32768,
+const hardware: EndpointHardware = {
+ gpuName: "Intel Arc Pro B65",
+ gpuCount: 2,
+ vramGb: 32,
+ pcie: "Gen5 x16",
+ p2p: "off",
rebar: true,
-};
-const nvidia: HardwareGpu = { ...intel, vendor: "nvidia", pciAddress: "0000:05:00.0", name: "NVIDIA RTX 4090", vramMb: 24564, driver: "nvidia", driverVersion: "580.82.07", barMb: 256, rebar: false };
-
-const hw: HostHardware = {
- gpus: [intel, nvidia],
- p2p: null,
- cpu: { model: "AMD EPYC 9124 16-Core Processor", cores: 16, threads: 32 },
- memoryBytes: 128e9,
- kernel: "6.17.1-pve",
- virtualization: { vm: true, hypervisor: "KVM/QEMU" },
- storage: { model: "Samsung SSD 990 PRO 2TB", kind: "nvme", sizeBytes: 2e12 },
- checkedAt: "2026-10-20T00:00:00.000Z",
+ gpuDriver: "xe (kernel 6.17.1)",
+ cpu: "AMD EPYC 9124 16-Core Processor",
+ memoryGb: 128,
+ os: "Debian GNU/Linux 13 (trixie)",
+ virtualization: "Proxmox VM with GPU passthrough",
+ kvCache: "q8_0",
+ description: "testing q8 KV",
};
-const opts: DeploymentOptions = { modelFile: "Qwen3-8B-Q4_K_M.gguf", contextSize: 8192, extraArgs: [], cacheTypeK: "q8_0", cacheTypeV: "q8_0", parallel: 2 };
+const snap = (h: EndpointHardware = hardware, over: Partial = {}): EndpointSnapshot => ({
+ type: "endpoint",
+ endpointName: "arc-box llama",
+ model: "Qwen3-8B-Q4_K_M.gguf",
+ engine: "llama.cpp",
+ engineVersion: "b6123",
+ contextSize: 32768,
+ hardware: h,
+ ...over,
+});
-describe("PCIe links and ReBAR", () => {
- it("maps link speeds to generations and formats current vs maximum", () => {
- assert.equal(linkGen("16.0 GT/s PCIe"), 4);
- assert.equal(linkGen("2.5 GT/s"), 1);
- assert.equal(linkGen("Unknown"), null);
+describe("PCIe links", () => {
+ it("formats current vs maximum and parses typed links", () => {
assert.equal(formatLinkPair({ gen: 4, width: 8 }, { gen: 5, width: 16 }), "Gen4 x8 of Gen5 x16");
assert.equal(formatLinkPair({ gen: 5, width: 16 }, { gen: 5, width: 16 }), "Gen5 x16");
- assert.equal(formatLinkPair(null, null), null);
- });
-
- it("parses typed links", () => {
- assert.deepEqual(parseLinkText("Gen4 x8"), { gen: 4, width: 8 });
- assert.deepEqual(parseLinkText("gen 5"), { gen: 5, width: null });
- assert.deepEqual(parseLinkText("x16"), { gen: null, width: 16 });
+ assert.deepEqual(parseLinkText("gen 4 x8"), { gen: 4, width: 8 });
assert.equal(parseLinkText("fast"), null);
- assert.equal(parseLinkText(""), null);
- });
-
- it("calls ReBAR on when a BAR covers the VRAM", () => {
- assert.equal(rebarFrom(32768, 32768), true);
- assert.equal(rebarFrom(256, 24564), false);
- assert.equal(rebarFrom(8192, null), true);
- assert.equal(rebarFrom(256, null), null);
- assert.equal(rebarFrom(null, 1024), null);
});
});
-describe("hardware overrides", () => {
- it("replace detected values and are listed", () => {
- const e = applyOverrides(hw, { gpus: { "0000:05:00.0": { linkCurrent: "Gen3 x16", rebar: true } }, storage: "Proxmox ZFS mirror", gpuPassthrough: true })!;
- assert.deepEqual(e.gpus[1].linkCurrent, { gen: 3, width: 16 });
- assert.equal(e.gpus[1].rebar, true);
- assert.deepEqual(e.gpus[0], intel);
- assert.equal(e.storage?.model, "Proxmox ZFS mirror");
- assert.equal(e.gpuPassthrough, true);
- assert.deepEqual(e.overridden, ["pcie link", "rebar", "storage", "gpu passthrough"]);
+describe("run metadata from an endpoint", () => {
+ it("takes the GPUs, link and model facts from the hardware notes", () => {
+ const m = endpointRunMeta(snap());
+ assert.equal(gpuLabel(m), "2× Intel Arc Pro B65 (32 GiB)");
+ assert.equal(pcieLabel(m), "Gen5 x16");
+ assert.equal(m.p2p, "off");
+ assert.equal(m.rebar, true);
+ assert.equal(m.runtime.engineName, "llama.cpp");
+ assert.equal(m.runtime.engineVersion, "b6123");
+ assert.equal(modelLabel(m), "Qwen3-8B-Q4_K_M.gguf Q4_K_M with q8_0 KV cache");
+ assert.equal(m.contextSize, 32768);
+ assert.equal(endpointRunMeta(snap(hardware, { slots: 4 })).concurrency, 4, "slots the server reported");
+ assert.equal(endpointRunMeta(snap({ ...hardware, concurrency: 2 }, { slots: 4 })).concurrency, 2, "the notes win");
});
- it("derive passthrough from a VM with GPUs", () => {
- assert.equal(applyOverrides(hw)!.gpuPassthrough, true);
- assert.equal(applyOverrides({ ...hw, virtualization: { vm: false, hypervisor: null } })!.gpuPassthrough, false);
+ it("lets the notes override what the server reported, and leaves out what nobody knows", () => {
+ const m = endpointRunMeta(snap({ engineName: "ik_llama.cpp", engineVersion: "4012", contextSize: 16384, quant: "IQ4_XS" }, { engine: null, engineVersion: null }));
+ assert.equal(m.runtime.engineName, "ik_llama.cpp");
+ assert.equal(m.runtime.engineVersion, "4012");
+ assert.equal(m.model.quant, "IQ4_XS");
+ assert.equal(m.contextSize, 16384);
+ assert.equal(gpuLabel(m), null, "no GPU in the notes");
+ const keys = metaRows(m).map((r) => r.key);
+ assert.ok(!keys.includes("image") && !keys.includes("digest") && !keys.includes("pcie"));
});
- it("are validated, empty fields dropped", () => {
- assert.deepEqual(validateOverrides({ gpus: { "0000:03:00.0": { name: "", linkMax: "Gen5 x16" } }, p2p: "", storage: " " }), { gpus: { "0000:03:00.0": { linkMax: "Gen5 x16" } } });
- assert.throws(() => validateOverrides({ gpus: { "0000:03:00.0": { linkCurrent: "fast" } } }), /isn't a PCIe link/);
- assert.throws(() => validateOverrides({ gpus: { "../etc": {} } }), /isn't a PCI address/);
- assert.throws(() => validateOverrides({ p2p: "maybe" }), /P2P/);
- assert.throws(() => validateOverrides({ gpus: { "0000:03:00.0": { vramMb: 1.5 } } }), /VRAM/);
- assert.throws(() => validateOverrides({ storage: "a\nb" }), /one line/);
+ it("finds the quant in model names", () => {
+ assert.equal(quantFromName("Qwen3-8B-Q4_K_M.gguf"), "Q4_K_M");
+ assert.equal(quantFromName("unsloth/Qwen3-8B-GGUF:UD-IQ3_XXS"), "UD-IQ3_XXS");
+ assert.equal(quantFromName("GLM-4.6-Q8_0-00001-of-00008.gguf"), "Q8_0");
+ assert.equal(quantFromName("Qwen/Qwen3.8-27B-FP8"), "FP8");
+ assert.equal(quantFromName("qwen3:8b"), null);
+ assert.equal(imageTag("ghcr.io/ggml-org/llama.cpp:server-b11429"), "server-b11429");
});
});
describe("system summary", () => {
- it("lists the whitelisted facts", () => {
- const text = systemSummaryText(systemSummary(applyOverrides(hw), "Debian GNU/Linux 13 (trixie)", "0.11.0"));
- assert.match(text, /CPU: AMD EPYC 9124 16-Core Processor \(16 cores, 32 threads\)/);
- assert.match(text, /Models disk: Samsung SSD 990 PRO 2TB, NVMe/);
- assert.match(text, /OS: Debian GNU\/Linux 13 \(trixie\), kernel 6\.17\.1-pve/);
- assert.match(text, /GPU driver: xe kernel 6\.17\.1, nvidia 580\.82\.07/);
- assert.match(text, /Virtualization: VM \(KVM\/QEMU\) with GPU passthrough/);
- assert.match(text, /Kaname 0\.11\.0/);
+ it("lists the facts from the notes", () => {
+ const text = systemSummaryText(endpointSystem(hardware, "0.15.0"));
+ assert.match(text, /CPU: AMD EPYC 9124 16-Core Processor/);
+ assert.match(text, /RAM: 128/);
+ assert.match(text, /OS: Debian GNU\/Linux 13 \(trixie\)/);
+ assert.match(text, /GPU driver: xe \(kernel 6\.17\.1\)/);
+ assert.match(text, /Virtualization: VM \(Proxmox VM with GPU passthrough\)/);
+ assert.match(text, /Kaname 0\.15\.0/);
+ assert.match(systemSummaryText(endpointSystem({ virtualization: "bare metal" }, "x")), /Virtualization: bare metal/);
});
- it("never contains the hostname, user, addresses or paths", () => {
- const s = systemSummary(applyOverrides(hw), "Debian GNU/Linux 13", "0.11.0");
- const meta = buildRunMeta({
- hardware: applyOverrides(hw),
- gpus: [intel],
- runtime: { image: "ghcr.io/ggml-org/llama.cpp:server-intel", digest: "sha256:abc", engine: "llama.cpp", engineName: null, extraArgs: [] },
- repoId: "unsloth/Qwen3-8B-GGUF",
- options: opts,
- engineInfo: null,
- });
- const published = JSON.stringify([s, metaNotes(meta, s, "testing q8 KV")]);
+ it("never contains the endpoint's address, the hostname, user or paths", () => {
+ const s = endpointSystem(hardware, "0.15.0");
+ const notes = metaNotes(endpointRunMeta(snap()), s, hardware.description ?? null);
+ const published = JSON.stringify([s, notes]);
for (const secret of [hostname(), userInfo().username].filter((x) => x.length > 2)) assert.ok(!published.includes(secret), `contains ${secret}`);
assert.doesNotMatch(published, /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/);
- assert.doesNotMatch(published, /\/(models|data|home|srv|mnt|var)\//);
- assert.doesNotMatch(published, /0000:0[35]:00\.0/);
+ assert.doesNotMatch(published, /https?:\/\//);
+ assert.equal(notes.description, "testing q8 KV");
+ assert.equal(notes.gpus, "2× Intel Arc Pro B65 (32 GiB)");
+ assert.equal(notes.pcie_max, "Gen5 x16");
// Only these keys exist; a new field must be added here on purpose.
assert.deepEqual(Object.keys(s).sort(), ["cpu", "gpuDrivers", "kaname", "kernel", "memoryBytes", "os", "storage", "virtualization"]);
});
});
-
-describe("run metadata", () => {
- it("reads image tags and flags", () => {
- assert.equal(imageTag("ghcr.io/ggml-org/llama.cpp:server-b11429"), "server-b11429");
- assert.equal(imageTag("registry:5000/vllm/vllm-openai@sha256:abc"), null);
- assert.equal(imageTag("vllm/vllm-openai:v0.31.0@sha256:abc"), "v0.31.0");
- assert.equal(argValue(["--kv-cache-dtype", "fp8", "--x"], "--kv-cache-dtype"), "fp8");
- assert.equal(argValue(["--quantization=awq"], "--quantization", "-q"), "awq");
- });
-
- it("finds quant and KV cache type per engine", () => {
- assert.equal(quantOf("llama.cpp", "Qwen3-8B-Q4_K_M.gguf", "unsloth/Qwen3-8B-GGUF", []), "Q4_K_M");
- assert.equal(quantOf("vllm", null, "Qwen/Qwen3.8-27B-FP8", []), "FP8");
- assert.equal(quantOf("vllm", null, "org/model", ["--quantization", "awq"]), "awq");
- assert.equal(quantOf("vllm", null, "Qwen/Qwen3-8B", []), null);
- assert.equal(kvCacheOf("llama.cpp", {}, []), "f16");
- assert.equal(kvCacheOf("llama.cpp", { cacheTypeK: "q8_0", cacheTypeV: "q4_0" }, []), "K q8_0 / V q4_0");
- assert.equal(kvCacheOf("vllm", {}, ["--kv-cache-dtype=fp8"]), "fp8");
- assert.equal(kvCacheOf("vllm", {}, []), "auto");
- });
-
- it("knows which GPUs a deployment gets", () => {
- const e = applyOverrides(hw);
- const nv = [{ vendor: "nvidia" as const, index: 0, uuid: "GPU-1", name: "x", memoryMb: 1, driver: "d", pciAddress: "0000:05:00.0" }];
- assert.deepEqual(gpusUsed(e, "dri", {}, nv).map((g) => g.pciAddress), ["0000:03:00.0"]);
- assert.deepEqual(gpusUsed(e, "nvidia", { gpus: ["GPU-1"] }, nv).map((g) => g.pciAddress), ["0000:05:00.0"]);
- assert.deepEqual(gpusUsed(e, "nvidia", { gpus: ["GPU-other"] }, nv), []);
- assert.deepEqual(gpusUsed(e, "cpu", {}, nv), []);
- });
-
- it("records what the server reported over the launch options", () => {
- const m = buildRunMeta({
- hardware: applyOverrides(hw),
- gpus: [intel],
- runtime: { image: "ghcr.io/ggml-org/llama.cpp:server-intel", digest: "sha256:abc", engine: "llama.cpp", engineName: "", extraArgs: [] },
- repoId: "unsloth/Qwen3-8B-GGUF",
- options: opts,
- engineInfo: { version: "b11429-d81235049", slots: 4, contextSize: 8192, at: "" },
- });
- assert.equal(m.p2p, "n/a");
- assert.equal(m.rebar, true);
- assert.equal(m.concurrency, 4);
- assert.deepEqual(m.runtime, { image: "ghcr.io/ggml-org/llama.cpp:server-intel", tag: "server-intel", digest: "sha256:abc", engine: "llama.cpp", engineName: "llama.cpp", engineVersion: "b11429-d81235049" });
- assert.equal(modelLabel(m), "Qwen3-8B-GGUF Q4_K_M with q8_0 KV cache");
- assert.equal(gpuLabel(m), "1× Intel Arc Pro B65 (32 GiB)");
- const rows = Object.fromEntries(metaRows(m).map((r) => [r.key, r.value]));
- assert.equal(rows.pcie, "Gen4 x8 of Gen5 x16 (at idle)");
- assert.equal(rows.engine, "llama.cpp b11429-d81235049");
- });
-
- it("falls back to the options, and to unknown, when the server didn't say", () => {
- const m = buildRunMeta({
- hardware: null,
- gpus: [nvidia, nvidia],
- runtime: { image: "vllm/vllm-openai:v0.31.0", digest: null, engine: "vllm", engineName: "vllm-radiance", extraArgs: ["--kv-cache-dtype", "fp8"] },
- repoId: "Qwen/Qwen3.8-27B-FP8",
- options: { modelFile: "", contextSize: 32768, extraArgs: [], maxNumSeqs: 8 },
- engineInfo: null,
- });
- assert.equal(m.p2p, null);
- assert.equal(m.rebar, false);
- assert.equal(m.concurrency, 8);
- assert.equal(m.runtime.engineName, "vllm-radiance");
- assert.equal(modelLabel(m), "Qwen3.8-27B-FP8 FP8 with fp8 KV cache");
- assert.equal(gpuLabel(m), "2× NVIDIA RTX 4090 (24 GiB)");
- const notes = metaNotes(m, null, " two\n lines ");
- assert.equal(notes.engine, "vllm-radiance");
- assert.equal(notes.p2p, "unknown");
- assert.equal(notes.description, "two lines");
- assert.equal(notes.gpus, "2× NVIDIA RTX 4090 (24 GiB)");
- });
-});
-
-describe("links under load", () => {
- const base = () =>
- buildRunMeta({
- hardware: applyOverrides(hw),
- gpus: [{ ...intel, linkCurrent: { gen: 1, width: 8 } }],
- runtime: { image: "x:y", digest: null, engine: "llama.cpp", engineName: null, extraArgs: [] },
- repoId: "a/b",
- options: opts,
- engineInfo: null,
- });
-
- it("marks an idle link and uses the fastest one seen under load", () => {
- const m = base();
- assert.equal(Object.fromEntries(metaRows(m).map((r) => [r.key, r.value])).pcie, "Gen1 x8 of Gen5 x16 (at idle)");
- const loaded = withLoadLinks(m, { "0000:03:00.0": { gen: 4, width: 8 } }, false)!;
- assert.equal(loaded.linkUnderLoad, true);
- assert.equal(Object.fromEntries(metaRows(loaded).map((r) => [r.key, r.value])).pcie, "Gen4 x8 of Gen5 x16");
- assert.equal(withLoadLinks(m, { "0000:03:00.0": { gen: 4, width: 8 } }, true), m);
- assert.equal(withLoadLinks(m, {}, false), m);
- });
-
- it("puts only the maximum link in the notes (known before the run)", () => {
- const n = metaNotes(base(), null, null);
- assert.equal(n.pcie_max, "Gen5 x16");
- assert.equal(n.pcie, undefined);
- });
-});
diff --git a/src/lib/benchmark-meta.ts b/src/lib/benchmark-meta.ts
index 38519d2..cdc32c2 100644
--- a/src/lib/benchmark-meta.ts
+++ b/src/lib/benchmark-meta.ts
@@ -1,9 +1,9 @@
-// What a benchmark run records about its setup (RunMeta) and the BetterBench notes made from it.
-// Pure; shared by the worker, the web app and tests.
+// What a benchmark run records about its setup (RunMeta, SystemSummary) and the BetterBench notes
+// made from it. Kaname can't see the machine behind an endpoint, so both come from the endpoint's
+// hardware notes plus what the server reports. Pure; shared by the worker, the web app and tests.
-import type { DeploymentOptions, EngineInfo, HardwareGpu, HostGpu, PcieLink, RunMeta, RuntimeAccelerator, RuntimeEngine, SystemSummary } from "@/lib/db/schema";
-import { type EffectiveHardware, formatLink, formatLinkPair, onOff, systemSummaryText } from "@/lib/hardware";
-import { quantGroup } from "@/lib/selection";
+import type { EndpointEngine, EndpointHardware, EndpointSnapshot, RunMeta, SystemSummary } from "@/lib/db/schema";
+import { formatLink, formatLinkPair, onOff, parseLinkText, systemSummaryText } from "@/lib/hardware";
/** "ghcr.io/org/img:tag@sha256:…" → "tag" (null: no tag, i.e. "latest" or digest only). */
export function imageTag(ref: string): string | null {
@@ -13,82 +13,69 @@ export function imageTag(ref: string): string | null {
return i >= 0 ? last.slice(i + 1) : null;
}
-/** Value of `--flag v` or `--flag=v` in an argument list (last one wins). */
-export function argValue(args: string[], ...flags: string[]): string | null {
- let v: string | null = null;
- for (let i = 0; i < args.length; i++) {
- for (const f of flags) {
- if (args[i] === f && i + 1 < args.length) v = args[i + 1];
- else if (args[i].startsWith(`${f}=`)) v = args[i].slice(f.length + 1);
- }
- }
- return v;
-}
-
const REPO_QUANT = /(?:^|[-_.])(nvfp4|mxfp4|fp8(?:[-_]dynamic)?|int8|int4|w8a8|w4a16|awq|gptq|bnb[-_]?4bit|bf16|fp16)(?=$|[-_.])/i;
-/** Quant: the GGUF's quant tag, vLLM's --quantization, or one named in the repo (FP8, AWQ, …). */
-export function quantOf(engine: RuntimeEngine, file: string | null, repoId: string, args: string[]): string | null {
- if (engine === "llama.cpp" && file) return quantGroup(file);
- const q = argValue(args, "--quantization", "-q");
- if (q) return q;
- const m = repoId.split("/").pop()?.match(REPO_QUANT);
+const NAME_QUANT = /[-_.:]((?:UD-)?(?:I?Q\d(?:_[A-Z0-9]+)*|BF16|F16|F32|MXFP4(?:_MOE)?|TQ\d_\d))$/i;
+
+/** The quant named in a model name: a GGUF quant tag ("Q4_K_M", "IQ3_XXS") or FP8, AWQ, … */
+export function quantFromName(name: string): string | null {
+ const base = name.trim().replace(/\.gguf$/i, "").replace(/-\d{5}-of-\d{5}$/, "");
+ const gguf = base.match(NAME_QUANT);
+ if (gguf) return gguf[1];
+ const m = base.split(/[/:]/).pop()?.match(REPO_QUANT);
return m ? m[1].toUpperCase().replace("_", "-") : null;
}
-/** KV cache type: llama.cpp -ctk/-ctv (f16 default), vLLM --kv-cache-dtype ("auto": the model's dtype). */
-export function kvCacheOf(engine: RuntimeEngine, o: Pick, args: string[]): string {
- if (engine === "vllm") return argValue(args, "--kv-cache-dtype") ?? "auto";
- const k = argValue(args, "-ctk", "--cache-type-k") ?? o.cacheTypeK ?? "f16";
- const v = argValue(args, "-ctv", "--cache-type-v") ?? o.cacheTypeV ?? "f16";
- return k === v ? k : `K ${k} / V ${v}`;
-}
+export const ENGINE_LABEL: Record = { "llama.cpp": "llama.cpp", vllm: "vLLM", sglang: "SGLang", ollama: "Ollama", other: "OpenAI-compatible server" };
-/** The GPUs a deployment gets: NVIDIA by UUID (all when none picked), /dev/dri ones by vendor. */
-export function gpusUsed(hw: EffectiveHardware | null, accelerator: RuntimeAccelerator | undefined, options: Pick, nvidia: HostGpu[]): HardwareGpu[] {
- const all = hw?.gpus ?? [];
- if (accelerator === "nvidia") {
- const picked = options.gpus?.length ? nvidia.filter((g) => options.gpus!.includes(g.uuid)).map((g) => g.pciAddress) : null;
- return all.filter((g) => g.vendor === "nvidia" && (!picked || picked.includes(g.pciAddress)));
- }
- if (accelerator === "dri") return all.filter((g) => g.vendor === "intel" || g.vendor === "amd");
- if (accelerator === "rocm") return all.filter((g) => g.vendor === "amd");
- return [];
-}
-
-export function buildRunMeta(x: {
- hardware: EffectiveHardware | null;
- gpus: HardwareGpu[];
- runtime: { image: string; digest: string | null; engine: RuntimeEngine; engineName: string | null; extraArgs: string[] };
- repoId: string;
- options: DeploymentOptions;
- engineInfo: EngineInfo | null;
-}): RunMeta {
- const args = [...x.runtime.extraArgs, ...x.options.extraArgs];
- const llama = x.runtime.engine === "llama.cpp";
+/** The run's setup from the endpoint snapshot: the hardware notes win over what the server reported. */
+export function endpointRunMeta(s: EndpointSnapshot): RunMeta {
+ const h = s.hardware;
+ const count = h.gpuName?.trim() ? Math.max(1, h.gpuCount ?? 1) : 0;
+ const link = h.pcie ? parseLinkText(h.pcie) : null;
+ const engine = s.engine ?? "other";
return {
v: 1,
- gpus: x.gpus.map((g) => ({ pciAddress: g.pciAddress, name: g.name, vramMb: g.vramMb, linkCurrent: g.linkCurrent, linkMax: g.linkMax, rebar: g.rebar })),
- linkUnderLoad: false,
- p2p: x.gpus.length < 2 ? "n/a" : (x.hardware?.p2p ?? null),
- rebar: x.gpus.length === 0 ? null : x.gpus.every((g) => g.rebar === true) ? true : x.gpus.some((g) => g.rebar === false) ? false : null,
+ gpus: Array.from({ length: count }, () => ({
+ name: h.gpuName!.trim(),
+ vramMb: h.vramGb ? Math.round(h.vramGb * 1024) : null,
+ linkCurrent: link,
+ linkMax: link,
+ rebar: h.rebar ?? null,
+ })),
+ // Typed in by the user, not sampled at idle.
+ linkUnderLoad: true,
+ p2p: count < 2 ? "n/a" : (h.p2p ?? null),
+ rebar: count ? (h.rebar ?? null) : null,
runtime: {
- image: x.runtime.image,
- tag: imageTag(x.runtime.image),
- digest: x.runtime.digest,
- engine: x.runtime.engine,
- engineName: x.runtime.engineName?.trim() || x.runtime.engine,
- engineVersion: x.engineInfo?.version ?? null,
+ image: h.image?.trim() ?? "",
+ tag: h.image?.trim() ? imageTag(h.image.trim()) : null,
+ digest: null,
+ engine,
+ engineName: h.engineName?.trim() || ENGINE_LABEL[engine],
+ engineVersion: h.engineVersion?.trim() || s.engineVersion,
},
- model: {
- repoId: x.repoId,
- file: x.options.modelFile || null,
- quant: quantOf(x.runtime.engine, x.options.modelFile || null, x.repoId, args),
- kvCache: kvCacheOf(x.runtime.engine, x.options, args),
- },
- contextSize: x.engineInfo?.contextSize ?? x.options.contextSize ?? null,
- concurrency: x.engineInfo?.slots ?? (llama ? x.options.parallel : x.options.maxNumSeqs) ?? null,
- overridden: x.hardware?.overridden ?? [],
+ model: { repoId: s.model, file: null, quant: h.quant?.trim() || quantFromName(s.model), kvCache: h.kvCache?.trim() || null },
+ contextSize: h.contextSize ?? s.contextSize,
+ concurrency: h.concurrency ?? s.slots ?? null,
+ overridden: [],
+ };
+}
+
+/** The publishable system summary from the notes: CPU, RAM, OS, driver, virtualization, Kaname. */
+export function endpointSystem(h: EndpointHardware, kaname: string): SystemSummary {
+ const virt = h.virtualization?.trim() || null;
+ const bare = !!virt && /bare[\s-]*metal/i.test(virt);
+ return {
+ cpu: { model: h.cpu?.trim() || null, cores: null, threads: null },
+ // GB as entered (formatBytes shows decimal units too).
+ memoryBytes: h.memoryGb ? Math.round(h.memoryGb * 1e9) : null,
+ storage: null,
+ os: h.os?.trim() || null,
+ kernel: null,
+ gpuDrivers: h.gpuDriver?.trim() ? [h.gpuDriver.trim()] : [],
+ virtualization: { vm: virt ? !bare : null, hypervisor: virt && !bare ? virt : null, gpuPassthrough: null },
+ kaname,
};
}
@@ -117,19 +104,6 @@ export function pcieMaxLabel(m: RunMeta): string | null {
return links.length ? links.join(", ") : null;
}
-/** The run's meta with the fastest links seen during the run as the current links (when sampled). */
-export function withLoadLinks(m: RunMeta | null, links: Record | null | undefined, overridden: boolean): RunMeta | null {
- if (!m || !links || overridden) return m;
- let hit = false;
- const gpus = m.gpus.map((g) => {
- const l = g.pciAddress ? links[g.pciAddress] : undefined;
- if (!l) return g;
- hit = true;
- return { ...g, linkCurrent: l };
- });
- return hit ? { ...m, gpus, linkUnderLoad: true } : m;
-}
-
export const engineLabel = (m: RunMeta) => [m.runtime.engineName, m.runtime.engineVersion].filter(Boolean).join(" ");
/** "Qwen3-8B-GGUF Q4_K_M with q8_0 KV cache" */
@@ -146,8 +120,8 @@ export function metaRows(m: RunMeta): { key: string; label: string; value: strin
...(m.gpus.length ? [{ key: "p2p", label: "P2P", value: m.p2p ?? "unknown" }] : []),
...(m.gpus.length ? [{ key: "rebar", label: "ReBAR", value: onOff(m.rebar) }] : []),
{ key: "engine", label: "Engine", value: engineLabel(m) || "unknown" },
- { key: "image", label: "Image", value: m.runtime.image },
- { key: "digest", label: "Digest", value: m.runtime.digest ?? "unknown" },
+ ...(m.runtime.image ? [{ key: "image", label: "Image", value: m.runtime.image }] : []),
+ ...(m.runtime.digest ? [{ key: "digest", label: "Digest", value: m.runtime.digest }] : []),
{ key: "model", label: "Model", value: modelLabel(m) },
{ key: "ctx", label: "Context", value: m.contextSize != null ? m.contextSize.toLocaleString("en-US") : "unknown" },
{ key: "concurrency", label: "Concurrency", value: m.concurrency != null ? String(m.concurrency) : "server default" },
@@ -161,7 +135,7 @@ export function metaRows(m: RunMeta): { key: string; label: string; value: strin
export function metaNotes(m: RunMeta, system: SystemSummary | null, description: string | null): Record {
const notes: Record = {
engine: engineLabel(m) || m.runtime.engine,
- image: m.runtime.image,
+ ...(m.runtime.image ? { image: m.runtime.image } : {}),
...(m.runtime.digest ? { digest: m.runtime.digest } : {}),
...(m.model.quant ? { quant: m.model.quant } : {}),
...(m.model.kvCache ? { kv_cache: m.model.kvCache } : {}),
@@ -170,7 +144,6 @@ export function metaNotes(m: RunMeta, system: SystemSummary | null, description:
gpus: gpuLabel(m) ?? "none",
};
if (m.gpus.length) {
- // The link under load is only known after the run (idle GPUs drop to a slower link).
notes.pcie_max = pcieMaxLabel(m) ?? "unknown";
notes.p2p = m.p2p ?? "unknown";
notes.rebar = onOff(m.rebar);
diff --git a/src/lib/benchmark-report.test.ts b/src/lib/benchmark-report.test.ts
index 6a8cdaa..c302fb2 100644
--- a/src/lib/benchmark-report.test.ts
+++ b/src/lib/benchmark-report.test.ts
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { describeHardware, reportCaveats, reportMethod, reportSubtitle, reportSummary, undersampled } from "./benchmark-report";
-import type { BenchmarkSnapshot, BenchmarkSummary } from "./db/schema";
+import type { BenchmarkSummary, DeploymentSnapshot, EndpointSnapshot } from "./db/schema";
const snap = {
deploymentName: "bench test",
@@ -15,7 +15,7 @@ const snap = {
memoryMb: 2640,
command: "",
host: { cpuModel: "AMD Ryzen 7 9850X3D 8-Core Processor", threads: 16, memoryBytes: 32e9, os: null },
-} as BenchmarkSnapshot;
+} as DeploymentSnapshot;
const summary: BenchmarkSummary = {
v: 2,
@@ -50,7 +50,25 @@ const summary: BenchmarkSummary = {
const run = { label: null, snapshot: snap, settings: { quick: true, passes: null, warmup: null, phases: [] }, summary };
+const endpointSnap: EndpointSnapshot = {
+ type: "endpoint",
+ endpointName: "arc box",
+ model: "Qwen3-8B-Q4_K_M.gguf",
+ engine: "llama.cpp",
+ engineVersion: "b6123",
+ contextSize: 32768,
+ hardware: { gpuName: "Intel Arc Pro B65", gpuCount: 2 },
+};
+
describe("benchmark report (launch80 conventions)", () => {
+ it("describes an endpoint run from its hardware notes, without the endpoint's name", () => {
+ assert.equal(describeHardware(endpointSnap), "2× Intel Arc Pro B65");
+ assert.equal(describeHardware({ ...endpointSnap, hardware: { cpu: "AMD EPYC 7282 16-Core Processor" } }), "an AMD EPYC 7282");
+ const s = reportSummary({ ...run, snapshot: endpointSnap });
+ assert.match(s, /Qwen3-8B-Q4_K_M\.gguf \(Q4_K_M, 32,768-token context\) on llama\.cpp b6123, 2× Intel Arc Pro B65/);
+ assert.doesNotMatch(s, /arc box/);
+ });
+
it("describes hardware, subtitle and summary", () => {
assert.equal(describeHardware(snap), "4 CPU cores of an AMD Ryzen 7 9850X3D");
assert.equal(describeHardware({ ...snap, gpuNames: ["NVIDIA GeForce RTX 3080", "NVIDIA GeForce RTX 3080"] }), "2× NVIDIA GeForce RTX 3080");
diff --git a/src/lib/benchmark-report.ts b/src/lib/benchmark-report.ts
index 4702b8a..10275f5 100644
--- a/src/lib/benchmark-report.ts
+++ b/src/lib/benchmark-report.ts
@@ -3,6 +3,8 @@
// say so first, under-sampled percentiles are flagged, truncated and batched runs are called out,
// and no endpoint or host name appears. Pure, for tests.
+import { quantFromName } from "@/lib/benchmark-meta";
+import { engineName, isEndpointSnapshot, modelName } from "@/lib/benchmark-view";
import type { BenchmarkSettings, BenchmarkSnapshot, BenchmarkSummary } from "@/lib/db/schema";
import { quantGroup } from "@/lib/selection";
@@ -23,21 +25,31 @@ export function isBatched(sum: BenchmarkSummary | null): boolean {
return !!sum?.single.some((r) => r.batched);
}
-/** "RTX 3080" / "4 CPU cores of an AMD Ryzen 7 9850X3D" / "an AMD EPYC 7282 (16 threads)". */
+const shortCpu = (cpu: string | null | undefined) =>
+ cpu
+ ?.replace(/\s+\d+-Core Processor$/i, "")
+ .replace(/\(R\)|\(TM\)/g, "")
+ .trim();
+
+/** "RTX 3080" / "2× Arc Pro B65" / "4 CPU cores of an AMD Ryzen 7 9850X3D" / "an AMD EPYC 7282 (16 threads)". */
export function describeHardware(s: BenchmarkSnapshot): string {
+ if (isEndpointSnapshot(s)) {
+ const h = s.hardware;
+ if (h.gpuName?.trim()) return (h.gpuCount ?? 1) > 1 ? `${h.gpuCount}× ${h.gpuName.trim()}` : h.gpuName.trim();
+ const cpu = shortCpu(h.cpu);
+ return cpu ? `an ${cpu}` : "unknown hardware";
+ }
if (s.gpuNames?.length) {
const names = [...new Set(s.gpuNames)];
return s.gpuNames.length > 1 && names.length === 1 ? `${s.gpuNames.length}× ${names[0]}` : names.join(" + ");
}
- const cpu = s.host?.cpuModel
- ?.replace(/\s+\d+-Core Processor$/i, "")
- .replace(/\(R\)|\(TM\)/g, "")
- .trim();
+ const cpu = shortCpu(s.host?.cpuModel);
if (s.cpus) return `${s.cpus} CPU core${s.cpus === 1 ? "" : "s"}${cpu ? ` of an ${cpu}` : ""}`;
return cpu ? `an ${cpu}${s.host?.threads ? ` (${s.host.threads} threads)` : ""}` : "CPU";
}
export function weightsLabel(s: BenchmarkSnapshot): string {
+ if (isEndpointSnapshot(s)) return s.hardware.quant?.trim() || quantFromName(s.model) || "weights not stated";
return s.options.modelFile ? (quantGroup(s.options.modelFile) ?? s.options.modelFile) : "safetensors";
}
@@ -53,13 +65,19 @@ export function reportSubtitle(run: Run): string {
return parts.join(" · ");
}
+/** The context window the run had (endpoint notes, the server's report, or the launch options). */
+export function contextOf(s: BenchmarkSnapshot): number | null {
+ return isEndpointSnapshot(s) ? (s.hardware.contextSize ?? s.contextSize) : s.options.contextSize;
+}
+
export function reportSummary(run: Run): string {
const s = run.snapshot;
+ const ctx = contextOf(s);
const sum = run.summary;
const out: string[] = [];
if (isQuick(sum)) out.push("Quick smoke run, not a publishable measurement.");
out.push(
- `${s.repoId} (${weightsLabel(s)}, ${int(s.options.contextSize)}-token context) on ${s.runtimeName}, ${describeHardware(s)}, measured with BetterBench ${sum?.betterbenchVersion ?? ""}${
+ `${modelName(s)} (${weightsLabel(s)}${ctx ? `, ${int(ctx)}-token context` : ""}) on ${engineName(s)}, ${describeHardware(s)}, measured with BetterBench ${sum?.betterbenchVersion ?? ""}${
sum?.single.length ? `: ${sum.passes} measured passes per category over ${sum.single.length} categories` : ""
}.`.replace(" ,", ","),
);
@@ -158,7 +176,7 @@ export function reportCaveats(run: Run): string[] {
const concFail = sum.concurrency.filter((c) => c.ok < c.requests).map((c) => `level ${c.level}: ${c.ok}/${c.requests} ok`);
if (concFail.length) out.push(`Concurrency requests failed at ${concFail.join("; ")}. Aggregate throughput counts only completed requests.`);
const skipped = sum.prefill.filter((p) => p.skipped).map((p) => int(p.target_depth));
- if (skipped.length) out.push(`Prefill depths skipped: ${skipped.join(", ")} tokens (exceed the model context of ${int(sum.maxModelLen ?? run.snapshot.options.contextSize)}).`);
+ if (skipped.length) out.push(`Prefill depths skipped: ${skipped.join(", ")} tokens (exceed the model context${(sum.maxModelLen ?? contextOf(run.snapshot)) ? ` of ${int((sum.maxModelLen ?? contextOf(run.snapshot))!)}` : ""}).`);
if (sum.cacheHits > 0) out.push(`${sum.cacheHits} request(s) were partly served from the server's prefix cache although the run asked for a cold cache; those prefill figures may be cache lookups.`);
return out.slice(0, 8);
}
diff --git a/src/lib/benchmark-setup.test.ts b/src/lib/benchmark-setup.test.ts
deleted file mode 100644
index ecaf3e7..0000000
--- a/src/lib/benchmark-setup.test.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-// What a run records about its setup, against a temporary database: detected hardware from the
-// worker, Settings → Hardware overrides, the runtime's digest and the server's reported version.
-
-import assert from "node:assert/strict";
-import { mkdtempSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { after, before, describe, it } from "node:test";
-import type { HostHardware } from "./db/schema";
-
-const dir = mkdtempSync(join(tmpdir(), "kaname-setup-"));
-process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
-process.env.APP_VERSION = "0.11.0-test";
-
-type Mods = {
- db: typeof import("./db/client");
- schema: typeof import("./db/schema");
- snapshot: typeof import("./benchmark-snapshot");
- settings: typeof import("./settings");
- benchmarks: typeof import("./benchmarks");
-};
-let M: Mods;
-let deploymentId: string;
-
-const hardware: HostHardware = {
- gpus: [
- {
- vendor: "intel",
- pciAddress: "0000:03:00.0",
- name: "Intel Arc Pro B65",
- vramMb: 32768,
- driver: "xe",
- driverVersion: "kernel 6.17.1",
- linkCurrent: { gen: 1, width: 1 },
- linkMax: { gen: 5, width: 16 },
- barMb: 256,
- rebar: false,
- },
- ],
- p2p: null,
- cpu: { model: "AMD EPYC 9124 16-Core Processor", cores: 16, threads: 32 },
- memoryBytes: 128e9,
- kernel: "6.17.1",
- virtualization: { vm: true, hypervisor: "KVM/QEMU" },
- storage: { model: "QEMU HARDDISK", kind: "virtual", sizeBytes: 2e12 },
- checkedAt: new Date().toISOString(),
-};
-
-before(async () => {
- const { runMigrations } = await import("./db/migrate");
- await runMigrations();
- M = {
- db: await import("./db/client"),
- schema: await import("./db/schema"),
- snapshot: await import("./benchmark-snapshot"),
- settings: await import("./settings"),
- benchmarks: await import("./benchmarks"),
- };
- const d = M.db.db();
- const s = M.schema;
- const now = new Date();
- await d.insert(s.workerState).values({
- id: "worker",
- startedAt: now,
- heartbeatAt: now,
- docker: {
- connected: true,
- error: null,
- serverVersion: "29.0",
- os: "Debian GNU/Linux 13 (trixie)",
- architecture: "x86_64",
- cpus: 32,
- memoryBytes: 128e9,
- cpuModel: null,
- cpuFeatures: [],
- network: "kaname_default",
- modelsSource: { type: "bind", source: "/srv/models" },
- hardware,
- checkedAt: now.toISOString(),
- },
- });
- const [model] = await d.insert(s.models).values({ repoId: "unsloth/Qwen3-8B-GGUF", pinnedSha: "a".repeat(40), localPath: "unsloth/Qwen3-8B-GGUF" }).returning();
- const [rt] = await d
- .insert(s.runtimes)
- .values({ name: "llama.cpp (Intel SYCL)", engine: "llama.cpp", accelerator: "dri", image: "ghcr.io/ggml-org/llama.cpp:server-intel", imageDigest: "sha256:feed" })
- .returning();
- const [dep] = await d
- .insert(s.deployments)
- .values({
- name: "qwen3 b65",
- runtimeId: rt.id,
- modelId: model.id,
- options: { modelFile: "Qwen3-8B-Q4_K_M.gguf", contextSize: 16384, cacheTypeK: "q8_0", cacheTypeV: "q8_0", extraArgs: [] },
- state: "running",
- engineInfo: { version: "b11429-d81235049", slots: 4, contextSize: 16384, at: now.toISOString() },
- })
- .returning();
- deploymentId = dep.id;
-});
-
-after(() => {
- (globalThis as { __kanameDb?: { client?: { close(): void } } }).__kanameDb?.client?.close();
- try {
- rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
- } catch {
- // Windows may still hold the WAL file for a moment.
- }
-});
-
-describe("run setup", () => {
- it("records GPU, link, ReBAR, engine version, quant, KV cache, context and slots", async () => {
- const { metas, system } = await M.snapshot.runSetup([deploymentId, null]);
- const m = metas[0]!;
- assert.equal(metas[1], null);
- assert.equal(m.gpus.length, 1);
- assert.equal(m.gpus[0].name, "Intel Arc Pro B65");
- assert.deepEqual(m.gpus[0].linkCurrent, { gen: 1, width: 1 });
- assert.equal(m.rebar, false);
- assert.equal(m.p2p, "n/a");
- assert.deepEqual(m.runtime, {
- image: "ghcr.io/ggml-org/llama.cpp:server-intel",
- tag: "server-intel",
- digest: "sha256:feed",
- engine: "llama.cpp",
- engineName: "llama.cpp",
- engineVersion: "b11429-d81235049",
- });
- assert.deepEqual(m.model, { repoId: "unsloth/Qwen3-8B-GGUF", file: "Qwen3-8B-Q4_K_M.gguf", quant: "Q4_K_M", kvCache: "q8_0" });
- assert.equal(m.contextSize, 16384);
- assert.equal(m.concurrency, 4);
- assert.deepEqual(m.overridden, []);
- assert.equal(system.kaname, "0.11.0-test");
- assert.equal(system.os, "Debian GNU/Linux 13 (trixie)");
- assert.equal(system.virtualization.gpuPassthrough, true);
- });
-
- it("applies Settings → Hardware to new runs", async () => {
- await M.settings.saveHardwareOverrides({
- gpus: { "0000:03:00.0": { linkCurrent: "Gen5 x8", rebar: true } },
- storage: "Samsung 990 PRO 2TB (passed through as a virtual disk)",
- hypervisor: "Proxmox VE 9 (KVM)",
- });
- const { metas, system } = await M.snapshot.runSetup([deploymentId]);
- assert.deepEqual(metas[0]!.gpus[0].linkCurrent, { gen: 5, width: 8 });
- assert.equal(metas[0]!.rebar, true);
- assert.deepEqual(metas[0]!.overridden, ["pcie link", "rebar", "storage", "virtualization"]);
- assert.equal(system.storage?.model, "Samsung 990 PRO 2TB (passed through as a virtual disk)");
- assert.equal(system.virtualization.hypervisor, "Proxmox VE 9 (KVM)");
- });
-
- it("rejects invalid overrides and clears them when empty", async () => {
- await assert.rejects(M.settings.saveHardwareOverrides({ gpus: { "0000:03:00.0": { linkMax: "Gen9" } } }), (e: Error) => e instanceof M.settings.SettingsError && /PCIe link/.test(e.message));
- assert.deepEqual(await M.settings.saveHardwareOverrides({}), {});
- assert.deepEqual(await M.settings.getHardwareOverrides(), {});
- });
-
- it("keeps a description with the run, editable later", async () => {
- const run = await M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ deploymentId, description: " q8_0 KV to fit 16k " }));
- assert.equal((await M.benchmarks.getBenchmark(run.id))?.description, "q8_0 KV to fit 16k");
- await M.benchmarks.updateBenchmark(run.id, { label: "q8 KV" });
- assert.equal((await M.benchmarks.getBenchmark(run.id))?.description, "q8_0 KV to fit 16k");
- await M.benchmarks.updateBenchmark(run.id, { description: "" });
- const row = await M.benchmarks.getBenchmark(run.id);
- assert.equal(row?.description, null);
- assert.equal(row?.label, "q8 KV");
- });
-});
diff --git a/src/lib/benchmark-snapshot.ts b/src/lib/benchmark-snapshot.ts
index b475d62..4b6ec3f 100644
--- a/src/lib/benchmark-snapshot.ts
+++ b/src/lib/benchmark-snapshot.ts
@@ -1,103 +1,40 @@
-// What a benchmark run records about the deployment it measures. Shared by the web app and the worker
-// (sweeps create runs there), so no "server-only" here.
+// What a benchmark run records about the endpoint it measures. Shared by the web app (when a run is
+// queued) and the worker (refreshed when it starts), so no "server-only" here.
-import { and, eq, isNull } from "drizzle-orm";
+import { eq, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
-import { buildRunMeta, gpusUsed } from "@/lib/benchmark-meta";
-import { type BenchmarkSnapshot, deployments, models, type RunMeta, runtimes, settings, type SystemSummary, workerState } from "@/lib/db/schema";
-import { applyOverrides, HARDWARE_OVERRIDES_KEY, parseOverrides, systemSummary } from "@/lib/hardware";
-
-/** Host CPU/RAM and the names of the GPUs a deployment uses (all detected ones when none are picked). */
-async function hostFacts(uuids: string[] | null, nvidia: boolean) {
- const ws = await db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") });
- const h = ws?.docker;
- const gpus = h?.gpus ?? [];
- return {
- gpuNames: nvidia ? (uuids ? gpus.filter((g) => uuids.includes(g.uuid)) : gpus).map((g) => g.name) : [],
- host: { cpuModel: h?.cpuModel ?? null, threads: h?.cpus ?? null, memoryBytes: h?.memoryBytes ?? null, os: h?.os ?? null },
- };
-}
-
-/** The deployment as it is now; null when it doesn't exist (or is being deleted). */
-export async function deploymentSnapshot(deploymentId: string): Promise<{ id: string; modelId: string; state: string; snapshot: BenchmarkSnapshot } | null> {
- const [d] = await db()
- .select({
- id: deployments.id,
- name: deployments.name,
- state: deployments.state,
- options: deployments.options,
- cpus: deployments.cpus,
- memoryMb: deployments.memoryMb,
- command: deployments.command,
- imageId: deployments.imageId,
- modelId: deployments.modelId,
- repoId: models.repoId,
- runtimeName: runtimes.name,
- engine: runtimes.engine,
- accelerator: runtimes.accelerator,
- image: runtimes.image,
- })
- .from(deployments)
- .innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
- .innerJoin(models, eq(models.id, deployments.modelId))
- .where(and(eq(deployments.id, deploymentId), isNull(deployments.deleteRequestedAt)));
- if (!d) return null;
- return {
- id: d.id,
- modelId: d.modelId,
- state: d.state,
- snapshot: {
- deploymentName: d.name,
- repoId: d.repoId,
- runtimeName: d.runtimeName,
- engine: d.engine,
- accelerator: d.accelerator,
- ...(await hostFacts(d.options.gpus ?? null, d.accelerator === "nvidia")),
- image: d.image,
- imageId: d.imageId,
- options: d.options,
- cpus: d.cpus,
- memoryMb: d.memoryMb,
- command: [d.image, ...(d.command ?? [])].join(" "),
- },
- };
-}
+import { type EndpointProbe, type EndpointSnapshot, endpoints, models } from "@/lib/db/schema";
+import { pickModel } from "@/lib/endpoint-probe";
/** Kaname's version (the image sets APP_VERSION). */
export const kanameVersion = () => process.env.APP_VERSION ?? "dev";
-/** The detected hardware with Settings → Hardware applied, and the host's OS. */
-export async function effectiveHardware() {
- const [ws, ov] = await Promise.all([
- db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") }),
- db().query.settings.findFirst({ where: eq(settings.key, HARDWARE_OVERRIDES_KEY) }),
- ]);
- const docker = ws?.docker ?? null;
- return { hardware: applyOverrides(docker?.hardware, parseOverrides(ov?.value)), nvidia: docker?.gpus ?? [], os: docker?.os ?? null };
+/** The endpoint's snapshot for a run of `model`, with what the server last reported. */
+export function snapshotOf(e: typeof endpoints.$inferSelect, model: string, probe: EndpointProbe | null): EndpointSnapshot {
+ return {
+ type: "endpoint",
+ endpointName: e.name,
+ model,
+ engine: e.engine ?? probe?.engine ?? null,
+ engineVersion: probe?.engineVersion ?? null,
+ contextSize: probe?.contextSize ?? null,
+ slots: probe?.slots ?? null,
+ hardware: e.hardware,
+ };
}
-/** Hardware, runtime and model facts of a deployment as it runs now, plus the system summary. */
-export async function runSetup(deploymentIds: (string | null)[]): Promise<{ metas: (RunMeta | null)[]; system: SystemSummary }> {
- const { hardware, nvidia, os } = await effectiveHardware();
- const metas = await Promise.all(
- deploymentIds.map(async (id) => {
- if (!id) return null;
- const [d] = await db()
- .select({ options: deployments.options, engineInfo: deployments.engineInfo, repoId: models.repoId, runtime: runtimes })
- .from(deployments)
- .innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
- .innerJoin(models, eq(models.id, deployments.modelId))
- .where(eq(deployments.id, id));
- if (!d) return null;
- return buildRunMeta({
- hardware,
- gpus: gpusUsed(hardware, d.runtime.accelerator, d.options, nvidia),
- runtime: { image: d.runtime.image, digest: d.runtime.imageDigest, engine: d.runtime.engine, engineName: d.runtime.engineName, extraArgs: d.runtime.extraArgs },
- repoId: d.repoId,
- options: d.options,
- engineInfo: d.engineInfo,
- });
- }),
- );
- return { metas, system: systemSummary(hardware, os, kanameVersion()) };
+/** The model to run: the one asked for, the endpoint's, or the only one the server lists. */
+export function modelFor(e: typeof endpoints.$inferSelect, probe: EndpointProbe, requested?: string | null) {
+ return pickModel(requested?.trim() || e.model, probe);
+}
+
+/**
+ * A downloaded model the server serves, by name: vLLM serves the repo id ("Qwen/Qwen3-8B"),
+ * llama.cpp's -hf alias is ":". GGUF file names are matched in M4.
+ */
+export async function libraryModelId(name: string): Promise {
+ const repo = name.trim().split(":")[0].toLowerCase();
+ if (!repo.includes("/")) return null;
+ const row = await db().query.models.findFirst({ columns: { id: true }, where: eq(sql`lower(${models.repoId})`, repo) });
+ return row?.id ?? null;
}
diff --git a/src/lib/benchmark-view.test.ts b/src/lib/benchmark-view.test.ts
index 49807c9..003214c 100644
--- a/src/lib/benchmark-view.test.ts
+++ b/src/lib/benchmark-view.test.ts
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
-import { configChips, deltaPct, describeSettings, headline } from "./benchmark-view";
+import { configChips, deltaPct, describeSettings, engineName, headline, modelName, targetName } from "./benchmark-view";
import type { BenchmarkSnapshot, BenchmarkSummary } from "./db/schema";
const summary: BenchmarkSummary = {
@@ -36,7 +36,24 @@ describe("benchmark view", () => {
cpus: 8,
memoryMb: null,
} as unknown as BenchmarkSnapshot;
- assert.deepEqual(configChips(snap), ["Q4_K_M", "context 4096", "threads 8", "kv cache k / v q8_0 / f16", "cpu limit 8 cores"]);
+ assert.deepEqual(configChips(snap), ["context 4096", "kv cache q8_0 / f16", "Q4_K_M", "threads 8", "cpu limit 8 cores"]);
+ });
+
+ it("lists an endpoint's notes as chips, and names it, its model and engine", () => {
+ const snap: BenchmarkSnapshot = {
+ type: "endpoint",
+ endpointName: "arc box",
+ model: "Qwen3-8B-Q4_K_M.gguf",
+ engine: "vllm",
+ engineVersion: "0.31.0",
+ contextSize: 32768,
+ hardware: { gpuName: "Intel Arc Pro B65", gpuCount: 2, kvCache: "fp8", concurrency: 4 },
+ };
+ assert.deepEqual(configChips(snap), ["2× Intel Arc Pro B65", "Q4_K_M", "context 32768", "parallel slots 4", "kv cache fp8"]);
+ assert.equal(targetName(snap), "arc box");
+ assert.equal(modelName(snap), "Qwen3-8B-Q4_K_M.gguf");
+ assert.equal(engineName(snap), "vLLM 0.31.0");
+ assert.equal(engineName({ ...snap, hardware: { engineName: "vllm-radiance" } }), "vllm-radiance 0.31.0");
});
it("describes settings and deltas", () => {
diff --git a/src/lib/benchmark-view.ts b/src/lib/benchmark-view.ts
index 0b0d799..7b787d4 100644
--- a/src/lib/benchmark-view.ts
+++ b/src/lib/benchmark-view.ts
@@ -1,6 +1,7 @@
// Display helpers for benchmark runs. Pure; shared by list, detail and compare pages.
-import type { BenchmarkSettings, BenchmarkSnapshot, BenchmarkSummary } from "@/lib/db/schema";
+import { ENGINE_LABEL, quantFromName } from "@/lib/benchmark-meta";
+import type { BenchmarkSettings, BenchmarkSnapshot, BenchmarkSummary, DeploymentSnapshot, EndpointSnapshot } from "@/lib/db/schema";
import { quantGroup } from "@/lib/selection";
export type Headline = {
@@ -25,37 +26,55 @@ export function headline(s: BenchmarkSummary | null): Headline {
};
}
+export const isEndpointSnapshot = (s: BenchmarkSnapshot): s is EndpointSnapshot => s.type === "endpoint";
+
+/** What was measured: the endpoint's name (or, before 0.15, the deployment's). */
+export const targetName = (s: BenchmarkSnapshot) => (isEndpointSnapshot(s) ? s.endpointName : s.deploymentName);
+/** The model name requested (before 0.15: the repo). */
+export const modelName = (s: BenchmarkSnapshot) => (isEndpointSnapshot(s) ? s.model : s.repoId);
+/** "llama.cpp b6123", "vLLM 0.31.0", or the runtime's name before 0.15. */
+export function engineName(s: BenchmarkSnapshot): string {
+ if (!isEndpointSnapshot(s)) return s.runtimeName;
+ const h = s.hardware;
+ const name = h.engineName?.trim() || (s.engine ? ENGINE_LABEL[s.engine] : "server");
+ const version = h.engineVersion?.trim() || s.engineVersion;
+ return version ? `${name} ${version}` : name;
+}
+
export type ConfigRow = { key: string; label: string; value: (s: BenchmarkSnapshot) => string | null };
const n = (v: number | null | undefined, unit = "") => (v != null ? `${v}${unit}` : null);
+const ep = (f: (s: EndpointSnapshot) => string | null) => (s: BenchmarkSnapshot) => (isEndpointSnapshot(s) ? f(s) : null);
+const dep = (f: (s: DeploymentSnapshot) => string | null) => (s: BenchmarkSnapshot) => (isEndpointSnapshot(s) ? null : f(s));
-/** Launch settings worth comparing between runs, in display order. */
+/** Settings worth comparing between runs, in display order (endpoint notes, then pre-0.15 launch options). */
export const CONFIG_ROWS: ConfigRow[] = [
- { key: "runtime", label: "Runtime", value: (s) => s.runtimeName },
- { key: "image", label: "Image", value: (s) => s.image },
- { key: "accel", label: "Runs on", value: (s) => (s.accelerator && s.accelerator !== "cpu" ? s.accelerator : null) },
- { key: "gpus", label: "GPUs", value: (s) => (s.gpuNames?.length ? s.gpuNames.join(", ") : null) },
- { key: "ngl", label: "GPU layers", value: (s) => s.options.gpuLayers ?? null },
- { key: "sm", label: "Split mode", value: (s) => s.options.splitMode ?? null },
- { key: "ts", label: "Tensor split", value: (s) => s.options.tensorSplit ?? null },
- { key: "moe", label: "MoE experts in RAM", value: (s) => (s.options.cpuMoe ? "all" : s.options.nCpuMoe != null ? `first ${s.options.nCpuMoe} layers` : null) },
- { key: "tp", label: "Tensor parallel", value: (s) => n(s.options.tensorParallel) },
- { key: "gmu", label: "GPU memory share", value: (s) => n(s.options.gpuMemoryUtilization) },
- { key: "cram", label: "Prompt cache (MiB)", value: (s) => n(s.options.cacheRamMb) },
- { key: "file", label: "Weights", value: (s) => (s.options.modelFile ? (quantGroup(s.options.modelFile) ?? s.options.modelFile) : "safetensors") },
- { key: "ctx", label: "Context", value: (s) => n(s.options.contextSize) },
- { key: "threads", label: "Threads", value: (s) => n(s.options.threads) },
- { key: "parallel", label: "Parallel slots", value: (s) => n(s.options.parallel) },
- { key: "batch", label: "Batch / micro-batch", value: (s) => (s.options.batchSize || s.options.ubatchSize ? `${s.options.batchSize ?? "–"} / ${s.options.ubatchSize ?? "–"}` : null) },
- { key: "kv", label: "KV cache K / V", value: (s) => (s.options.cacheTypeK || s.options.cacheTypeV ? `${s.options.cacheTypeK ?? "f16"} / ${s.options.cacheTypeV ?? "f16"}` : null) },
- { key: "fa", label: "Flash attention", value: (s) => s.options.flashAttn ?? null },
- { key: "draft", label: "Speculative", value: (s) => (s.options.draftFile ? `${s.options.draftType === "draft-mtp" ? "MTP" : "draft"}: ${s.options.draftFile}` : null) },
- { key: "dtype", label: "Data type", value: (s) => s.options.dtype ?? null },
- { key: "seqs", label: "Max sequences", value: (s) => n(s.options.maxNumSeqs) },
- { key: "kvgb", label: "KV cache (GiB)", value: (s) => n(s.options.kvCacheGb) },
- { key: "cpus", label: "CPU limit", value: (s) => n(s.cpus, " cores") },
- { key: "mem", label: "Memory limit", value: (s) => (s.memoryMb ? `${Math.round(s.memoryMb / 102.4) / 10} GiB` : null) },
- { key: "args", label: "Extra arguments", value: (s) => (s.options.extraArgs.length ? s.options.extraArgs.join(" ") : null) },
+ { key: "runtime", label: "Engine", value: (s) => engineName(s) },
+ { key: "image", label: "Image", value: (s) => (isEndpointSnapshot(s) ? s.hardware.image?.trim() || null : s.image) },
+ { key: "gpus", label: "GPUs", value: (s) => (isEndpointSnapshot(s) ? (s.hardware.gpuName ? `${s.hardware.gpuCount ?? 1}× ${s.hardware.gpuName}` : null) : s.gpuNames?.length ? s.gpuNames.join(", ") : null) },
+ { key: "quant", label: "Quant", value: ep((s) => s.hardware.quant?.trim() || quantFromName(s.model)) },
+ { key: "ctx", label: "Context", value: (s) => (isEndpointSnapshot(s) ? n(s.hardware.contextSize ?? s.contextSize) : n(s.options.contextSize)) },
+ { key: "concurrency", label: "Parallel slots", value: (s) => (isEndpointSnapshot(s) ? n(s.hardware.concurrency ?? s.slots) : n(s.options.parallel)) },
+ { key: "kv", label: "KV cache", value: (s) => (isEndpointSnapshot(s) ? s.hardware.kvCache?.trim() || null : s.options.cacheTypeK || s.options.cacheTypeV ? `${s.options.cacheTypeK ?? "f16"} / ${s.options.cacheTypeV ?? "f16"}` : null) },
+ { key: "accel", label: "Runs on", value: dep((s) => (s.accelerator && s.accelerator !== "cpu" ? s.accelerator : null)) },
+ { key: "ngl", label: "GPU layers", value: dep((s) => s.options.gpuLayers ?? null) },
+ { key: "sm", label: "Split mode", value: dep((s) => s.options.splitMode ?? null) },
+ { key: "ts", label: "Tensor split", value: dep((s) => s.options.tensorSplit ?? null) },
+ { key: "moe", label: "MoE experts in RAM", value: dep((s) => (s.options.cpuMoe ? "all" : s.options.nCpuMoe != null ? `first ${s.options.nCpuMoe} layers` : null)) },
+ { key: "tp", label: "Tensor parallel", value: dep((s) => n(s.options.tensorParallel)) },
+ { key: "gmu", label: "GPU memory share", value: dep((s) => n(s.options.gpuMemoryUtilization)) },
+ { key: "cram", label: "Prompt cache (MiB)", value: dep((s) => n(s.options.cacheRamMb)) },
+ { key: "file", label: "Weights", value: dep((s) => (s.options.modelFile ? (quantGroup(s.options.modelFile) ?? s.options.modelFile) : "safetensors")) },
+ { key: "threads", label: "Threads", value: dep((s) => n(s.options.threads)) },
+ { key: "batch", label: "Batch / micro-batch", value: dep((s) => (s.options.batchSize || s.options.ubatchSize ? `${s.options.batchSize ?? "–"} / ${s.options.ubatchSize ?? "–"}` : null)) },
+ { key: "fa", label: "Flash attention", value: dep((s) => s.options.flashAttn ?? null) },
+ { key: "draft", label: "Speculative", value: dep((s) => (s.options.draftFile ? `${s.options.draftType === "draft-mtp" ? "MTP" : "draft"}: ${s.options.draftFile}` : null)) },
+ { key: "dtype", label: "Data type", value: dep((s) => s.options.dtype ?? null) },
+ { key: "seqs", label: "Max sequences", value: dep((s) => n(s.options.maxNumSeqs)) },
+ { key: "kvgb", label: "KV cache (GiB)", value: dep((s) => n(s.options.kvCacheGb)) },
+ { key: "cpus", label: "CPU limit", value: dep((s) => n(s.cpus, " cores")) },
+ { key: "mem", label: "Memory limit", value: dep((s) => (s.memoryMb ? `${Math.round(s.memoryMb / 102.4) / 10} GiB` : null)) },
+ { key: "args", label: "Extra arguments", value: dep((s) => (s.options.extraArgs.length ? s.options.extraArgs.join(" ") : null)) },
];
/** Short chips for a list row: the settings that are set. */
@@ -64,7 +83,7 @@ export function configChips(s: BenchmarkSnapshot): string[] {
return CONFIG_ROWS.filter((r) => !skip.has(r.key))
.map((r) => {
const v = r.value(s);
- return v == null ? null : r.key === "file" ? v : `${r.label.toLowerCase()} ${v}`;
+ return v == null ? null : r.key === "file" || r.key === "quant" || r.key === "gpus" ? v : `${r.label.toLowerCase()} ${v}`;
})
.filter((v): v is string => v != null);
}
diff --git a/src/lib/benchmarks.ts b/src/lib/benchmarks.ts
index 7bef4c7..8836a5e 100644
--- a/src/lib/benchmarks.ts
+++ b/src/lib/benchmarks.ts
@@ -3,9 +3,10 @@ import { rm } from "node:fs/promises";
import { and, asc, desc, eq, gt, inArray, or } from "drizzle-orm";
import { z } from "zod";
import { runDir } from "@/lib/benchmark-paths";
-import { deploymentSnapshot } from "@/lib/benchmark-snapshot";
+import { libraryModelId, modelFor, snapshotOf } from "@/lib/benchmark-snapshot";
import { db } from "@/lib/db/client";
-import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, QUALITY_SECTIONS } from "@/lib/db/schema";
+import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, endpoints, QUALITY_SECTIONS } from "@/lib/db/schema";
+import { probeEndpoint } from "@/lib/endpoint-probe";
export class BenchmarkError extends Error {
constructor(
@@ -20,7 +21,9 @@ export class BenchmarkError extends Error {
export const DESCRIPTION_MAX = 4000;
export const BenchmarkBody = z.object({
- deploymentId: z.string().min(1),
+ endpointId: z.string().min(1),
+ /** The model to request; default: the endpoint's (or the only one it serves). */
+ model: z.string().trim().max(300).nullable().optional(),
label: z.string().trim().max(120).nullable().optional(),
/** Free text: what this run tries out. Passed to BetterBench and launch80 with the system summary. */
description: z.string().trim().max(DESCRIPTION_MAX).nullable().optional(),
@@ -29,53 +32,50 @@ export const BenchmarkBody = z.object({
warmup: z.number().int().min(0).max(50).nullable().optional(),
/** Empty: all phases. */
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
- /** A/B: the second deployment (B), the target minimum detectable effect in % and the pair ceiling. */
- deploymentBId: z.string().min(1).nullable().optional(),
+ /** A/B: the second endpoint (B), the target minimum detectable effect in % and the pair ceiling. */
+ endpointBId: z.string().min(1).nullable().optional(),
mdePct: z.number().min(0.1).max(50).nullable().optional(),
maxPairs: z.number().int().min(12).max(2000).nullable().optional(),
- /** Set by sweeps. */
- sweepId: z.string().nullable().optional(),
- /** "eval": the quality eval instead of BetterBench (default: run, or ab with deploymentBId). */
+ /** "eval": the quality eval instead of BetterBench (default: run, or ab with endpointBId). */
kind: z.enum(["run", "ab", "eval"]).optional(),
/** eval: which sections (empty: all). */
evalSections: z.array(z.enum(QUALITY_SECTIONS)).max(3).optional(),
});
export type BenchmarkInput = z.infer;
-/** A running deployment as it is now: what a run measures and records. */
-async function snapshotOf(deploymentId: string, role: string) {
- const d = await deploymentSnapshot(deploymentId);
- if (!d) throw new BenchmarkError("not_found", `${role} not found.`, 404);
- if (d.state !== "running") throw new BenchmarkError("invalid", `Start ${role.toLowerCase()} first; benchmarks run against a running server.`, 409);
- return d;
+/** The endpoint, asked right now: a run against a server that doesn't answer fails at once. */
+async function endpointFor(id: string, role: string) {
+ const e = await db().query.endpoints.findFirst({ where: eq(endpoints.id, id) });
+ if (!e) throw new BenchmarkError("not_found", `${role} not found.`, 404);
+ const probe = await probeEndpoint({ baseUrl: e.baseUrl, apiKey: e.apiKey, engine: e.engine });
+ await db().update(endpoints).set({ probe }).where(eq(endpoints.id, e.id));
+ if (!probe.ok) throw new BenchmarkError("invalid", `${role} (${e.name}): ${probe.error}`, 409);
+ return { e, probe };
}
/**
- * Queue a run against a running deployment, or a paired A/B between two running deployments of the
- * same model (BetterBench sends one model name to both). The worker runs one benchmark at a time.
+ * Queue a run against an endpoint, or a paired A/B between two endpoints serving the same model
+ * (BetterBench sends one model name to both). The worker runs one benchmark at a time.
*/
-/** Requested through the API: who asked, whether it waits for approval, and its time limit. */
-export type AgentRequest = { requestedBy: { tokenId: string; name: string }; pendingApproval: boolean; timeLimitS: number };
-
-export async function createBenchmark(input: BenchmarkInput, agent?: AgentRequest) {
- const kind = input.kind ?? (input.deploymentBId ? "ab" : "run");
+export async function createBenchmark(input: BenchmarkInput) {
+ const kind = input.kind ?? (input.endpointBId ? "ab" : "run");
const ab = kind === "ab";
- if (ab && !input.deploymentBId) throw new BenchmarkError("invalid", "An A/B needs a second deployment.", 400);
- const a = await snapshotOf(input.deploymentId, ab ? "Deployment A" : "The deployment");
- const b = ab ? await snapshotOf(input.deploymentBId!, "Deployment B") : null;
- if (b) {
- if (b.id === a.id) throw new BenchmarkError("invalid", "Pick two different deployments for an A/B.", 400);
- if (b.snapshot.repoId !== a.snapshot.repoId) {
- throw new BenchmarkError("invalid", "An A/B compares two deployments of the same model (BetterBench requests one model name from both).", 400);
- }
+ if (ab && !input.endpointBId) throw new BenchmarkError("invalid", "An A/B needs a second endpoint.", 400);
+ if (ab && input.endpointBId === input.endpointId) throw new BenchmarkError("invalid", "Pick two different endpoints for an A/B.", 400);
+ const a = await endpointFor(input.endpointId, ab ? "Endpoint A" : "The endpoint");
+ const picked = modelFor(a.e, a.probe, input.model);
+ if ("error" in picked) throw new BenchmarkError("invalid", picked.error, 400);
+ const b = ab ? await endpointFor(input.endpointBId!, "Endpoint B") : null;
+ if (b && b.probe.models.length && !b.probe.models.includes(picked.model)) {
+ throw new BenchmarkError("invalid", `Endpoint B doesn't serve "${picked.model}". An A/B sends the same model name to both servers.`, 400);
}
const [row] = await db()
.insert(benchmarkRuns)
.values({
kind,
- deploymentId: a.id,
- deploymentBId: b?.id ?? null,
- modelId: a.modelId,
+ endpointId: a.e.id,
+ endpointBId: b?.e.id ?? null,
+ modelId: await libraryModelId(picked.model),
label: input.label || null,
description: input.description || null,
settings:
@@ -88,17 +88,8 @@ export async function createBenchmark(input: BenchmarkInput, agent?: AgentReques
phases: input.phases,
...(ab ? { mdePct: input.mdePct ?? null, maxPairs: input.maxPairs ?? null } : {}),
},
- snapshot: a.snapshot,
- snapshotB: b?.snapshot ?? null,
- sweepId: input.sweepId ?? null,
- ...(agent
- ? {
- requestedByTokenId: agent.requestedBy.tokenId,
- requestedBy: agent.requestedBy.name,
- timeLimitS: agent.timeLimitS,
- state: agent.pendingApproval ? ("pending_approval" as const) : ("queued" as const),
- }
- : {}),
+ snapshot: snapshotOf(a.e, picked.model, a.probe),
+ snapshotB: b ? snapshotOf(b.e, picked.model, b.probe) : null,
})
.returning({ id: benchmarkRuns.id });
return row;
@@ -106,7 +97,7 @@ export async function createBenchmark(input: BenchmarkInput, agent?: AgentReques
const listColumns = {
id: benchmarkRuns.id,
- deploymentId: benchmarkRuns.deploymentId,
+ endpointId: benchmarkRuns.endpointId,
modelId: benchmarkRuns.modelId,
tool: benchmarkRuns.tool,
label: benchmarkRuns.label,
@@ -121,15 +112,10 @@ const listColumns = {
summary: benchmarkRuns.summary,
hasReport: benchmarkRuns.hasReport,
kind: benchmarkRuns.kind,
- deploymentBId: benchmarkRuns.deploymentBId,
+ endpointBId: benchmarkRuns.endpointBId,
snapshotB: benchmarkRuns.snapshotB,
ab: benchmarkRuns.ab,
- resources: benchmarkRuns.resources,
quality: benchmarkRuns.quality,
- sweepId: benchmarkRuns.sweepId,
- requestedBy: benchmarkRuns.requestedBy,
- requestedByTokenId: benchmarkRuns.requestedByTokenId,
- timeLimitS: benchmarkRuns.timeLimitS,
meta: benchmarkRuns.meta,
metaB: benchmarkRuns.metaB,
system: benchmarkRuns.system,
@@ -139,13 +125,13 @@ const listColumns = {
export type BenchmarkRow = Awaited>[number];
-export async function listBenchmarks(filter: { deploymentId?: string; modelId?: string } = {}) {
+export async function listBenchmarks(filter: { endpointId?: string; modelId?: string } = {}) {
return db()
.select(listColumns)
.from(benchmarkRuns)
.where(
and(
- filter.deploymentId ? or(eq(benchmarkRuns.deploymentId, filter.deploymentId), eq(benchmarkRuns.deploymentBId, filter.deploymentId)) : undefined,
+ filter.endpointId ? or(eq(benchmarkRuns.endpointId, filter.endpointId), eq(benchmarkRuns.endpointBId, filter.endpointId)) : undefined,
filter.modelId ? eq(benchmarkRuns.modelId, filter.modelId) : undefined,
),
)
@@ -163,37 +149,17 @@ export async function getBenchmarks(ids: string[]) {
return ids.map((id) => rows.find((r) => r.id === id)).filter((r) => r != null);
}
-/** Queued (or still unapproved) runs are cancelled right away; a running one is stopped by the worker. */
+/** Queued runs are cancelled right away; a running one is stopped by the worker. */
export async function cancelBenchmark(id: string) {
const run = await getBenchmark(id);
if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
- if (run.state === "queued" || run.state === "pending_approval") {
+ if (run.state === "queued") {
await db().update(benchmarkRuns).set({ state: "cancelled", finishedAt: new Date() }).where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, run.state)));
} else if (run.state === "running") {
await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, id));
}
}
-/** Let a run an agent asked for start (it joins the queue). */
-export async function approveBenchmark(id: string) {
- const res = await db()
- .update(benchmarkRuns)
- .set({ state: "queued" })
- .where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, "pending_approval")))
- .returning({ id: benchmarkRuns.id });
- if (res.length === 0) throw new BenchmarkError("invalid", "This run doesn't wait for approval.", 409);
-}
-
-/** Turn down a run an agent asked for. */
-export async function rejectBenchmark(id: string) {
- const res = await db()
- .update(benchmarkRuns)
- .set({ state: "cancelled", finishedAt: new Date(), error: "Rejected by the user." })
- .where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, "pending_approval")))
- .returning({ id: benchmarkRuns.id });
- if (res.length === 0) throw new BenchmarkError("invalid", "This run doesn't wait for approval.", 409);
-}
-
/** Rename a run (label) and/or change its description; fields left out stay as they are. */
export async function updateBenchmark(id: string, patch: { label?: string | null; description?: string | null }) {
const set: Partial