API for agents: tokens, /api/v1, guardrails, approval

- Scoped bearer tokens (models:read, downloads:create), stored as SHA-256, managed in
  Settings -> API tokens. Only /api/v1 accepts them; the rest stays OIDC-only.
- /api/v1: Hub lookup, library list with the search filters, download requests through the
  existing add-model/queue path (idempotent), compact job status, disk space.
- Guardrails: approval mode (default approve), max size per request, minimum free space incl.
  reserved bytes, max open agent jobs, author allowlist. Approve/reject in the UI; "requested by"
  shown and filterable.
- docs/api.md (incl. Traefik forward-auth bypass), docs/agent/SKILL.md, DB-backed API tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-20 16:14:45 +02:00
1 parent 2532f2f2b3
commit 7b1c8070b3
52 files changed
+4583 -35

No files matched your search

+180
View File
@@ -0,0 +1,180 @@
import "server-only";
import { and, eq, inArray, isNotNull, ne, sql } from "drizzle-orm";
import { checkAuthor, checkGuardrails, type Guardrails } from "@/lib/agent-guardrails";
import { newPaths, resolveRequestPaths } from "@/lib/agent-selection";
import type { TokenIdentity } from "@/lib/api-tokens";
import { db } from "@/lib/db/client";
import { jobs, modelFiles, models } from "@/lib/db/schema";
import { lookupRepo } from "@/lib/hub/lookup";
import { JobError, OPEN_STATES, queueDownload } from "@/lib/jobs";
import { purgeModelRows } from "@/lib/model-purge";
import { addFilesToModel, addModel, ModelError, restoreSelection } from "@/lib/models";
import { escapeGlob } from "@/lib/selection";
import { getGuardrails, getRecommendedRoles } from "@/lib/settings";
import { addTag, normalizeTagName } from "@/lib/tags";
import { getWorkerStatus } from "@/lib/worker-status";
export type DownloadRequest = {
repoId: string;
sha: string;
/** Branch to track for update checks (default "main"). */
revision?: string;
quant?: string;
include?: string[];
tags?: string[];
};
export type DownloadOutcome = {
/** false: the same repo + commit + files was requested before; nothing new was queued. */
created: boolean;
modelId: string;
jobId: string | null;
state: string;
requestedBytes: number;
files: string[];
message: string;
};
/** Bytes that open download jobs still have to fetch (pending approval included). */
export async function reservedBytes(): Promise<number> {
const [r] = await db()
.select({ n: sql<number>`coalesce(sum(${jobs.totalBytes} - ${jobs.doneBytes}), 0)` })
.from(jobs)
.where(and(eq(jobs.kind, "download"), inArray(jobs.state, [...OPEN_STATES])));
return Number(r.n);
}
/** API-requested jobs that are pending approval, queued or running (all tokens). */
export async function openAgentJobs(): Promise<number> {
const [r] = await db()
.select({ n: sql<number>`count(*)` })
.from(jobs)
.where(and(isNotNull(jobs.requestedByTokenId), inArray(jobs.state, [...OPEN_STATES])));
return Number(r.n);
}
function stateMessage(state: string, created: boolean): string {
if (state === "pending_approval") {
return `${created ? "Requested" : "Already requested"}; waiting for the user to approve it in Kaname. Do not retry: check GET /api/v1/jobs/{jobId} every few minutes.`;
}
if (state === "queued" || state === "downloading" || state === "verifying") return `${created ? "Queued" : "Already queued"}; poll GET /api/v1/jobs/{jobId} for progress.`;
if (state === "completed") return "Already downloaded.";
return `The last download ended as "${state}"; ask the user to retry it in Kaname.`;
}
/** Latest job of a model, for answers to repeated requests. */
async function latestJob(modelId: string) {
return db().query.jobs.findFirst({ columns: { id: true, state: true }, where: eq(jobs.modelId, modelId), orderBy: (j, { desc }) => desc(j.createdAt) });
}
/**
* A download requested through the API. Checks the author allowlist, resolves the files at the
* pinned commit, applies the guardrails, then uses the same addModel / addFilesToModel / queue path
* as the UI. Repeating a request returns what exists instead of queueing a duplicate.
*/
export async function requestDownload(token: TokenIdentity, req: DownloadRequest, guardrails?: Guardrails): Promise<DownloadOutcome> {
const g = guardrails ?? (await getGuardrails());
// The allowlist first, before anything goes to the Hub.
checkAuthor(g, req.repoId);
(req.tags ?? []).forEach(normalizeTagName); // validate before anything is written
const hub = await lookupRepo(req.repoId, req.sha);
const paths = resolveRequestPaths(hub.files, req, await getRecommendedRoles());
const size = new Map(hub.files.map((f) => [f.path, f.size]));
const requestedBy = { tokenId: token.id, name: token.name };
const pendingApproval = g.approvalMode === "approve";
const existing = await db().query.models.findFirst({ where: sql`lower(${models.repoId}) = lower(${hub.repoId})` });
if (existing && existing.pinnedSha !== hub.sha) {
throw new ModelError(
"already_exists",
`${existing.repoId} is already in the library, pinned to commit ${existing.pinnedSha}; you asked for ${hub.sha}. Updating a model is done by the user in Kaname, not through the API.`,
409,
);
}
let add = paths;
if (existing) {
const selected = await db().select({ path: modelFiles.path }).from(modelFiles).where(and(eq(modelFiles.modelId, existing.id), eq(modelFiles.selected, true)));
add = newPaths(paths, selected.map((f) => f.path));
if (add.length === 0) {
const job = await latestJob(existing.id);
const state = job?.state ?? existing.status;
return { created: false, modelId: existing.id, jobId: job?.id ?? null, state, requestedBytes: 0, files: paths, message: stateMessage(state, false) };
}
const open = await db().query.jobs.findFirst({ columns: { id: true, state: true }, where: and(eq(jobs.modelId, existing.id), inArray(jobs.state, [...OPEN_STATES])) });
if (open) {
throw new JobError("busy", `${existing.repoId} has a download that is still ${open.state.replace("_", " ")} (job ${open.id}). Request the other files once it has finished.`, 409);
}
}
const requestBytes = add.reduce((s, p) => s + (size.get(p) ?? 0), 0);
const worker = await getWorkerStatus();
checkGuardrails(g, {
repoId: hub.repoId,
requestBytes,
freeBytes: worker.online ? worker.modelsDirFreeBytes : null,
reservedBytes: await reservedBytes(),
openAgentJobs: await openAgentJobs(),
});
let modelId: string;
let jobId: string;
if (existing) {
modelId = existing.id;
({ jobId } = await addFilesToModel(existing.id, add, { pendingApproval, requestedBy }));
} else {
({ id: modelId } = await addModel({
repoId: hub.repoId,
revision: req.revision?.trim() || "main",
sha: hub.sha,
rule: { include: paths.map(escapeGlob), exclude: [] },
requestedBy,
}));
({ jobId } = await queueDownload(modelId, "initial", { pendingApproval, requestedBy }));
}
for (const tag of req.tags ?? []) await addTag(modelId, tag);
const state = pendingApproval ? "pending_approval" : "queued";
return { created: true, modelId, jobId, state, requestedBytes: requestBytes, files: paths, message: stateMessage(state, true) };
}
async function pendingJob(jobId: string) {
const job = await db().query.jobs.findFirst({ where: eq(jobs.id, jobId) });
if (!job) throw new JobError("not_found", "Job not found.", 404);
if (job.state !== "pending_approval") throw new JobError("not_cancellable", `This job doesn't wait for approval (it is ${job.state}).`, 409);
return job;
}
/** Let an API-requested download start. */
export async function approveJob(jobId: string): Promise<void> {
const job = await pendingJob(jobId);
const d = db();
await d.batch([
d.update(jobs).set({ state: "queued" }).where(and(eq(jobs.id, job.id), eq(jobs.state, "pending_approval"))),
d.update(models).set({ status: "downloading" }).where(eq(models.id, job.modelId)),
]);
}
/**
* Turn an API-requested download down. A new model that was only added by this request leaves the
* library again; for added files, the model's previous selection is restored.
*/
export async function rejectJob(jobId: string): Promise<{ removedModel: boolean }> {
const job = await pendingJob(jobId);
await db()
.update(jobs)
.set({ state: "cancelled", finishedAt: new Date(), errorMessage: "Rejected by the user." })
.where(eq(jobs.id, job.id));
if (job.purpose === "initial") {
// Only this request ever touched the model: nothing on disk, so it leaves the library again.
const [{ n }] = await db().select({ n: sql<number>`count(*)` }).from(jobs).where(and(eq(jobs.modelId, job.modelId), ne(jobs.id, job.id)));
if (Number(n) === 0) {
await purgeModelRows(job.modelId);
return { removedModel: true };
}
}
// A pending job never changed the model's status, so only the selection needs restoring.
if (job.result?.previousRule) await restoreSelection(job.modelId, job.result.previousRule);
return { removedModel: false };
}
+133
View File
@@ -0,0 +1,133 @@
// Guardrails for downloads requested through the API (an autonomous agent, not a person in the
// UI). Pure: settings parsing and the checks themselves; the request flow is in agent-downloads.ts.
export const APPROVAL_MODES = ["approve", "auto"] as const;
export type ApprovalMode = (typeof APPROVAL_MODES)[number];
export type Guardrails = {
/** approve: requests wait as "pending approval" until someone confirms them in the UI. */
approvalMode: ApprovalMode;
/** Largest download one request may add. */
maxRequestBytes: number;
/** Free space that must remain on the models folder after the download. */
minFreeBytes: number;
/** API-requested jobs that may be pending approval, queued or running at once (all tokens). */
maxOpenJobs: number;
/** Hub authors (orgs/users) the API may download from; empty = any. Case-insensitive. */
allowedAuthors: string[];
};
const GB = 1_000_000_000;
export const DEFAULT_GUARDRAILS: Guardrails = {
approvalMode: "approve",
maxRequestBytes: 60 * GB,
minFreeBytes: 100 * GB,
maxOpenJobs: 2,
allowedAuthors: [],
};
export class GuardrailError extends Error {
constructor(
public code: "too_large" | "disk_space" | "disk_unknown" | "too_many_jobs" | "author_not_allowed",
message: string,
public status = 422,
) {
super(message);
}
}
const AUTHOR_RE = /^[A-Za-z0-9][\w.-]{0,95}$/;
/** Stored value merged over the defaults; anything invalid falls back to the default. */
export function parseGuardrails(v: unknown): Guardrails {
const o = (v && typeof v === "object" ? v : {}) as Record<string, unknown>;
const num = (x: unknown, min: number, def: number) => (typeof x === "number" && Number.isFinite(x) && x >= min ? Math.round(x) : def);
return {
approvalMode: APPROVAL_MODES.includes(o.approvalMode as ApprovalMode) ? (o.approvalMode as ApprovalMode) : DEFAULT_GUARDRAILS.approvalMode,
maxRequestBytes: num(o.maxRequestBytes, 1, DEFAULT_GUARDRAILS.maxRequestBytes),
minFreeBytes: num(o.minFreeBytes, 0, DEFAULT_GUARDRAILS.minFreeBytes),
maxOpenJobs: num(o.maxOpenJobs, 1, DEFAULT_GUARDRAILS.maxOpenJobs),
allowedAuthors: Array.isArray(o.allowedAuthors) ? o.allowedAuthors.filter((a): a is string => typeof a === "string" && AUTHOR_RE.test(a)) : [],
};
}
/** "unsloth, ggml-org Qwen" → ["unsloth", "ggml-org", "Qwen"]; throws on an invalid name. */
export function parseAuthorList(text: string): string[] {
const out: string[] = [];
for (const a of text.split(/[\s,]+/).filter(Boolean)) {
if (!AUTHOR_RE.test(a)) throw new Error(`"${a}" is not a valid Hugging Face user or organization name.`);
if (!out.some((x) => x.toLowerCase() === a.toLowerCase())) out.push(a);
}
return out;
}
/** Plain GB (10^9), as the Hub and the settings use: "74.2 GB". */
export function gb(bytes: number): string {
return `${(bytes / GB).toFixed(1)} GB`;
}
export type GuardrailInput = {
repoId: string;
/** Bytes this request would download. */
requestBytes: number;
/** Free bytes on the models folder (worker heartbeat), or null if unknown. */
freeBytes: number | null;
/** Bytes other open jobs still have to download. */
reservedBytes: number;
/** API-requested jobs that are pending approval, queued or running right now. */
openAgentJobs: number;
};
/** The author allowlist alone (checked before anything goes to the Hub). */
export function checkAuthor(g: Guardrails, repoId: string): void {
const author = repoId.split("/")[0];
if (g.allowedAuthors.length > 0 && !g.allowedAuthors.some((a) => a.toLowerCase() === author.toLowerCase())) {
throw new GuardrailError(
"author_not_allowed",
`author "${author}" is not on the allowlist (${g.allowedAuthors.join(", ")}). Pick a repo from one of these authors, or ask the user to extend the allowlist.`,
403,
);
}
}
/** Throws a GuardrailError with a message an agent can act on; returns normally if allowed. */
export function checkGuardrails(g: Guardrails, x: GuardrailInput): void {
checkAuthor(g, x.repoId);
if (x.requestBytes > g.maxRequestBytes) {
throw new GuardrailError(
"too_large",
`exceeds max size per request ${gb(g.maxRequestBytes)}: requested ${gb(x.requestBytes)}. Pick a smaller quant or fewer files.`,
);
}
if (x.openAgentJobs >= g.maxOpenJobs) {
throw new GuardrailError(
"too_many_jobs",
`too many agent downloads at once: ${x.openAgentJobs} pending or running, the limit is ${g.maxOpenJobs}. Wait until one has finished (or been approved and finished) before requesting another.`,
429,
);
}
if (x.freeBytes == null) {
throw new GuardrailError("disk_unknown", "free disk space is unknown (the Kaname worker is offline). Try again later.", 503);
}
const after = x.freeBytes - x.reservedBytes - x.requestBytes;
if (after < g.minFreeBytes) {
throw new GuardrailError(
"disk_space",
`not enough disk space: ${gb(x.requestBytes)} requested, ${gb(x.freeBytes)} free` +
(x.reservedBytes > 0 ? ` (${gb(x.reservedBytes)} of it reserved by other downloads)` : "") +
`, and at least ${gb(g.minFreeBytes)} must stay free (${gb(Math.max(0, after))} would be left). Pick a smaller quant or ask the user to free space.`,
507,
);
}
}
export function describeGuardrails(g: Guardrails): string {
return [
g.approvalMode === "approve" ? "requests wait for approval" : "downloads start immediately",
`max ${gb(g.maxRequestBytes)} per request`,
`${gb(g.minFreeBytes)} must stay free`,
`max ${g.maxOpenJobs} agent jobs at once`,
g.allowedAuthors.length ? `authors: ${g.allowedAuthors.join(", ")}` : "any author",
].join(" · ");
}
+62
View File
@@ -0,0 +1,62 @@
// Which files an API download request means, from a quant name or include globs, the same way the
// Add model dialog picks them. Pure.
import { fileRole, type FileRole } from "@/lib/file-roles";
import { recommendFiles } from "@/lib/recommend";
import { matchesAny, quantGroup } from "@/lib/selection";
type File = { path: string; size: number };
export class SelectionError extends Error {
code = "empty_selection";
status = 400;
}
/** Quant group of a model-weight file (not mmproj/MTP/imatrix), e.g. "Q4_K_M", "UD-Q4_K_XL". */
function weightQuant(path: string): string | null {
return fileRole(path) === "model" ? quantGroup(path) : null;
}
/** Quants in a repo (model weights only) with file count and total size, in file order. */
export function quantSummary(files: File[]): { quant: string; files: number; bytes: number }[] {
const out = new Map<string, { quant: string; files: number; bytes: number }>();
for (const f of files) {
const q = weightQuant(f.path);
if (!q) continue;
const e = out.get(q) ?? { quant: q, files: 0, bytes: 0 };
e.files++;
e.bytes += f.size;
out.set(q, e);
}
return [...out.values()];
}
/**
* Paths for a request: the weight files of `quant` (all split parts) plus the companion files of the
* recommended kinds (Settings → Downloads), or every file matching one of the `include` globs.
*/
export function resolveRequestPaths(files: File[], req: { quant?: string; include?: string[] }, recommendedRoles: FileRole[]): string[] {
if (req.quant) {
const want = req.quant.trim().toLowerCase();
const weights = files.filter((f) => weightQuant(f.path)?.toLowerCase() === want).map((f) => f.path);
if (weights.length === 0) {
const available = quantSummary(files).map((q) => q.quant);
throw new SelectionError(
available.length
? `quant "${req.quant}" not found in this repo. Available: ${available.join(", ")}.`
: `quant "${req.quant}" not found: this repo has no GGUF quants. Use "include" globs instead (e.g. ["*.safetensors", "*.json"]).`,
);
}
return [...new Set([...weights, ...recommendFiles(files, weights, recommendedRoles)])].sort();
}
const globs = req.include ?? [];
const paths = files.filter((f) => matchesAny(f.path, globs)).map((f) => f.path);
if (paths.length === 0) throw new SelectionError(`no file in this repo matches ${JSON.stringify(globs)}. Look up the repo to see its files.`);
return paths.sort();
}
/** Files a request adds to what's already selected, for size checks and idempotency. */
export function newPaths(requested: string[], selected: Iterable<string>): string[] {
const have = new Set(selected);
return requested.filter((p) => !have.has(p));
}
+192
View File
@@ -0,0 +1,192 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { describe, it } from "node:test";
import { checkAuthor, checkGuardrails, DEFAULT_GUARDRAILS, type GuardrailError, type GuardrailInput, parseAuthorList, parseGuardrails } from "./agent-guardrails";
import { newPaths, quantSummary, resolveRequestPaths } from "./agent-selection";
import { bearerToken, generateToken, hashToken, isScope } from "./api-token-core";
import { parseModelFilters } from "./api-v1-filters";
import { EMPTY_FILTERS, facetValues, matchesFilters, type SearchableModel } from "./search";
const GB = 1e9;
describe("API tokens", () => {
it("generates kn_ tokens whose hash and prefix match", () => {
const t = generateToken();
assert.match(t.token, /^kn_[A-Za-z0-9_-]{43}$/);
assert.equal(t.hash, hashToken(t.token));
assert.ok(t.token.startsWith(t.prefix));
assert.notEqual(generateToken().token, t.token);
});
it("reads only well-formed bearer headers", () => {
const { token } = generateToken();
assert.equal(bearerToken(`Bearer ${token}`), token);
assert.equal(bearerToken(`bearer ${token} `), token);
assert.equal(bearerToken(token), null);
assert.equal(bearerToken("Bearer kn_short"), null);
assert.equal(bearerToken("Basic abc"), null);
assert.equal(bearerToken(null), null);
});
it("knows the scopes", () => {
assert.ok(isScope("models:read"));
assert.ok(isScope("downloads:create"));
assert.ok(!isScope("models:delete"));
assert.ok(!isScope("settings:write"));
});
});
describe("guardrails", () => {
const ok: GuardrailInput = { repoId: "unsloth/Qwen3-8B-GGUF", requestBytes: 5 * GB, freeBytes: 500 * GB, reservedBytes: 0, openAgentJobs: 0 };
const rejects = (g: Partial<typeof DEFAULT_GUARDRAILS>, x: Partial<GuardrailInput>, code: GuardrailError["code"], message: RegExp) =>
assert.throws(
() => checkGuardrails({ ...DEFAULT_GUARDRAILS, ...g }, { ...ok, ...x }),
(err: GuardrailError) => err.code === code && message.test(err.message),
);
it("defaults: approve, 60 GB, 100 GB free, 2 jobs, any author", () => {
assert.deepEqual(parseGuardrails(null), DEFAULT_GUARDRAILS);
assert.equal(DEFAULT_GUARDRAILS.approvalMode, "approve");
assert.equal(DEFAULT_GUARDRAILS.maxRequestBytes, 60 * GB);
assert.equal(DEFAULT_GUARDRAILS.minFreeBytes, 100 * GB);
assert.equal(DEFAULT_GUARDRAILS.maxOpenJobs, 2);
assert.deepEqual(DEFAULT_GUARDRAILS.allowedAuthors, []);
});
it("falls back to defaults for invalid stored values", () => {
const g = parseGuardrails({ approvalMode: "yolo", maxRequestBytes: -1, minFreeBytes: "x", maxOpenJobs: 0, allowedAuthors: ["ok", "../bad"] });
assert.equal(g.approvalMode, "approve");
assert.equal(g.maxRequestBytes, DEFAULT_GUARDRAILS.maxRequestBytes);
assert.equal(g.minFreeBytes, DEFAULT_GUARDRAILS.minFreeBytes);
assert.equal(g.maxOpenJobs, DEFAULT_GUARDRAILS.maxOpenJobs);
assert.deepEqual(g.allowedAuthors, ["ok"]);
});
it("passes a request within all limits", () => {
checkGuardrails(DEFAULT_GUARDRAILS, ok);
});
it("rejects requests over the max size, with both sizes in the message", () => {
rejects({}, { requestBytes: 74.2 * GB }, "too_large", /exceeds max size per request 60\.0 GB: requested 74\.2 GB/);
});
it("rejects when the minimum free space would not remain", () => {
rejects({}, { requestBytes: 20 * GB, freeBytes: 110 * GB }, "disk_space", /at least 100\.0 GB must stay free/);
});
it("counts space reserved by other open downloads", () => {
checkGuardrails(DEFAULT_GUARDRAILS, { ...ok, requestBytes: 20 * GB, freeBytes: 130 * GB });
rejects({}, { requestBytes: 20 * GB, freeBytes: 130 * GB, reservedBytes: 20 * GB }, "disk_space", /20\.0 GB of it reserved/);
});
it("rejects when free space is unknown (worker offline)", () => {
rejects({}, { freeBytes: null }, "disk_unknown", /worker is offline/);
});
it("rejects when too many agent jobs are open", () => {
rejects({}, { openAgentJobs: 2 }, "too_many_jobs", /2 pending or running, the limit is 2/);
checkGuardrails({ ...DEFAULT_GUARDRAILS, maxOpenJobs: 3 }, { ...ok, openAgentJobs: 2 });
});
it("enforces the author allowlist case-insensitively", () => {
const g = { allowedAuthors: ["unsloth", "ggml-org"] };
checkAuthor({ ...DEFAULT_GUARDRAILS, ...g }, "Unsloth/x");
rejects(g, { repoId: "TheBloke/x-GGUF" }, "author_not_allowed", /author "TheBloke" is not on the allowlist \(unsloth, ggml-org\)/);
});
it("parses the allowlist text", () => {
assert.deepEqual(parseAuthorList("unsloth, ggml-org Qwen,unsloth"), ["unsloth", "ggml-org", "Qwen"]);
assert.deepEqual(parseAuthorList(" "), []);
assert.throws(() => parseAuthorList("ok, ../x"), /not a valid/);
});
});
describe("request file selection", () => {
const files = [
{ path: "Qwen3-8B-Q4_K_M.gguf", size: 5 * GB },
{ path: "Qwen3-8B-Q8_0.gguf", size: 8.7 * GB },
{ path: "mmproj-F16.gguf", size: 0.6 * GB },
{ path: "BF16/Qwen3-8B-BF16-00001-of-00002.gguf", size: 8 * GB },
{ path: "BF16/Qwen3-8B-BF16-00002-of-00002.gguf", size: 8 * GB },
{ path: "README.md", size: 1000 },
];
it("summarizes quants (weights only, split parts together)", () => {
assert.deepEqual(
quantSummary(files).map((q) => [q.quant, q.files]),
[
["Q4_K_M", 1],
["Q8_0", 1],
["BF16", 2],
],
);
});
it("resolves a quant to its weights plus recommended companions", () => {
assert.deepEqual(resolveRequestPaths(files, { quant: "q4_k_m" }, ["vision"]), ["Qwen3-8B-Q4_K_M.gguf", "mmproj-F16.gguf"]);
assert.deepEqual(resolveRequestPaths(files, { quant: "Q4_K_M" }, []), ["Qwen3-8B-Q4_K_M.gguf"]);
assert.deepEqual(resolveRequestPaths(files, { quant: "BF16" }, []), ["BF16/Qwen3-8B-BF16-00001-of-00002.gguf", "BF16/Qwen3-8B-BF16-00002-of-00002.gguf"]);
});
it("explains a missing quant with the available ones", () => {
assert.throws(() => resolveRequestPaths(files, { quant: "Q2_K" }, []), /quant "Q2_K" not found in this repo\. Available: .*Q4_K_M/);
assert.throws(() => resolveRequestPaths([{ path: "model.safetensors", size: 1 }], { quant: "Q4_K_M" }, []), /no GGUF quants\. Use "include"/);
});
it("resolves include globs and rejects ones that match nothing", () => {
assert.deepEqual(resolveRequestPaths(files, { include: ["*Q8_0*", "README.md"] }, []), ["Qwen3-8B-Q8_0.gguf", "README.md"]);
assert.throws(() => resolveRequestPaths(files, { include: ["*.safetensors"] }, []), /no file in this repo matches/);
});
it("finds what a request adds to the selection", () => {
assert.deepEqual(newPaths(["a", "b", "c"], ["b"]), ["a", "c"]);
assert.deepEqual(newPaths(["a"], ["a", "b"]), []);
});
});
describe("GET /api/v1/models filters", () => {
it("reads repeated and comma-separated values, requested_by → requester", () => {
const { query, filters } = parseModelFilters(new URLSearchParams("q=qwen 8b&author=unsloth,bartowski&quant=Q4_K_M&quant=Q8_0&requested_by=hermes&status=pending_approval"));
assert.equal(query, "qwen 8b");
assert.deepEqual(filters, { ...EMPTY_FILTERS, author: ["unsloth", "bartowski"], quant: ["Q4_K_M", "Q8_0"], requester: ["hermes"], status: ["pending_approval"] });
});
it("filters by requester and pending approval like the library", () => {
const m: SearchableModel = {
repoId: "unsloth/Qwen3-8B-GGUF",
author: "unsloth",
families: ["Qwen"],
baseModels: [],
architecture: null,
quants: ["Q4_K_M"],
tags: [],
hubTags: [],
pipelineTag: null,
license: null,
status: "pending",
hubStatus: null,
requestedBy: "hermes",
pendingApproval: true,
};
assert.deepEqual(facetValues(m, "status"), ["pending", "pending_approval"]);
assert.ok(matchesFilters(m, { ...EMPTY_FILTERS, requester: ["Hermes"] }));
assert.ok(!matchesFilters({ ...m, requestedBy: null }, { ...EMPTY_FILTERS, requester: ["hermes"] }));
});
});
describe("proxy", () => {
// The OIDC gate must skip exactly /api/v1 (bearer tokens), nothing that merely starts like it.
const src = readFileSync(new URL("../proxy.ts", import.meta.url), "utf8");
const matcher = JSON.parse(`"${src.match(/matcher: \["([^"]+)"\]/)![1]}"`) as string;
const gated = (path: string) => new RegExp(`^${matcher}$`).test(path);
it("leaves /api/v1 to token auth and gates everything else", () => {
assert.ok(!gated("/api/v1"));
assert.ok(!gated("/api/v1/models"));
assert.ok(!gated("/api/v1/jobs/01ABC"));
assert.ok(gated("/api/v1x"));
assert.ok(gated("/api/models"));
assert.ok(gated("/api/api-tokens"));
assert.ok(gated("/settings/api-tokens"));
});
});
+32
View File
@@ -0,0 +1,32 @@
// API token format, hashing and scope checks. Pure (no DB), shared by the server code and tests.
import { createHash, randomBytes } from "node:crypto";
import { TOKEN_SCOPES, type TokenScope } from "@/lib/db/schema";
/** "kn_" + 32 random bytes as base64url (43 chars). */
export const TOKEN_PREFIX = "kn_";
const TOKEN_RE = /^kn_[A-Za-z0-9_-]{43}$/;
/** Characters of the token kept for display ("kn_AbCd…"). */
const DISPLAY_CHARS = 7;
export const TOKEN_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,39}$/;
export function generateToken(): { token: string; prefix: string; hash: string } {
const token = TOKEN_PREFIX + randomBytes(32).toString("base64url");
return { token, prefix: token.slice(0, DISPLAY_CHARS), hash: hashToken(token) };
}
/** SHA-256 is enough: the tokens are 256 random bits, not passwords that need a slow hash. */
export function hashToken(token: string): string {
return createHash("sha256").update(token).digest("hex");
}
/** The token from an `Authorization: Bearer …` header, or null if it's missing or malformed. */
export function bearerToken(header: string | null): string | null {
const m = header?.match(/^Bearer\s+(\S+)\s*$/i);
return m && TOKEN_RE.test(m[1]) ? m[1] : null;
}
export function isScope(v: unknown): v is TokenScope {
return typeof v === "string" && (TOKEN_SCOPES as readonly string[]).includes(v);
}
+98
View File
@@ -0,0 +1,98 @@
import "server-only";
import { and, desc, eq, isNotNull, isNull } from "drizzle-orm";
import { NextResponse } from "next/server";
import { bearerToken, generateToken, hashToken, isScope, TOKEN_NAME_RE } from "@/lib/api-token-core";
import { db } from "@/lib/db/client";
import { apiTokens, type TokenScope } from "@/lib/db/schema";
export class TokenError extends Error {
constructor(
public code: "invalid" | "exists" | "not_found",
message: string,
public status = 400,
) {
super(message);
}
}
export type ApiTokenRow = Omit<typeof apiTokens.$inferSelect, "hash">;
/** lastUsedAt is written at most this often per token, not on every request. */
const TOUCH_MS = 60_000;
export async function listTokens(): Promise<ApiTokenRow[]> {
return db()
.select({
id: apiTokens.id,
name: apiTokens.name,
prefix: apiTokens.prefix,
scopes: apiTokens.scopes,
lastUsedAt: apiTokens.lastUsedAt,
revokedAt: apiTokens.revokedAt,
createdAt: apiTokens.createdAt,
})
.from(apiTokens)
.orderBy(desc(apiTokens.createdAt));
}
/** Create a token; the plain token is returned only here and never stored. */
export async function createToken(name: string, scopes: string[]): Promise<{ id: string; token: string }> {
const n = name.trim().toLowerCase();
if (!TOKEN_NAME_RE.test(n)) throw new TokenError("invalid", "Name: 1–40 characters, lowercase letters, digits, . _ - (e.g. hermes).");
const s = [...new Set(scopes)];
if (s.length === 0 || !s.every(isScope)) throw new TokenError("invalid", "Pick at least one valid scope.");
if (await db().query.apiTokens.findFirst({ columns: { id: true }, where: eq(apiTokens.name, n) })) {
throw new TokenError("exists", `A token named "${n}" already exists. Delete it first or pick another name.`, 409);
}
const t = generateToken();
const [row] = await db().insert(apiTokens).values({ name: n, prefix: t.prefix, hash: t.hash, scopes: s as TokenScope[] }).returning({ id: apiTokens.id });
return { id: row.id, token: t.token };
}
export async function revokeToken(id: string): Promise<void> {
const res = await db().update(apiTokens).set({ revokedAt: new Date() }).where(and(eq(apiTokens.id, id), isNull(apiTokens.revokedAt))).returning({ id: apiTokens.id });
if (res.length === 0) throw new TokenError("not_found", "Token not found or already revoked.", 404);
}
/** Only revoked tokens can be deleted (frees the name; "requested by" labels keep it). */
export async function deleteToken(id: string): Promise<void> {
const res = await db().delete(apiTokens).where(and(eq(apiTokens.id, id), isNotNull(apiTokens.revokedAt))).returning({ id: apiTokens.id });
if (res.length === 0) throw new TokenError("not_found", "Revoke the token before deleting it.", 409);
}
export type TokenIdentity = { id: string; name: string; scopes: TokenScope[] };
/** The active token behind a request's bearer header, or null. */
export async function tokenFromRequest(req: Request): Promise<TokenIdentity | null> {
const token = bearerToken(req.headers.get("authorization"));
if (!token) return null;
const row = await db().query.apiTokens.findFirst({ where: and(eq(apiTokens.hash, hashToken(token)), isNull(apiTokens.revokedAt)) });
if (!row) return null;
if (!row.lastUsedAt || Date.now() - row.lastUsedAt.getTime() > TOUCH_MS) {
await db().update(apiTokens).set({ lastUsedAt: new Date() }).where(eq(apiTokens.id, row.id));
}
return { id: row.id, name: row.name, scopes: row.scopes };
}
function v1Error(status: number, code: string, message: string) {
return NextResponse.json({ error: { code, message } }, { status, headers: status === 401 ? { "WWW-Authenticate": 'Bearer realm="kaname"' } : undefined });
}
type Handler<Ctx> = (req: Request, ctx: Ctx & { token: TokenIdentity }) => Promise<Response> | Response;
/**
* Wraps a /api/v1 route: requires `Authorization: Bearer <token>` with `scope` (null: any valid
* token). Login sessions don't count here; the rest of the app is OIDC-only.
*/
export function withToken<Ctx = unknown>(scope: TokenScope | null, handler: Handler<Ctx>) {
return async (req: Request, ctx: Ctx) => {
const token = await tokenFromRequest(req);
if (!token) {
return v1Error(401, "unauthorized", "Missing or invalid API token. Send it as \"Authorization: Bearer kn_…\"; tokens are created in Kaname under Settings → API tokens.");
}
if (scope && !token.scopes.includes(scope)) {
return v1Error(403, "forbidden", `This token lacks the scope "${scope}" (it has: ${token.scopes.join(", ")}). Ask the user to grant it in Settings → API tokens.`);
}
return handler(req, { ...ctx, token });
};
}
+26
View File
@@ -0,0 +1,26 @@
// Query-string filters for GET /api/v1/models, with the library's search semantics
// (terms AND-ed in `q`; OR within a facet, AND across facets). Pure.
import { EMPTY_FILTERS, type Facet, type Filters } from "@/lib/search";
/** Query parameter per facet; each may repeat or hold a comma-separated list. */
const PARAM: Record<Facet, string> = {
author: "author",
family: "family",
quant: "quant",
tag: "tag",
status: "status",
requester: "requested_by",
};
export function parseModelFilters(params: URLSearchParams): { query: string; filters: Filters } {
const filters = { ...EMPTY_FILTERS };
for (const facet of Object.keys(PARAM) as Facet[]) {
filters[facet] = params
.getAll(PARAM[facet])
.flatMap((v) => v.split(","))
.map((v) => v.trim())
.filter(Boolean);
}
return { query: params.get("q")?.trim() ?? "", filters };
}
+306
View File
@@ -0,0 +1,306 @@
// /api/v1 end to end against a temporary SQLite database and a stubbed Hugging Face API:
// token auth, scopes, every guardrail rejection, idempotency, approve/reject.
// Runs with `--conditions=react-server` (see package.json) so "server-only" modules load.
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, it } from "node:test";
const dir = mkdtempSync(join(tmpdir(), "kaname-api-"));
process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
process.env.MODELS_DIR = join(dir, "models");
delete process.env.HF_TOKEN;
const GB = 1e9;
const SHA = { a: "a".repeat(40), b: "b".repeat(40), c: "c".repeat(40), d: "d".repeat(40) };
/** Fake Hub: repo → commit + files. */
const REPOS: Record<string, { sha: string; files: [string, number][] }> = {
"unsloth/Test-GGUF": {
sha: SHA.a,
files: [
["Test-Q4_K_M.gguf", 5 * GB],
["Test-Q8_0.gguf", 9 * GB],
["Test-F16.gguf", 70 * GB],
["README.md", 1000],
],
},
"unsloth/Other-GGUF": { sha: SHA.b, files: [["Other-Q4_K_M.gguf", 2 * GB]] },
"ggml-org/Third-GGUF": { sha: SHA.c, files: [["Third-Q4_K_M.gguf", 3 * GB]] },
"TheBloke/Old-GGUF": { sha: SHA.d, files: [["Old-Q4_K_M.gguf", 1 * GB]] },
};
const realFetch = globalThis.fetch;
globalThis.fetch = (async (input: string | URL | Request) => {
const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
const m = url.pathname.match(/^\/api\/models\/([^/]+\/[^/]+)\/(revision|tree)\/([^/]+)/);
// Like the Hub: repo ids are case-insensitive, the response has the canonical one.
const id = m && Object.keys(REPOS).find((k) => k.toLowerCase() === decodeURIComponent(m[1]).toLowerCase());
const repo = id && REPOS[id];
if (!m || !id || !repo) return new Response("not found", { status: 404 });
const rev = decodeURIComponent(m[3]);
if (rev !== "main" && rev !== repo.sha) return new Response("", { status: 404, headers: { "x-error-code": "RevisionNotFound" } });
if (m[2] === "revision") return Response.json({ id, sha: repo.sha, gated: false, private: false, tags: [] });
return Response.json(repo.files.map(([path, size]) => ({ type: "file", path, size, oid: "0".repeat(40), lfs: { oid: "e".repeat(64), size } })));
}) as typeof fetch;
type Mods = {
db: typeof import("./db/client");
schema: typeof import("./db/schema");
tokens: typeof import("./api-tokens");
settings: typeof import("./settings");
agent: typeof import("./agent-downloads");
v1: typeof import("../app/api/v1/route");
downloads: typeof import("../app/api/v1/downloads/route");
job: typeof import("../app/api/v1/jobs/[id]/route");
models: typeof import("../app/api/v1/models/route");
disk: typeof import("../app/api/v1/disk/route");
};
let M: Mods;
let full: string; // models:read + downloads:create
let readOnly: string;
const call = async (handler: (req: Request, ctx: never) => Promise<Response>, path: string, opts: { token?: string; body?: unknown; params?: Record<string, string> } = {}) => {
const req = new Request(`http://kaname.test${path}`, {
method: opts.body ? "POST" : "GET",
headers: { ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}), "Content-Type": "application/json" },
body: opts.body ? JSON.stringify(opts.body) : undefined,
});
const res = await handler(req, { params: Promise.resolve(opts.params ?? {}) } as never);
return { status: res.status, body: (await res.json()) as Record<string, any> }; // eslint-disable-line @typescript-eslint/no-explicit-any
};
const request = (body: unknown, token = full) => call(M.downloads.POST, "/api/v1/downloads", { token, body });
async function setFree(bytes: number) {
const { db } = M.db;
const now = new Date();
await db()
.insert(M.schema.workerState)
.values({ id: "worker", startedAt: now, heartbeatAt: now, modelsDirFreeBytes: bytes, modelsDirTotalBytes: 2000 * GB })
.onConflictDoUpdate({ target: M.schema.workerState.id, set: { heartbeatAt: now, modelsDirFreeBytes: bytes } });
}
before(async () => {
const { runMigrations } = await import("./db/migrate");
await runMigrations();
M = {
db: await import("./db/client"),
schema: await import("./db/schema"),
tokens: await import("./api-tokens"),
settings: await import("./settings"),
agent: await import("./agent-downloads"),
v1: await import("../app/api/v1/route"),
downloads: await import("../app/api/v1/downloads/route"),
job: await import("../app/api/v1/jobs/[id]/route"),
models: await import("../app/api/v1/models/route"),
disk: await import("../app/api/v1/disk/route"),
};
full = (await M.tokens.createToken("hermes", ["models:read", "downloads:create"])).token;
readOnly = (await M.tokens.createToken("reader", ["models:read"])).token;
await setFree(500 * GB);
});
after(() => {
globalThis.fetch = realFetch;
// Close the database first; Windows can't delete an open file.
(globalThis as { __kanameDb?: { client?: { close(): void } } }).__kanameDb?.client?.close();
try {
rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
} catch {
// Windows may still hold the WAL file for a moment; a leftover temp dir is harmless.
}
});
describe("token auth", () => {
it("rejects missing, malformed and unknown tokens with 401", async () => {
assert.equal((await call(M.v1.GET, "/api/v1")).status, 401);
assert.equal((await call(M.v1.GET, "/api/v1", { token: "kn_nope" })).status, 401);
const unknown = (await import("./api-token-core")).generateToken().token;
const r = await call(M.v1.GET, "/api/v1", { token: unknown });
assert.equal(r.status, 401);
assert.match(r.body.error.message, /Settings → API tokens/);
});
it("answers with the token's name, scopes and the guardrails", async () => {
const r = await call(M.v1.GET, "/api/v1", { token: readOnly });
assert.equal(r.status, 200);
assert.deepEqual(r.body.token, { name: "reader", scopes: ["models:read"] });
assert.equal(r.body.guardrails.approvalMode, "approve");
assert.equal(r.body.guardrails.maxRequestSize, "60.0 GB");
});
it("enforces scopes with 403", async () => {
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q4_K_M" }, readOnly);
assert.equal(r.status, 403);
assert.match(r.body.error.message, /lacks the scope "downloads:create"/);
assert.equal((await call(M.disk.GET, "/api/v1/disk", { token: readOnly })).status, 200);
});
it("records last use and stops accepting a revoked token", async () => {
const t = await M.tokens.createToken("temp", ["models:read"]);
assert.equal((await call(M.v1.GET, "/api/v1", { token: t.token })).status, 200);
const row = (await M.tokens.listTokens()).find((x) => x.name === "temp")!;
assert.ok(row.lastUsedAt);
await M.tokens.revokeToken(t.id);
assert.equal((await call(M.v1.GET, "/api/v1", { token: t.token })).status, 401);
await M.tokens.deleteToken(t.id);
});
it("never stores the token itself", async () => {
const rows = await M.db.db().select().from(M.schema.apiTokens);
assert.ok(rows.every((r) => r.hash !== full && r.hash.length === 64 && !r.hash.startsWith("kn_")));
});
});
describe("download requests", () => {
let first: { modelId: string; jobId: string };
it("validates the body", async () => {
const r = await request({ repoId: "unsloth/Test-GGUF", sha: "main", quant: "Q4_K_M" });
assert.equal(r.status, 400);
assert.match(r.body.error.message, /40-character commit SHA/);
assert.equal((await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a })).status, 400);
assert.equal((await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q2_K" })).status, 400);
});
it("creates a model and a job that waits for approval, marked with the token name", async () => {
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q4_K_M", tags: ["agent"] });
assert.equal(r.status, 201);
assert.equal(r.body.state, "pending_approval");
assert.equal(r.body.requestedSize, "5.0 GB");
assert.deepEqual(r.body.files, ["Test-Q4_K_M.gguf"]);
assert.match(r.body.message, /Do not retry/);
first = { modelId: r.body.modelId, jobId: r.body.jobId };
const job = await call(M.job.GET, `/api/v1/jobs/${first.jobId}`, { token: readOnly, params: { id: first.jobId } });
assert.equal(job.body.state, "pending_approval");
assert.equal(job.body.requestedBy, "hermes");
assert.equal(job.body.log, undefined);
assert.deepEqual(job.body.files.map((f: { path: string }) => f.path), ["Test-Q4_K_M.gguf"]);
const model = await M.db.db().query.models.findFirst({ where: (m, { eq }) => eq(m.id, first.modelId) });
assert.equal(model?.requestedBy, "hermes");
assert.equal(model?.status, "pending"); // not "downloading" until approved
});
it("is idempotent: the same repo + commit + files returns the existing job", async () => {
const r = await request({ repoId: "unsloth/test-gguf", sha: SHA.a, quant: "q4_k_m" });
assert.equal(r.status, 200);
assert.equal(r.body.created, false);
assert.equal(r.body.jobId, first.jobId);
const n = await M.db.db().select().from(M.schema.jobs);
assert.equal(n.length, 1);
});
it("refuses other files while the model has an open job", async () => {
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q8_0" });
assert.equal(r.status, 409);
assert.match(r.body.error.message, /still pending approval/);
});
it("refuses a different commit of a model in the library", async () => {
REPOS["unsloth/Test-GGUF"].sha = SHA.d;
try {
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.d, quant: "Q4_K_M" });
assert.equal(r.status, 409);
assert.match(r.body.error.message, /pinned to commit a{40}.*Updating a model is done by the user/);
} finally {
REPOS["unsloth/Test-GGUF"].sha = SHA.a;
}
});
it("rejects over the max agent jobs at once", async () => {
const second = await request({ repoId: "unsloth/Other-GGUF", sha: SHA.b, quant: "Q4_K_M" });
assert.equal(second.status, 201);
const third = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
assert.equal(third.status, 429);
assert.equal(third.body.error.code, "too_many_jobs");
assert.match(third.body.error.message, /2 pending or running, the limit is 2/);
// Reject the second request again; the model it added leaves the library.
assert.deepEqual(await M.agent.rejectJob(second.body.jobId), { removedModel: true });
assert.equal(await M.db.db().query.models.findFirst({ where: (m, { eq }) => eq(m.id, second.body.modelId) }), undefined);
});
it("rejects requests over the max size", async () => {
await M.settings.saveGuardrails({ maxOpenJobs: 10 });
const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
assert.equal(r.status, 201);
await M.agent.rejectJob(r.body.jobId);
await M.settings.saveGuardrails({ maxRequestBytes: 2.5 * GB });
const big = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
assert.equal(big.status, 422);
assert.equal(big.body.error.message, "exceeds max size per request 2.5 GB: requested 3.0 GB. Pick a smaller quant or fewer files.");
await M.settings.saveGuardrails({ maxRequestBytes: 60 * GB });
});
it("rejects when the minimum free space would not remain (counting reserved bytes)", async () => {
await setFree(107 * GB); // 5 GB reserved by the pending first request
const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
assert.equal(r.status, 507);
assert.equal(r.body.error.code, "disk_space");
assert.match(r.body.error.message, /107\.0 GB free \(5\.0 GB of it reserved by other downloads\), and at least 100\.0 GB must stay free/);
const disk = await call(M.disk.GET, "/api/v1/disk", { token: readOnly });
assert.equal(disk.body.reservedBytes, 5 * GB);
assert.equal(disk.body.availableForRequestsBytes, 2 * GB);
await setFree(500 * GB);
});
it("rejects when the worker is offline (free space unknown)", async () => {
const { db } = M.db;
await db().update(M.schema.workerState).set({ heartbeatAt: new Date(0) });
const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
assert.equal(r.status, 503);
assert.equal(r.body.error.code, "disk_unknown");
await setFree(500 * GB);
});
it("rejects authors outside the allowlist before asking the Hub", async () => {
await M.settings.saveGuardrails({ allowedAuthors: ["unsloth", "ggml-org"] });
const r = await request({ repoId: "TheBloke/Old-GGUF", sha: SHA.d, quant: "Q4_K_M" });
assert.equal(r.status, 403);
assert.equal(r.body.error.code, "author_not_allowed");
assert.match(r.body.error.message, /author "TheBloke" is not on the allowlist \(unsloth, ggml-org\)/);
await M.settings.saveGuardrails({ allowedAuthors: [] });
});
it("approve queues the job; the model then shows as downloading", async () => {
await M.agent.approveJob(first.jobId);
const job = await call(M.job.GET, `/api/v1/jobs/${first.jobId}?log=5`, { token: readOnly, params: { id: first.jobId } });
assert.equal(job.body.state, "queued");
assert.ok(Array.isArray(job.body.log));
await assert.rejects(M.agent.approveJob(first.jobId), /doesn't wait for approval/);
});
it("extra files of a finished model are added; rejecting restores the selection", async () => {
const { db } = M.db;
await db().update(M.schema.jobs).set({ state: "completed", finishedAt: new Date() }).where((await import("drizzle-orm")).eq(M.schema.jobs.id, first.jobId));
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q8_0" });
assert.equal(r.status, 201);
assert.equal(r.body.requestedSize, "9.0 GB");
const selected = async () =>
(await db().query.modelFiles.findMany({ where: (f, { and, eq }) => and(eq(f.modelId, first.modelId), eq(f.selected, true)) })).map((f) => f.path).sort();
assert.deepEqual(await selected(), ["Test-Q4_K_M.gguf", "Test-Q8_0.gguf"]);
assert.deepEqual(await M.agent.rejectJob(r.body.jobId), { removedModel: false });
assert.deepEqual(await selected(), ["Test-Q4_K_M.gguf"]);
});
it("auto approval queues right away", async () => {
await M.settings.saveGuardrails({ approvalMode: "auto" });
const r = await request({ repoId: "unsloth/Other-GGUF", sha: SHA.b, include: ["*.gguf"] });
assert.equal(r.status, 201);
assert.equal(r.body.state, "queued");
await M.settings.saveGuardrails({ approvalMode: "approve" });
});
it("lists models with the library filters, including requested_by", async () => {
const all = await call(M.models.GET, "/api/v1/models", { token: readOnly });
assert.equal(all.body.count, 2);
const mine = await call(M.models.GET, "/api/v1/models?requested_by=hermes&quant=Q4_K_M&author=unsloth", { token: readOnly });
assert.deepEqual(mine.body.models.map((m: { repoId: string }) => m.repoId).sort(), ["unsloth/Other-GGUF", "unsloth/Test-GGUF"]);
assert.equal(mine.body.models[0].requestedBy, "hermes");
const none = await call(M.models.GET, "/api/v1/models?requested_by=someone-else", { token: readOnly });
assert.equal(none.body.count, 0);
});
});
+49
View File
@@ -0,0 +1,49 @@
import "server-only";
import { NextResponse } from "next/server";
import { z } from "zod";
import { GuardrailError } from "@/lib/agent-guardrails";
import { SelectionError } from "@/lib/agent-selection";
import { HubError } from "@/lib/hub/client";
import { JobError } from "@/lib/jobs";
import { ModelError } from "@/lib/models";
import { TagError } from "@/lib/tags";
// Shared by the /api/v1 routes: compact JSON for an agent to read, errors as
// { error: { code, message } } with a message that says what to do next.
export function v1Json(data: unknown, status = 200) {
return NextResponse.json(data, { status, headers: { "Cache-Control": "no-store" } });
}
export function v1Error(status: number, code: string, message: string) {
return v1Json({ error: { code, message } }, status);
}
const HUB_STATUS: Partial<Record<HubError["code"], number>> = {
invalid_repo_id: 400,
repo_not_found: 404,
revision_not_found: 404,
gated_no_token: 403,
gated_no_access: 403,
rate_limited: 429,
network: 502,
};
/** Known errors → JSON; anything else is logged and becomes a generic 500 (no stack traces). */
export function v1Catch(err: unknown) {
if (err instanceof GuardrailError) return v1Error(err.status, err.code, err.message);
if (err instanceof SelectionError) return v1Error(err.status, err.code, err.message);
if (err instanceof ModelError || err instanceof JobError || err instanceof TagError) return v1Error(err.status, err.code, err.message);
if (err instanceof HubError) return v1Error(HUB_STATUS[err.code] ?? 502, err.code, err.message);
if (err instanceof z.ZodError) {
return v1Error(400, "invalid_request", err.issues.map((i) => `${i.path.join(".") || "body"}: ${i.message}`).join("; "));
}
if (err instanceof SyntaxError) return v1Error(400, "invalid_json", "The request body is not valid JSON.");
console.error("[api/v1]", err);
return v1Error(500, "internal", "Internal error in Kaname. Tell the user; retrying won't help.");
}
/** "74.2 GB" next to byte counts, so a reader doesn't have to convert. */
export function size(bytes: number | null | undefined): string | null {
return bytes == null ? null : `${(bytes / 1e9).toFixed(1)} GB`;
}
+34
View File
@@ -73,6 +73,8 @@ export type JobResult = {
removePaths?: string[];
/** Delete jobs: files that were kept because they don't belong to the repo. */
kept?: string[];
/** API "add files" requests: the selection rule before, restored if the request is rejected. */
previousRule?: { include: string[]; exclude: string[] };
};
export const models = sqliteTable(
@@ -124,6 +126,9 @@ export const models = sqliteTable(
/** Hub tags, minus noise like arxiv:/region:/deploy:. */
hubTags: text("hub_tags", { mode: "json" }).$type<string[]>(),
metadataFetchedAt: ts("metadata_fetched_at"),
/** Added through the API: the token that asked for it, and its name at the time. */
requestedByTokenId: text("requested_by_token_id"),
requestedBy: text("requested_by"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
@@ -224,6 +229,7 @@ export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update"] as
export type JobPurpose = (typeof JOB_PURPOSES)[number];
export const JOB_STATES = [
"pending_approval", // requested through the API, waits for a human to approve it
"queued",
"downloading",
"verifying",
@@ -269,6 +275,9 @@ export const jobs = sqliteTable(
result: text("result", { mode: "json" }).$type<JobResult>(),
/** Set by the web app; the worker picks it up and stops the job. */
cancelRequestedAt: ts("cancel_requested_at"),
/** Requested through the API: the token, and its name at the time. */
requestedByTokenId: text("requested_by_token_id"),
requestedBy: text("requested_by"),
startedAt: ts("started_at"),
finishedAt: ts("finished_at"),
createdAt: createdAt(),
@@ -558,6 +567,31 @@ export const apiKeys = sqliteTable("api_keys", {
createdAt: createdAt(),
});
// ---------------------------------------------------------------------------
// API tokens: machine clients (e.g. an AI agent) calling /api/v1 with a bearer token
// ---------------------------------------------------------------------------
/** What a token may do. Nothing can delete, change settings or manage runtimes/tokens. */
export const TOKEN_SCOPES = ["models:read", "downloads:create"] as const;
export type TokenScope = (typeof TOKEN_SCOPES)[number];
export const apiTokens = sqliteTable(
"api_tokens",
{
id: id(),
name: text("name").notNull(),
/** First characters of the token, shown in the UI to tell tokens apart. */
prefix: text("prefix").notNull(),
/** SHA-256 of the token (hex); the token itself is never stored. */
hash: text("hash").notNull().unique(),
scopes: text("scopes", { mode: "json" }).$type<TokenScope[]>().notNull(),
lastUsedAt: ts("last_used_at"),
revokedAt: ts("revoked_at"),
createdAt: createdAt(),
},
(t) => [uniqueIndex("api_tokens_name_uq").on(t.name)],
);
// ---------------------------------------------------------------------------
// Benchmarks (BetterBench runs against a running deployment)
// ---------------------------------------------------------------------------
+24 -7
View File
@@ -24,7 +24,8 @@ export class JobError extends Error {
}
}
const OPEN_STATES = ["queued", ...ACTIVE_JOB_STATES] as const;
/** Jobs that block another job for the same model; pending approval counts (it will run). */
export const OPEN_STATES = ["pending_approval", "queued", ...ACTIVE_JOB_STATES] as const;
const INSERT_CHUNK = 500;
/** True if the model has a queued or running job (only one job per model at a time). */
@@ -36,15 +37,19 @@ export async function hasOpenJob(modelId: string): Promise<boolean> {
return !!open;
}
/** Who asked for a job through the API (token id + its name at the time). */
export type RequestedBy = { tokenId: string; name: string };
/**
* Queue a download of all selected files of a model at its pinned SHA. hf skips files that are
* already complete, so this also serves as resume and repair. `removePaths`: files of an older
* revision to delete once the download succeeded (updates).
* revision to delete once the download succeeded (updates). `pendingApproval`: the job waits in
* "pending_approval" (the worker only picks up "queued") until someone approves it.
*/
export async function queueDownload(
modelId: string,
purpose: JobPurpose = "initial",
options: { removePaths?: string[] } = {},
options: { removePaths?: string[]; pendingApproval?: boolean; requestedBy?: RequestedBy; previousRule?: JobResult["previousRule"] } = {},
): Promise<{ jobId: string }> {
const d = db();
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
@@ -62,18 +67,25 @@ export async function queueDownload(
const jobId = ulid();
const rows = files.map((f) => ({ jobId, modelFileId: f.id, path: f.path, expectedBytes: f.size }));
const result: JobResult = {};
if (options.removePaths?.length) result.removePaths = options.removePaths;
if (options.previousRule) result.previousRule = options.previousRule;
await d.batch([
d.insert(jobs).values({
id: jobId,
modelId,
kind: "download",
purpose,
state: options.pendingApproval ? "pending_approval" : "queued",
targetSha: model.pinnedSha,
totalBytes: files.reduce((s, f) => s + f.size, 0),
result: options.removePaths?.length ? { removePaths: options.removePaths } : null,
result: Object.keys(result).length ? result : null,
requestedByTokenId: options.requestedBy?.tokenId ?? null,
requestedBy: options.requestedBy?.name ?? null,
}),
...chunk(rows, INSERT_CHUNK).map((c) => d.insert(jobFiles).values(c)),
d.update(models).set({ status: "downloading" }).where(eq(models.id, modelId)),
// A job waiting for approval doesn't download yet; the model keeps its status.
...(options.pendingApproval ? [] : [d.update(models).set({ status: "downloading" }).where(eq(models.id, modelId))]),
]);
return { jobId };
}
@@ -110,10 +122,12 @@ export async function queueVerify(modelId: string, deep: boolean): Promise<{ job
/** Ask the worker to stop a job. Queued jobs are cancelled by the worker on its next tick. */
export async function requestCancel(jobId: string): Promise<void> {
const pending = await db().query.jobs.findFirst({ columns: { id: true }, where: and(eq(jobs.id, jobId), eq(jobs.state, "pending_approval")) });
if (pending) throw new JobError("not_cancellable", "This download waits for approval. Approve or reject it instead.", 409);
const res = await db()
.update(jobs)
.set({ cancelRequestedAt: new Date() })
.where(and(eq(jobs.id, jobId), inArray(jobs.state, [...OPEN_STATES]), isNull(jobs.cancelRequestedAt)))
.where(and(eq(jobs.id, jobId), inArray(jobs.state, ["queued", ...ACTIVE_JOB_STATES]), isNull(jobs.cancelRequestedAt)))
.returning({ id: jobs.id });
if (res.length === 0) {
const job = await db().query.jobs.findFirst({ columns: { id: true }, where: eq(jobs.id, jobId) });
@@ -143,6 +157,8 @@ export type JobSnapshot = {
errorMessage: string | null;
result: JobResult | null;
cancelRequested: boolean;
/** Token name if the job was requested through the API. */
requestedBy: string | null;
createdAt: number;
startedAt: number | null;
finishedAt: number | null;
@@ -175,12 +191,13 @@ const jobColumns = {
errorMessage: jobs.errorMessage,
result: jobs.result,
cancelRequestedAt: jobs.cancelRequestedAt,
requestedBy: jobs.requestedBy,
createdAt: jobs.createdAt,
startedAt: jobs.startedAt,
finishedAt: jobs.finishedAt,
};
type JobRow = Omit<typeof jobs.$inferSelect, "targetSha" | "updatedAt"> & { repoId: string };
type JobRow = Omit<typeof jobs.$inferSelect, "targetSha" | "updatedAt" | "requestedByTokenId"> & { repoId: string };
function toSnapshot(r: JobRow): JobSnapshot {
const { cancelRequestedAt, createdAt, startedAt, finishedAt, ...rest } = r;
+9 -1
View File
@@ -2,7 +2,7 @@ import "server-only";
import { and, asc, desc, eq, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { deploymentsByModel, listDeployableModels } from "@/lib/deployments";
import { modelFiles, models, modelTags, tags } from "@/lib/db/schema";
import { jobs, modelFiles, models, modelTags, tags } from "@/lib/db/schema";
import { modelFamilies } from "@/lib/hub/metadata";
import { fileRole } from "@/lib/file-roles";
import { quantGroup } from "@/lib/selection";
@@ -30,8 +30,11 @@ export async function listLibrary() {
pipelineTag: models.pipelineTag,
license: models.license,
hubTags: models.hubTags,
requestedBy: models.requestedBy,
fileCount: sql<number>`count(${modelFiles.id})`,
totalBytes: sql<number>`coalesce(sum(${modelFiles.size}), 0)`,
/** Selected files that are on disk (present or verified). */
presentBytes: sql<number>`coalesce(sum(case when ${modelFiles.state} in ('present', 'verified') then ${modelFiles.size} else 0 end), 0)`,
})
.from(models)
.leftJoin(modelFiles, and(eq(modelFiles.modelId, models.id), eq(modelFiles.selected, true)))
@@ -53,6 +56,10 @@ export async function listLibrary() {
const tagsByModel = new Map<string, Tag[]>();
for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name, color: t.color }]);
const pending = new Set(
(await d.select({ modelId: jobs.modelId }).from(jobs).where(eq(jobs.state, "pending_approval"))).map((j) => j.modelId),
);
const [byModel, deployable] = await Promise.all([deploymentsByModel(), listDeployableModels()]);
const deployableIds = new Set(deployable.map((m) => m.id));
@@ -66,6 +73,7 @@ export async function listLibrary() {
quants: [...(quants.get(r.id) ?? [])].sort(),
tags: tagsByModel.get(r.id) ?? [],
deployable: deployableIds.has(r.id),
pendingApproval: pending.has(r.id),
deployments: byModel.get(r.id) ?? [],
}));
}
+31 -5
View File
@@ -7,7 +7,7 @@ import { hubMissingMessage } from "@/lib/hub/availability";
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
import { metadataColumns } from "@/lib/hub/refresh";
import { deploymentsUsing } from "@/lib/deployments";
import { hasOpenJob, queueDownload } from "@/lib/jobs";
import { hasOpenJob, queueDownload, type RequestedBy } from "@/lib/jobs";
import { getLocalFolder, requestFolderScan } from "@/lib/local-folders";
import { purgeModelRows } from "@/lib/model-purge";
import { contentId } from "@/lib/update-diff";
@@ -36,6 +36,8 @@ export async function addModel(input: {
rule: SelectionRule;
/** Import: use this existing folder in MODELS_DIR (must be one the worker's scan found). */
localPath?: string;
/** Added through the API by this token. */
requestedBy?: RequestedBy;
}): Promise<{ id: string }> {
const info = await getRepoInfo(input.repoId, input.sha);
const repoId = info.repoId;
@@ -82,6 +84,8 @@ export async function addModel(input: {
localPath,
includePatterns: input.rule.include,
excludePatterns: input.rule.exclude,
requestedByTokenId: input.requestedBy?.tokenId ?? null,
requestedBy: input.requestedBy?.name ?? null,
...metadataColumns(info.metadata, await getAuthorAvatar(repoId.split("/")[0])),
}),
d.insert(modelRevisions).values({ modelId, sha: info.sha }),
@@ -202,7 +206,11 @@ function chunk<T>(items: T[], size: number): T[][] {
* rule as exact includes; exclude patterns that would block one of them are dropped, then the
* rule is re-applied to the whole file list so `selected` always matches the stored rule.
*/
export async function addFilesToModel(modelId: string, paths: string[]): Promise<{ jobId: string; added: number }> {
export async function addFilesToModel(
modelId: string,
paths: string[],
options: { pendingApproval?: boolean; requestedBy?: RequestedBy } = {},
): Promise<{ jobId: string; added: number }> {
const d = db();
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
if (!model) throw new ModelError("not_found", "Model not found.", 404);
@@ -211,9 +219,9 @@ export async function addFilesToModel(modelId: string, paths: string[]): Promise
const open = await d.query.jobs.findFirst({
columns: { id: true },
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, ["queued", "downloading", "verifying"])),
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, ["pending_approval", "queued", "downloading", "verifying"])),
});
if (open) throw new ModelError("busy", "A download for this model is still queued or running. Add files when it has finished.", 409);
if (open) throw new ModelError("busy", "A download for this model is still pending, queued or running. Add files when it has finished.", 409);
const files = await d.select().from(modelFiles).where(eq(modelFiles.modelId, modelId));
const known = new Map(files.map((f) => [f.path, f]));
@@ -233,6 +241,24 @@ export async function addFilesToModel(modelId: string, paths: string[]): Promise
d.update(modelFiles).set({ selected: !f.selected, state: "pending" }).where(eq(modelFiles.id, f.id)),
),
]);
const { jobId } = await queueDownload(modelId, "add");
const { jobId } = await queueDownload(modelId, "add", {
...options,
// API requests can be rejected; the rule before goes with the job so it can be restored.
previousRule: options.requestedBy ? { include: model.includePatterns, exclude: model.excludePatterns } : undefined,
});
return { jobId, added: changed.filter((f) => !f.selected).length };
}
/** Put a model's selection rule back (a rejected API "add files" request) and re-apply it. */
export async function restoreSelection(modelId: string, rule: SelectionRule): Promise<void> {
const d = db();
const files = await d
.select({ id: modelFiles.id, path: modelFiles.path, selected: modelFiles.selected })
.from(modelFiles)
.where(eq(modelFiles.modelId, modelId));
const changed = files.filter((f) => f.selected !== isSelected(f.path, rule));
await d.batch([
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude, updateDiff: null }).where(eq(models.id, modelId)),
...changed.map((f) => d.update(modelFiles).set({ selected: !f.selected }).where(eq(modelFiles.id, f.id))),
]);
}
+2
View File
@@ -56,6 +56,8 @@ const model = (over: Partial<SearchableModel>): SearchableModel => ({
license: "apache-2.0",
status: "ready",
hubStatus: null,
requestedBy: null,
pendingApproval: false,
...over,
});
+13 -3
View File
@@ -14,13 +14,20 @@ export type SearchableModel = {
status: string;
/** Extra status value when the repo or commit is gone from the Hub, e.g. "deleted on Hub". */
hubStatus: string | null;
/** API token name if the model was requested through the API. */
requestedBy: string | null;
/** A download of it waits for approval. */
pendingApproval: boolean;
};
export const FACETS = ["author", "family", "quant", "tag", "status"] as const;
/** Status facet value for models with a download waiting for approval. */
export const PENDING_APPROVAL = "pending_approval";
export const FACETS = ["author", "family", "quant", "tag", "status", "requester"] as const;
export type Facet = (typeof FACETS)[number];
export type Filters = Record<Facet, string[]>;
export const EMPTY_FILTERS: Filters = { author: [], family: [], quant: [], tag: [], status: [] };
export const EMPTY_FILTERS: Filters = { author: [], family: [], quant: [], tag: [], status: [], requester: [] };
export function facetValues(m: SearchableModel, facet: Facet): string[] {
switch (facet) {
@@ -33,7 +40,9 @@ export function facetValues(m: SearchableModel, facet: Facet): string[] {
case "tag":
return m.tags;
case "status":
return m.hubStatus ? [m.status, m.hubStatus] : [m.status];
return [m.status, m.hubStatus, m.pendingApproval ? PENDING_APPROVAL : null].filter((v): v is string => !!v);
case "requester":
return m.requestedBy ? [m.requestedBy] : [];
}
}
@@ -51,6 +60,7 @@ function haystack(m: SearchableModel): string {
m.license,
m.status,
m.hubStatus,
m.requestedBy,
]
.filter(Boolean)
.join(" ")
+20
View File
@@ -2,6 +2,7 @@ import "server-only";
import { eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { settings } from "@/lib/db/schema";
import { APPROVAL_MODES, type Guardrails, parseGuardrails } from "@/lib/agent-guardrails";
import { isLabelColor } from "@/lib/colors";
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles";
import { MIN_SPEED_LIMIT, parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit";
@@ -99,3 +100,22 @@ export async function saveDownloadSpeedLimit(bytesPerSecond: number | null): Pro
else await write(SPEED_LIMIT_KEY, Math.round(bytesPerSecond));
return getDownloadSpeedLimit();
}
const GUARDRAILS_KEY = "agent.guardrails";
/** Limits for downloads requested through the API (Settings → API tokens). */
export async function getGuardrails(): Promise<Guardrails> {
return parseGuardrails(await read<unknown>(GUARDRAILS_KEY));
}
export async function saveGuardrails(input: Partial<Guardrails>): Promise<Guardrails> {
const next = { ...(await getGuardrails()), ...input };
if (!APPROVAL_MODES.includes(next.approvalMode)) throw new SettingsError(`Approval mode must be one of: ${APPROVAL_MODES.join(", ")}.`);
if (!(next.maxRequestBytes >= 1_000_000)) throw new SettingsError("Max size per request must be at least 0.001 GB.");
if (!(next.minFreeBytes >= 0)) throw new SettingsError("Minimum free space can't be negative.");
if (!Number.isInteger(next.maxOpenJobs) || next.maxOpenJobs < 1 || next.maxOpenJobs > 50) throw new SettingsError("Max agent jobs at once must be 1–50.");
const parsed = parseGuardrails(next);
if (parsed.allowedAuthors.length !== next.allowedAuthors.length) throw new SettingsError("The author allowlist contains an invalid name.");
await write(GUARDRAILS_KEY, parsed);
return parsed;
}
+8
View File
@@ -0,0 +1,8 @@
// What each API token scope allows, for the settings UI. Pure, safe for the browser.
import type { TokenScope } from "@/lib/db/schema";
export const SCOPE_LABEL: Record<TokenScope, string> = {
"models:read": "Look up Hub repos, list models, read jobs and disk space",
"downloads:create": "Request downloads (within the guardrails)",
};