Release 0.13.0: agent API for deployments and benchmarks
Release / release (push) Successful in 3m0s
Release / release (push) Successful in 3m0s
Scopes deployments:read/write and benchmarks:read/run; /api/v1 endpoints for runtimes, deployments (create with dry run, edit, start, stop, delete own ones), benchmark runs, A/B, sweeps and comparisons; ?wait= on all status endpoints. Guardrails: approval, agent deployments at once, one GPU job at a time, time limits, sweep variants, runtime and argument allowlists, host port range, memory/CPU caps, protected deployments with a VRAM check. Requested-by filters, approval bars, per-token activity log, scope editing, docs/agent/SKILL-tuning.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e007a35143
commit
716bd8f2f0
62 files changed
+6091
-219
No files matched your search
@@ -33,6 +33,8 @@ import { Input } from "@/components/ui/input";
|
||||
import { reportSummary, weightsLabel } from "@/lib/benchmark-report";
|
||||
import { CONFIG_ROWS, describeSettings } 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";
|
||||
@@ -60,7 +62,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 === "queued" || r.state === "running";
|
||||
const active = r.state === "pending_approval" || r.state === "queued" || r.state === "running";
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
@@ -120,6 +122,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
state={r.state}
|
||||
cancelling={!!r.cancelRequestedAt}
|
||||
/>
|
||||
<RequestedByBadge name={r.requestedBy} />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{r.deploymentId ? (
|
||||
@@ -265,6 +268,13 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{r.state === "pending_approval" && (
|
||||
<AgentApprovalBar
|
||||
requestedBy={r.requestedBy}
|
||||
what={`run ${r.kind === "ab" ? "an A/B" : "a benchmark"} on ${s.deploymentName} (${describeSettings(r.settings)}${r.timeLimitS ? `, at most ${Math.round(r.timeLimitS / 60)} min` : ""})`}
|
||||
base={`/api/benchmarks/${r.id}`}
|
||||
/>
|
||||
)}
|
||||
{r.error && (
|
||||
<div className="flex gap-3 rounded-xl border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm">
|
||||
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-destructive" />
|
||||
|
||||
@@ -4,16 +4,28 @@ 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";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import type { BenchmarkRow } from "@/lib/benchmarks";
|
||||
import { configChips, describeSettings, headline } from "@/lib/benchmark-view";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type ListRow = Omit<BenchmarkRow, "createdAt" | "startedAt" | "finishedAt" | "cancelRequestedAt"> & {
|
||||
export type ListRow = Omit<
|
||||
BenchmarkRow,
|
||||
"createdAt" | "startedAt" | "finishedAt" | "cancelRequestedAt"
|
||||
> & {
|
||||
createdAt: string;
|
||||
startedAt: string | null;
|
||||
finishedAt: string | null;
|
||||
@@ -21,18 +33,35 @@ export type ListRow = Omit<BenchmarkRow, "createdAt" | "startedAt" | "finishedAt
|
||||
};
|
||||
|
||||
const MAX_COMPARE = 16;
|
||||
const fmt = (v: number | null | undefined, digits = 1) => (v == null ? "–" : v.toFixed(digits));
|
||||
const fmt = (v: number | null | undefined, digits = 1) =>
|
||||
v == null ? "–" : v.toFixed(digits);
|
||||
|
||||
/** All runs with their headline numbers; polls while something is queued or running. */
|
||||
export function BenchmarkList({ rows: initial, compact }: { rows: ListRow[]; compact?: boolean }) {
|
||||
export function BenchmarkList({
|
||||
rows: initial,
|
||||
compact,
|
||||
}: {
|
||||
rows: ListRow[];
|
||||
compact?: boolean;
|
||||
}) {
|
||||
const [rows, setRows] = useState(initial);
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
// "" = everything, "-" = started in Kaname, else a token 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),
|
||||
);
|
||||
|
||||
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", { cache: "no-store" }).catch(
|
||||
() => null,
|
||||
);
|
||||
if (res?.ok) setRows(await res.json());
|
||||
}, 3_000);
|
||||
return () => clearInterval(t);
|
||||
@@ -53,22 +82,54 @@ export function BenchmarkList({ rows: initial, compact }: { rows: ListRow[]; com
|
||||
);
|
||||
}
|
||||
|
||||
const toggle = (id: string) => setSelected((s) => (s.includes(id) ? s.filter((x) => x !== id) : s.length < MAX_COMPARE ? [...s, id] : s));
|
||||
const toggle = (id: string) =>
|
||||
setSelected((s) =>
|
||||
s.includes(id)
|
||||
? s.filter((x) => x !== id)
|
||||
: s.length < MAX_COMPARE
|
||||
? [...s, id]
|
||||
: s,
|
||||
);
|
||||
const comparable = rows.filter((r) => r.state === "completed");
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
{!compact && comparable.length > 1 && (
|
||||
<div className="flex items-center justify-between gap-2 text-sm">
|
||||
<span className="text-muted-foreground">{selected.length === 0 ? "Select completed runs to compare them." : `${selected.length} selected (up to ${MAX_COMPARE}).`}</span>
|
||||
<Link
|
||||
href={`/benchmarks/compare?ids=${selected.join(",")}`}
|
||||
className={cn(buttonVariants({ size: "sm" }), selected.length < 2 && "pointer-events-none opacity-50")}
|
||||
aria-disabled={selected.length < 2}
|
||||
>
|
||||
<GitCompareIcon />
|
||||
Compare
|
||||
</Link>
|
||||
{!compact && (comparable.length > 1 || tokens.length > 0) && (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-sm">
|
||||
<span className="text-muted-foreground">
|
||||
{selected.length === 0
|
||||
? "Select completed runs to compare them."
|
||||
: `${selected.length} selected (up to ${MAX_COMPARE}).`}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
{tokens.length > 0 && (
|
||||
<NativeSelect
|
||||
value={by}
|
||||
onChange={(e) => setBy(e.target.value)}
|
||||
className="h-8 text-xs"
|
||||
aria-label="Requested by"
|
||||
>
|
||||
<option value="">Requested by anyone</option>
|
||||
<option value="-">Started in Kaname</option>
|
||||
{tokens.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{t} (API)
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
)}
|
||||
<Link
|
||||
href={`/benchmarks/compare?ids=${selected.join(",")}`}
|
||||
className={cn(
|
||||
buttonVariants({ size: "sm" }),
|
||||
selected.length < 2 && "pointer-events-none opacity-50",
|
||||
)}
|
||||
aria-disabled={selected.length < 2}
|
||||
>
|
||||
<GitCompareIcon />
|
||||
Compare
|
||||
</Link>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<Card className="py-0">
|
||||
@@ -78,27 +139,42 @@ export function BenchmarkList({ rows: initial, compact }: { rows: ListRow[]; com
|
||||
{!compact && <TableHead className="w-8" />}
|
||||
<TableHead>Run</TableHead>
|
||||
<TableHead className="hidden lg:table-cell">Settings</TableHead>
|
||||
<TableHead className="text-right" title="Weighted single-stream decode speed">
|
||||
<TableHead
|
||||
className="text-right"
|
||||
title="Weighted single-stream decode speed"
|
||||
>
|
||||
Decode t/s
|
||||
</TableHead>
|
||||
<TableHead className="text-right" title="Median time to first token">
|
||||
<TableHead
|
||||
className="text-right"
|
||||
title="Median time to first token"
|
||||
>
|
||||
TTFT
|
||||
</TableHead>
|
||||
<TableHead className="hidden text-right md:table-cell" title="Prompt processing at the deepest measured input">
|
||||
<TableHead
|
||||
className="hidden text-right md:table-cell"
|
||||
title="Prompt processing at the deepest measured input"
|
||||
>
|
||||
Prefill t/s
|
||||
</TableHead>
|
||||
<TableHead className="hidden text-right md:table-cell" title="Best aggregate throughput under parallel load">
|
||||
<TableHead
|
||||
className="hidden text-right md:table-cell"
|
||||
title="Best aggregate throughput under parallel load"
|
||||
>
|
||||
Peak t/s
|
||||
</TableHead>
|
||||
<TableHead className="w-28">State</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{rows.map((r) => {
|
||||
{shown.map((r) => {
|
||||
const h = headline(r.summary);
|
||||
const s = r.snapshot;
|
||||
return (
|
||||
<TableRow key={r.id} data-state={selected.includes(r.id) ? "selected" : undefined}>
|
||||
<TableRow
|
||||
key={r.id}
|
||||
data-state={selected.includes(r.id) ? "selected" : undefined}
|
||||
>
|
||||
{!compact && (
|
||||
<TableCell>
|
||||
<Checkbox
|
||||
@@ -110,35 +186,64 @@ export function BenchmarkList({ rows: initial, compact }: { rows: ListRow[]; com
|
||||
</TableCell>
|
||||
)}
|
||||
<TableCell className="whitespace-normal">
|
||||
<Link href={`/benchmarks/${r.id}`} className="font-medium hover:underline">
|
||||
<Link
|
||||
href={`/benchmarks/${r.id}`}
|
||||
className="font-medium hover:underline"
|
||||
>
|
||||
{r.label ?? s.deploymentName}
|
||||
</Link>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<div className="flex flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
|
||||
{r.label && `${s.deploymentName} · `}
|
||||
{s.repoId} · <LocalTime value={r.createdAt} />
|
||||
<RequestedByBadge
|
||||
name={r.requestedBy}
|
||||
className="h-4 text-[10px]"
|
||||
/>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="hidden max-w-md whitespace-normal lg:table-cell">
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<span className="rounded-4xl border border-foreground/15 px-1.5 text-[11px] leading-4">{s.runtimeName}</span>
|
||||
<span className="rounded-4xl border border-foreground/15 px-1.5 text-[11px] leading-4">
|
||||
{s.runtimeName}
|
||||
</span>
|
||||
{configChips(s).map((c) => (
|
||||
<span key={c} className="rounded-4xl bg-muted px-1.5 text-[11px] leading-4 text-muted-foreground">
|
||||
<span
|
||||
key={c}
|
||||
className="rounded-4xl bg-muted px-1.5 text-[11px] leading-4 text-muted-foreground"
|
||||
>
|
||||
{c}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-0.5 text-[11px] text-muted-foreground">{describeSettings(r.settings)}</div>
|
||||
<div className="mt-0.5 text-[11px] text-muted-foreground">
|
||||
{describeSettings(r.settings)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-medium tabular-nums">{fmt(h.decode)}</TableCell>
|
||||
<TableCell className="text-right tabular-nums">{h.ttftMs != null ? `${Math.round(h.ttftMs)} ms` : "–"}</TableCell>
|
||||
<TableCell className="hidden text-right tabular-nums md:table-cell" title={h.prefill ? `at ${h.prefill.depth} tokens` : undefined}>
|
||||
<TableCell className="text-right font-medium tabular-nums">
|
||||
{fmt(h.decode)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">
|
||||
{h.ttftMs != null ? `${Math.round(h.ttftMs)} ms` : "–"}
|
||||
</TableCell>
|
||||
<TableCell
|
||||
className="hidden text-right tabular-nums md:table-cell"
|
||||
title={
|
||||
h.prefill ? `at ${h.prefill.depth} tokens` : undefined
|
||||
}
|
||||
>
|
||||
{fmt(h.prefill?.tps, 0)}
|
||||
</TableCell>
|
||||
<TableCell className="hidden text-right tabular-nums md:table-cell" title={h.peak ? `at ${h.peak.level} parallel` : undefined}>
|
||||
<TableCell
|
||||
className="hidden text-right tabular-nums md:table-cell"
|
||||
title={h.peak ? `at ${h.peak.level} parallel` : undefined}
|
||||
>
|
||||
{fmt(h.peak?.tps)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
|
||||
<BenchmarkStateBadge
|
||||
state={r.state}
|
||||
cancelling={!!r.cancelRequestedAt}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
|
||||
@@ -9,6 +9,8 @@ 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, ResourceStats, RunMeta, SweepVariant } from "@/lib/db/schema";
|
||||
@@ -90,7 +92,7 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
|
||||
const [data, setData] = useState(initial);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const { sweep } = data;
|
||||
const active = sweep.state === "queued" || sweep.state === "running";
|
||||
const active = sweep.state === "pending_approval" || sweep.state === "queued" || sweep.state === "running";
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
@@ -153,6 +155,7 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RequestedByBadge name={sweep.requestedBy} />
|
||||
<BenchmarkStateBadge state={sweep.state} cancelling={!!sweep.cancelRequestedAt && active} />
|
||||
{runIds.length >= 2 && (
|
||||
<Link href={`/benchmarks/compare?ids=${runIds.join(",")}`} className={buttonVariants({ variant: "outline", size: "sm" })}>
|
||||
@@ -179,6 +182,13 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
|
||||
{done} of {rows.length} variants finished. Each variant is deployed, benchmarked and removed again, one after another.
|
||||
</p>
|
||||
)}
|
||||
{sweep.state === "pending_approval" && (
|
||||
<AgentApprovalBar
|
||||
requestedBy={sweep.requestedBy}
|
||||
what={`run a sweep of ${rows.length} variants from ${sweep.base.name} (${sweep.params.map((p) => `${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 && <p className="text-sm text-destructive">{sweep.error}</p>}
|
||||
|
||||
{finished.length > 0 && (
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { ExternalLinkIcon, PencilIcon, PlayIcon, SendIcon, SquareIcon, Trash2Icon } from "lucide-react";
|
||||
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";
|
||||
@@ -83,6 +86,13 @@ export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment;
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h1 className="text-xl font-semibold">{d.name}</h1>
|
||||
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
|
||||
<RequestedByBadge name={d.requestedBy} />
|
||||
{d.protected && (
|
||||
<span className="inline-flex items-center gap-1 rounded-4xl border border-emerald-500/30 bg-emerald-500/10 px-2 text-xs text-emerald-700 dark:text-emerald-300">
|
||||
<ShieldCheckIcon className="size-3" />
|
||||
protected
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<Link href={`/${d.repoId}`} className="hover:underline">
|
||||
@@ -118,6 +128,19 @@ export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment;
|
||||
Start
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
title={d.protected ? "Agents can't touch it now; click to allow them again" : "Agents (API tokens) can't edit, stop, delete or benchmark a protected deployment, nor crowd it out of VRAM"}
|
||||
onClick={async () => {
|
||||
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 ? <ShieldCheckIcon /> : <ShieldIcon />}
|
||||
{d.protected ? "Protected" : "Protect"}
|
||||
</Button>
|
||||
<Link
|
||||
href={`/deployments/${d.id}/edit`}
|
||||
className={cn(buttonVariants({ variant: "outline" }), active && "pointer-events-none opacity-50")}
|
||||
@@ -153,6 +176,13 @@ export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment;
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{d.startRequestedAt && (
|
||||
<AgentApprovalBar
|
||||
requestedBy={d.requestedBy}
|
||||
what={`start this deployment (${d.runtimeName}${file ? `, ${file}` : ""}, context ${d.options.contextSize}${d.memoryMb ? `, ${formatBytes(d.memoryMb * 2 ** 20)} RAM limit` : ""})`}
|
||||
base={`/api/deployments/${d.id}`}
|
||||
/>
|
||||
)}
|
||||
|
||||
{d.state === "failed" && d.error && (
|
||||
<pre className="max-h-72 overflow-auto rounded-xl bg-destructive/10 px-4 py-3 text-xs whitespace-pre-wrap text-destructive">{d.error}</pre>
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import { ExternalLinkIcon, PlayIcon, RocketIcon, SquareIcon } from "lucide-react";
|
||||
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";
|
||||
@@ -12,23 +19,45 @@ import { formatBytes } from "@/lib/format";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
import { startDeployment, stopDeployment } from "./actions";
|
||||
|
||||
type Row = Omit<DeploymentRow, "startedAt" | "readyAt" | "stoppedAt" | "createdAt"> & {
|
||||
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";
|
||||
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"));
|
||||
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);
|
||||
const res = await fetch("/api/deployments", { cache: "no-store" }).catch(
|
||||
() => null,
|
||||
);
|
||||
if (res?.ok) setRows(await res.json());
|
||||
}
|
||||
useEffect(() => {
|
||||
@@ -40,7 +69,10 @@ export function DeploymentList({ rows: initial }: { rows: Row[] }) {
|
||||
return (
|
||||
<Card className="items-center gap-3 py-10 text-center">
|
||||
<RocketIcon className="size-8 text-muted-foreground" />
|
||||
<p className="text-sm text-muted-foreground">No deployments yet. Pick a runtime and a downloaded model to start one.</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No deployments yet. Pick a runtime and a downloaded model to start
|
||||
one.
|
||||
</p>
|
||||
<Link href="/deployments/new" className="text-sm underline">
|
||||
New deployment
|
||||
</Link>
|
||||
@@ -49,59 +81,130 @@ export function DeploymentList({ rows: initial }: { rows: Row[] }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{rows.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 (
|
||||
<Card key={r.id} className="gap-3 px-4 py-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
<Link href={`/deployments/${r.id}`} className="truncate font-medium hover:underline">
|
||||
{r.name}
|
||||
</Link>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{r.repoId}
|
||||
{file && ` · ${file}`}
|
||||
{r.options.mmproj && " · vision"}
|
||||
{r.options.draftFile && " · MTP/draft"}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">{r.runtimeName}</span>
|
||||
<div className="flex flex-col gap-3">
|
||||
{tokens.length > 0 && (
|
||||
<label className="flex items-center gap-2 self-end text-xs text-muted-foreground">
|
||||
Requested by
|
||||
<NativeSelect
|
||||
value={by}
|
||||
onChange={(e) => setBy(e.target.value)}
|
||||
className="h-7 text-xs"
|
||||
aria-label="Requested by"
|
||||
>
|
||||
<option value="">Anyone</option>
|
||||
<option value="-">Created in Kaname</option>
|
||||
{tokens.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{t} (API)
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</label>
|
||||
)}
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{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 (
|
||||
<Card key={r.id} className="gap-3 px-4 py-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
<Link
|
||||
href={`/deployments/${r.id}`}
|
||||
className="truncate font-medium hover:underline"
|
||||
>
|
||||
{r.name}
|
||||
</Link>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{r.repoId}
|
||||
{file && ` · ${file}`}
|
||||
{r.options.mmproj && " · vision"}
|
||||
{r.options.draftFile && " · MTP/draft"}
|
||||
</span>
|
||||
<span className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
|
||||
{r.runtimeName}
|
||||
<RequestedByBadge
|
||||
name={r.requestedBy}
|
||||
className="h-4 text-[10px]"
|
||||
/>
|
||||
{r.protected && (
|
||||
<span className="text-emerald-700 dark:text-emerald-300">
|
||||
protected
|
||||
</span>
|
||||
)}
|
||||
{r.startRequestedAt && (
|
||||
<span className="text-amber-700 dark:text-amber-300">
|
||||
start awaits approval
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<DeploymentStateBadge
|
||||
state={r.state}
|
||||
desiredState={r.desiredState}
|
||||
/>
|
||||
</div>
|
||||
<DeploymentStateBadge state={r.state} desiredState={r.desiredState} />
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||
<span className="tabular-nums">
|
||||
{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`}
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
{r.state === "running" && webUiUrl(r, hostname) && (
|
||||
<a href={webUiUrl(r, hostname)!} target="_blank" rel="noreferrer" className={buttonVariants({ size: "xs", variant: "outline" })}>
|
||||
<ExternalLinkIcon />
|
||||
Web UI
|
||||
</a>
|
||||
)}
|
||||
{isActive(r) ? (
|
||||
<Button size="xs" variant="outline" onClick={async () => (await stopDeployment(r.id)) && reload()}>
|
||||
<SquareIcon />
|
||||
Stop
|
||||
</Button>
|
||||
) : (
|
||||
<Button size="xs" onClick={async () => (await startDeployment(r.id)) && reload()}>
|
||||
<PlayIcon />
|
||||
Start
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||
<span className="tabular-nums">
|
||||
{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`}
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
{r.state === "running" && webUiUrl(r, hostname) && (
|
||||
<a
|
||||
href={webUiUrl(r, hostname)!}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={buttonVariants({
|
||||
size: "xs",
|
||||
variant: "outline",
|
||||
})}
|
||||
>
|
||||
<ExternalLinkIcon />
|
||||
Web UI
|
||||
</a>
|
||||
)}
|
||||
{isActive(r) ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={async () =>
|
||||
(await stopDeployment(r.id)) && reload()
|
||||
}
|
||||
>
|
||||
<SquareIcon />
|
||||
Stop
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="xs"
|
||||
onClick={async () =>
|
||||
(await startDeployment(r.id)) && reload()
|
||||
}
|
||||
>
|
||||
<PlayIcon />
|
||||
Start
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +1,27 @@
|
||||
import type { Metadata } from "next";
|
||||
import { listActivity } from "@/lib/agent-activity";
|
||||
import { listTokens } from "@/lib/api-tokens";
|
||||
import { getGuardrails } from "@/lib/settings";
|
||||
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] = await Promise.all([listTokens(), getGuardrails()]);
|
||||
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 (
|
||||
<div className="flex flex-col gap-4">
|
||||
<TokenSettings tokens={tokens} />
|
||||
<TokenSettings tokens={tokens} activity={activity} />
|
||||
<GuardrailSettings initial={guardrails} />
|
||||
<TuningSettings initial={tuning} runtimes={runtimes.map((r) => ({ id: r.id, name: r.name, pulled: r.imageState === "present" }))} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
"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";
|
||||
@@ -19,7 +20,13 @@ import {
|
||||
} 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 {
|
||||
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";
|
||||
@@ -27,25 +34,43 @@ 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 }: { tokens: ApiTokenRow[] }) {
|
||||
const [created, setCreated] = useState<{ name: string; token: string } | null>(null);
|
||||
export function TokenSettings({
|
||||
tokens,
|
||||
activity,
|
||||
}: {
|
||||
tokens: ApiTokenRow[];
|
||||
activity: Record<string, ActivityItem[]>;
|
||||
}) {
|
||||
const [created, setCreated] = useState<{
|
||||
name: string;
|
||||
token: string;
|
||||
} | null>(null);
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>API tokens</CardTitle>
|
||||
<CardDescription>
|
||||
For programs and agents calling Kaname's API at <code className="font-mono text-xs">/api/v1</code> with{" "}
|
||||
<code className="font-mono text-xs">Authorization: Bearer <token></code>. No token can delete models or files, change settings, or manage runtimes and
|
||||
tokens.
|
||||
For programs and agents calling Kaname's API at{" "}
|
||||
<code className="font-mono text-xs">/api/v1</code> with{" "}
|
||||
<code className="font-mono text-xs">
|
||||
Authorization: Bearer <token>
|
||||
</code>
|
||||
. No token can delete models or files, change settings, or manage
|
||||
runtimes and tokens.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<NewTokenForm onCreated={setCreated} />
|
||||
{created && (
|
||||
<div className="flex flex-col gap-1.5 rounded-lg border border-primary/40 bg-primary/5 px-4 py-3">
|
||||
<p className="text-sm font-medium">Token “{created.name}” created. Copy it now: it is not shown again.</p>
|
||||
<p className="text-sm font-medium">
|
||||
Token “{created.name}” created. Copy it now: it is not
|
||||
shown again.
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="min-w-0 flex-1 rounded-md bg-muted px-2 py-1 font-mono text-xs break-all">{created.token}</code>
|
||||
<code className="min-w-0 flex-1 rounded-md bg-muted px-2 py-1 font-mono text-xs break-all">
|
||||
{created.token}
|
||||
</code>
|
||||
<CopyButton value={created.token} label="Copy token" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -55,7 +80,7 @@ export function TokenSettings({ tokens }: { tokens: ApiTokenRow[] }) {
|
||||
) : (
|
||||
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
|
||||
{tokens.map((t) => (
|
||||
<TokenRow key={t.id} token={t} />
|
||||
<TokenRow key={t.id} token={t} activity={activity[t.id] ?? []} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
@@ -64,7 +89,11 @@ export function TokenSettings({ tokens }: { tokens: ApiTokenRow[] }) {
|
||||
);
|
||||
}
|
||||
|
||||
function NewTokenForm({ onCreated }: { onCreated: (t: { name: string; token: string }) => void }) {
|
||||
function NewTokenForm({
|
||||
onCreated,
|
||||
}: {
|
||||
onCreated: (t: { name: string; token: string }) => void;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [name, setName] = useState("");
|
||||
const [scopes, setScopes] = useState<TokenScope[]>(["models:read"]);
|
||||
@@ -74,9 +103,16 @@ function NewTokenForm({ onCreated }: { onCreated: (t: { name: string; token: str
|
||||
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 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})`);
|
||||
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();
|
||||
@@ -86,93 +122,269 @@ function NewTokenForm({ onCreated }: { onCreated: (t: { name: string; token: str
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={create} className="flex flex-col gap-3 rounded-lg border border-dashed px-4 py-3">
|
||||
<form
|
||||
onSubmit={create}
|
||||
className="flex flex-col gap-3 rounded-lg border border-dashed px-4 py-3"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
value={name}
|
||||
maxLength={40}
|
||||
disabled={busy}
|
||||
onChange={(e) => setName(e.target.value.toLowerCase().replace(/[^a-z0-9._-]/g, ""))}
|
||||
onChange={(e) =>
|
||||
setName(e.target.value.toLowerCase().replace(/[^a-z0-9._-]/g, ""))
|
||||
}
|
||||
placeholder="Name, e.g. hermes"
|
||||
aria-label="Token name"
|
||||
className="max-w-56"
|
||||
/>
|
||||
<Button type="submit" size="sm" disabled={busy || !name || scopes.length === 0}>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
disabled={busy || !name || scopes.length === 0}
|
||||
>
|
||||
<PlusIcon />
|
||||
Create token
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{TOKEN_SCOPES.map((s) => (
|
||||
<label key={s} className="flex cursor-pointer items-start gap-2 text-sm">
|
||||
<Checkbox checked={scopes.includes(s)} onCheckedChange={(v) => setScopes((cur) => (v ? [...cur, s] : cur.filter((x) => x !== s)))} className="mt-0.5" />
|
||||
<label
|
||||
key={s}
|
||||
className="flex cursor-pointer items-start gap-2 text-sm"
|
||||
>
|
||||
<Checkbox
|
||||
checked={scopes.includes(s)}
|
||||
onCheckedChange={(v) =>
|
||||
setScopes((cur) =>
|
||||
v ? [...cur, s] : cur.filter((x) => x !== s),
|
||||
)
|
||||
}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<span className="flex flex-col">
|
||||
<code className="font-mono text-xs">{s}</code>
|
||||
<span className="text-xs text-muted-foreground">{SCOPE_LABEL[s]}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{SCOPE_LABEL[s]}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">The name is shown as “requested by” on everything the token asks for.</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
The name is shown as “requested by” on everything the token
|
||||
asks for.
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function TokenRow({ token }: { token: ApiTokenRow }) {
|
||||
function TokenRow({
|
||||
token,
|
||||
activity,
|
||||
}: {
|
||||
token: ApiTokenRow;
|
||||
activity: ActivityItem[];
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const revoked = !!token.revokedAt;
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [scopes, setScopes] = useState<TokenScope[]>(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`);
|
||||
else
|
||||
toast.success(
|
||||
method === "POST"
|
||||
? `Token "${token.name}" revoked`
|
||||
: `Token "${token.name}" deleted`,
|
||||
);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-2.5">
|
||||
<BotIcon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">{token.name}</span>
|
||||
<code className="font-mono text-xs text-muted-foreground">{token.prefix}…</code>
|
||||
<span className="flex flex-wrap gap-1">
|
||||
{token.scopes.map((s) => (
|
||||
<Badge key={s} variant="outline" className="font-mono text-[10px]">
|
||||
{s}
|
||||
</Badge>
|
||||
))}
|
||||
</span>
|
||||
{revoked && <Badge variant="destructive">revoked</Badge>}
|
||||
<span className="ml-auto text-xs text-muted-foreground">
|
||||
{token.lastUsedAt ? (
|
||||
<>
|
||||
used <LocalTime value={token.lastUsedAt} />
|
||||
</>
|
||||
) : (
|
||||
"never used"
|
||||
<div className="flex flex-col gap-2 px-4 py-2.5">
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<BotIcon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">{token.name}</span>
|
||||
<code className="font-mono text-xs text-muted-foreground">
|
||||
{token.prefix}…
|
||||
</code>
|
||||
<span className="flex flex-wrap gap-1">
|
||||
{token.scopes.map((s) => (
|
||||
<Badge key={s} variant="outline" className="font-mono text-[10px]">
|
||||
{s}
|
||||
</Badge>
|
||||
))}
|
||||
</span>
|
||||
{revoked && <Badge variant="destructive">revoked</Badge>}
|
||||
<span className="ml-auto text-xs text-muted-foreground">
|
||||
{token.lastUsedAt ? (
|
||||
<>
|
||||
used <LocalTime value={token.lastUsedAt} />
|
||||
</>
|
||||
) : (
|
||||
"never used"
|
||||
)}
|
||||
</span>
|
||||
{activity.length > 0 && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowActivity((v) => !v)}
|
||||
>
|
||||
Activity ({activity.length})
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button variant="ghost" size="sm" />}>{revoked ? <Trash2Icon /> : "Revoke"}</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{revoked ? "Delete" : "Revoke"} token “{token.name}”?
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{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."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={() => act(revoked ? "DELETE" : "POST")}>
|
||||
{revoked ? "Delete" : "Revoke"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
{!revoked && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setEditing((v) => !v)}
|
||||
>
|
||||
Scopes
|
||||
</Button>
|
||||
)}
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button variant="ghost" size="sm" />}>
|
||||
{revoked ? <Trash2Icon /> : "Revoke"}
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{revoked ? "Delete" : "Revoke"} token “{token.name}
|
||||
”?
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{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."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant="destructive"
|
||||
onClick={() => act(revoked ? "DELETE" : "POST")}
|
||||
>
|
||||
{revoked ? "Delete" : "Revoke"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
{editing && (
|
||||
<div className="flex flex-col gap-2 rounded-lg border p-3">
|
||||
{TOKEN_SCOPES.map((s) => (
|
||||
<label
|
||||
key={s}
|
||||
className="flex cursor-pointer items-start gap-2 text-sm"
|
||||
>
|
||||
<Checkbox
|
||||
checked={scopes.includes(s)}
|
||||
onCheckedChange={(v) =>
|
||||
setScopes((cur) =>
|
||||
v ? [...cur, s] : cur.filter((x) => x !== s),
|
||||
)
|
||||
}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<span className="flex flex-col">
|
||||
<span className="font-mono text-xs">{s}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{SCOPE_LABEL[s]}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
<Button
|
||||
size="sm"
|
||||
className="self-start"
|
||||
disabled={scopes.length === 0}
|
||||
onClick={saveScopes}
|
||||
>
|
||||
Save scopes
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{showActivity && <ActivityList items={activity} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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, (id: string) => 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 (
|
||||
<ul className="flex max-h-80 flex-col gap-1 overflow-y-auto rounded-lg border p-2 text-xs">
|
||||
{items.map((a) => (
|
||||
<li key={a.id} className="flex flex-wrap items-baseline gap-x-2">
|
||||
<span className="text-muted-foreground tabular-nums">
|
||||
<LocalTime value={a.createdAt} />
|
||||
</span>
|
||||
<span className="font-mono">{a.action}</span>
|
||||
<span
|
||||
className={
|
||||
a.outcome === "refused"
|
||||
? "text-destructive"
|
||||
: a.outcome === "pending_approval"
|
||||
? "text-amber-700 dark:text-amber-300"
|
||||
: "text-emerald-700 dark:text-emerald-300"
|
||||
}
|
||||
>
|
||||
{a.outcome === "refused"
|
||||
? `refused: ${a.code}`
|
||||
: a.outcome === "pending_approval"
|
||||
? "awaiting approval"
|
||||
: "ok"}
|
||||
</span>
|
||||
{a.targetType && a.targetId && TARGET_HREF[a.targetType] && (
|
||||
<Link
|
||||
href={TARGET_HREF[a.targetType](a.targetId)}
|
||||
className="underline"
|
||||
>
|
||||
{a.targetType}
|
||||
</Link>
|
||||
)}
|
||||
{a.message && (
|
||||
<span className="w-full text-muted-foreground">{a.message}</span>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
"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<ApprovalMode>(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<string[]>(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 } = {}) => (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={id}>{label}</Label>
|
||||
<Input id={id} value={value} onChange={(e) => set((opts.decimal ? decText : intText)(e.target.value))} inputMode={opts.decimal ? "decimal" : "numeric"} placeholder={opts.placeholder} />
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-1.5">
|
||||
<ShieldCheckIcon className="size-4 text-muted-foreground" />
|
||||
Guardrails for API deployments and benchmarks
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
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.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={save} className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="t-mode">Approval</Label>
|
||||
<NativeSelect id="t-mode" value={mode} onChange={(e) => setMode(e.target.value as ApprovalMode)} className="max-w-md">
|
||||
<option value="approve">Ask me: starts, runs and sweeps wait for approval</option>
|
||||
<option value="auto">Automatic: they go ahead right away</option>
|
||||
</NativeSelect>
|
||||
<p className="text-xs text-muted-foreground">Creating or editing a stopped deployment, stopping and deleting their own ones never needs approval.</p>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{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)}
|
||||
</div>
|
||||
<p className="-mt-2 text-xs text-muted-foreground">
|
||||
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.
|
||||
</p>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{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" })}
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>Runtimes agents may use</Label>
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1.5">
|
||||
{runtimes.map((r) => (
|
||||
<label key={r.id} className="flex cursor-pointer items-center gap-2 text-sm">
|
||||
<Checkbox checked={allowed.includes(r.id)} onCheckedChange={(v) => setAllowed((cur) => (v ? [...cur, r.id] : cur.filter((x) => x !== r.id)))} />
|
||||
{r.name}
|
||||
{!r.pulled && <span className="text-xs text-muted-foreground">(not pulled)</span>}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">None ticked: every runtime with a pulled image.</p>
|
||||
</div>
|
||||
{(
|
||||
[
|
||||
["llama.cpp", llamaArgs, setLlamaArgs],
|
||||
["vllm", vllmArgs, setVllmArgs],
|
||||
] as const
|
||||
).map(([engine, value, set]) => (
|
||||
<div key={engine} className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={`t-args-${engine}`}>Extra argument flags agents may use: {engine}</Label>
|
||||
<textarea
|
||||
id={`t-args-${engine}`}
|
||||
value={value}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
<button type="button" className="self-start text-xs text-muted-foreground underline" onClick={() => set(DEFAULT_ALLOWED_ARGS[engine].join(" "))}>
|
||||
Reset to the default list
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{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."}
|
||||
</p>
|
||||
<Button type="submit" className="self-start" disabled={busy || !!argError}>
|
||||
Save guardrails
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
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 } from "@/lib/api-tokens";
|
||||
import { deleteToken, revokeToken, TokenError, updateTokenScopes } from "@/lib/api-tokens";
|
||||
|
||||
/** Revoke a token: it stops working immediately. */
|
||||
export const POST = withAuth<RouteContext<"/api/api-tokens/[id]">>(async (_req, { params }) => {
|
||||
@@ -14,6 +15,19 @@ export const POST = withAuth<RouteContext<"/api/api-tokens/[id]">>(async (_req,
|
||||
}
|
||||
});
|
||||
|
||||
/** Change an active token's scopes. */
|
||||
export const PATCH = withAuth<RouteContext<"/api/api-tokens/[id]">>(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<RouteContext<"/api/api-tokens/[id]">>(async (_req, { params }) => {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
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<RouteContext<"/api/benchmarks/[id]/approve">>(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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
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<RouteContext<"/api/benchmarks/[id]/reject">>(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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
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<RouteContext<"/api/deployments/[id]/approve">>(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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
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<RouteContext<"/api/deployments/[id]/protect">>(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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
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<RouteContext<"/api/deployments/[id]/reject">>(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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
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<RouteContext<"/api/sweeps/[id]/approve">>(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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
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<RouteContext<"/api/sweeps/[id]/reject">>(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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
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<RouteContext<"/api/v1/benchmarks/[id]/cancel">>("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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
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=<s> (max 900) blocks
|
||||
* until it is finished or waits for approval; ?full=1 adds BetterBench's full summary.
|
||||
*/
|
||||
export const GET = withToken<RouteContext<"/api/v1/benchmarks/[id]">>("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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
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, { token }) => {
|
||||
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=<id>,<id>");
|
||||
return v1Json(await compareRuns(ids, token));
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
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=<id>, ?requested_by=<token name>, ?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 benchmark run (kind "run") or a paired A/B (kind "ab") 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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
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=<s> (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<RouteContext<"/api/v1/deployments/[id]">>("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<RouteContext<"/api/v1/deployments/[id]">>("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<RouteContext<"/api/v1/deployments/[id]">>("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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
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<RouteContext<"/api/v1/deployments/[id]/start">>("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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
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<RouteContext<"/api/v1/deployments/[id]/stop">>("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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
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";
|
||||
@@ -25,7 +26,10 @@ const Body = z
|
||||
export const POST = withToken("downloads:create", async (req, { token }) => {
|
||||
try {
|
||||
const body = Body.parse(await req.json());
|
||||
const r = await requestDownload(token, body);
|
||||
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,
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
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<string, string> = {
|
||||
pending_approval: "Waiting for the user to approve it. Don't retry; check again in a few minutes.",
|
||||
queued: "Waiting for a free download slot.",
|
||||
downloading: "Downloading; check again in a minute.",
|
||||
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.",
|
||||
@@ -17,13 +18,19 @@ const NEXT: Record<string, string> = {
|
||||
interrupted: "Interrupted by a Kaname restart; the user can resume it.",
|
||||
};
|
||||
|
||||
/** Job state with per-file progress. The hf log only with ?log=N (last N lines, max 200). */
|
||||
const SETTLED = new Set(["pending_approval", "completed", "failed", "cancelled", "interrupted"]);
|
||||
|
||||
/**
|
||||
* Job state with per-file progress. ?wait=<s> (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<RouteContext<"/api/v1/jobs/[id]">>("models:read", async (req, { params }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
const job = await getJob(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(new URL(req.url).searchParams.get("log")) || 0));
|
||||
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({
|
||||
@@ -50,6 +57,7 @@ export const GET = withToken<RouteContext<"/api/v1/jobs/[id]">>("models:read", a
|
||||
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) {
|
||||
|
||||
+32
-3
@@ -1,12 +1,12 @@
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { size, v1Json } from "@/lib/api-v1";
|
||||
import { getGuardrails } from "@/lib/settings";
|
||||
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 = await getGuardrails();
|
||||
const [g, t] = await Promise.all([getGuardrails(), getTuning()]);
|
||||
return v1Json({
|
||||
token: { name: token.name, scopes: token.scopes },
|
||||
guardrails: {
|
||||
@@ -18,13 +18,42 @@ export const GET = withToken(null, async (_req, { token }) => {
|
||||
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}[?log=50]",
|
||||
"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",
|
||||
],
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
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<RouteContext<"/api/v1/sweeps/[id]/cancel">>("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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
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=<s> (max 900) blocks until it is finished or waits for approval. */
|
||||
export const GET = withToken<RouteContext<"/api/v1/sweeps/[id]">>("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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user