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
@@ -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