// Guardrails for downloads requested through the API (an autonomous agent, not a person in the // UI). Pure: settings parsing and the checks themselves; the request flow is in agent-downloads.ts. export const APPROVAL_MODES = ["approve", "auto"] as const; export type ApprovalMode = (typeof APPROVAL_MODES)[number]; export type Guardrails = { /** approve: requests wait as "pending approval" until someone confirms them in the UI. */ approvalMode: ApprovalMode; /** Largest download one request may add. */ maxRequestBytes: number; /** Free space that must remain on the models folder after the download. */ minFreeBytes: number; /** API-requested jobs that may be pending approval, queued or running at once (all tokens). */ maxOpenJobs: number; /** Hub authors (orgs/users) the API may download from; empty = any. Case-insensitive. */ allowedAuthors: string[]; }; const GB = 1_000_000_000; export const DEFAULT_GUARDRAILS: Guardrails = { approvalMode: "approve", maxRequestBytes: 60 * GB, minFreeBytes: 100 * GB, maxOpenJobs: 2, allowedAuthors: [], }; export class GuardrailError extends Error { constructor( public code: "too_large" | "disk_space" | "disk_unknown" | "too_many_jobs" | "author_not_allowed", message: string, public status = 422, ) { super(message); } } const AUTHOR_RE = /^[A-Za-z0-9][\w.-]{0,95}$/; /** Stored value merged over the defaults; anything invalid falls back to the default. */ export function parseGuardrails(v: unknown): Guardrails { const o = (v && typeof v === "object" ? v : {}) as Record; const num = (x: unknown, min: number, def: number) => (typeof x === "number" && Number.isFinite(x) && x >= min ? Math.round(x) : def); return { approvalMode: APPROVAL_MODES.includes(o.approvalMode as ApprovalMode) ? (o.approvalMode as ApprovalMode) : DEFAULT_GUARDRAILS.approvalMode, maxRequestBytes: num(o.maxRequestBytes, 1, DEFAULT_GUARDRAILS.maxRequestBytes), minFreeBytes: num(o.minFreeBytes, 0, DEFAULT_GUARDRAILS.minFreeBytes), maxOpenJobs: num(o.maxOpenJobs, 1, DEFAULT_GUARDRAILS.maxOpenJobs), allowedAuthors: Array.isArray(o.allowedAuthors) ? o.allowedAuthors.filter((a): a is string => typeof a === "string" && AUTHOR_RE.test(a)) : [], }; } /** "unsloth, ggml-org Qwen" → ["unsloth", "ggml-org", "Qwen"]; throws on an invalid name. */ export function parseAuthorList(text: string): string[] { const out: string[] = []; for (const a of text.split(/[\s,]+/).filter(Boolean)) { if (!AUTHOR_RE.test(a)) throw new Error(`"${a}" is not a valid Hugging Face user or organization name.`); if (!out.some((x) => x.toLowerCase() === a.toLowerCase())) out.push(a); } return out; } /** Plain GB (10^9), as the Hub and the settings use: "74.2 GB". */ export function gb(bytes: number): string { return `${(bytes / GB).toFixed(1)} GB`; } export type GuardrailInput = { repoId: string; /** Bytes this request would download. */ requestBytes: number; /** Free bytes on the models folder (worker heartbeat), or null if unknown. */ freeBytes: number | null; /** Bytes other open jobs still have to download. */ reservedBytes: number; /** API-requested jobs that are pending approval, queued or running right now. */ openAgentJobs: number; }; /** The author allowlist alone (checked before anything goes to the Hub). */ export function checkAuthor(g: Guardrails, repoId: string): void { const author = repoId.split("/")[0]; if (g.allowedAuthors.length > 0 && !g.allowedAuthors.some((a) => a.toLowerCase() === author.toLowerCase())) { throw new GuardrailError( "author_not_allowed", `author "${author}" is not on the allowlist (${g.allowedAuthors.join(", ")}). Pick a repo from one of these authors, or ask the user to extend the allowlist.`, 403, ); } } /** Throws a GuardrailError with a message an agent can act on; returns normally if allowed. */ export function checkGuardrails(g: Guardrails, x: GuardrailInput): void { checkAuthor(g, x.repoId); if (x.requestBytes > g.maxRequestBytes) { throw new GuardrailError( "too_large", `exceeds max size per request ${gb(g.maxRequestBytes)}: requested ${gb(x.requestBytes)}. Pick a smaller quant or fewer files.`, ); } if (x.openAgentJobs >= g.maxOpenJobs) { throw new GuardrailError( "too_many_jobs", `too many agent downloads at once: ${x.openAgentJobs} pending or running, the limit is ${g.maxOpenJobs}. Wait until one has finished (or been approved and finished) before requesting another.`, 429, ); } if (x.freeBytes == null) { throw new GuardrailError("disk_unknown", "free disk space is unknown (the Kaname worker is offline). Try again later.", 503); } const after = x.freeBytes - x.reservedBytes - x.requestBytes; if (after < g.minFreeBytes) { throw new GuardrailError( "disk_space", `not enough disk space: ${gb(x.requestBytes)} requested, ${gb(x.freeBytes)} free` + (x.reservedBytes > 0 ? ` (${gb(x.reservedBytes)} of it reserved by other downloads)` : "") + `, and at least ${gb(g.minFreeBytes)} must stay free (${gb(Math.max(0, after))} would be left). Pick a smaller quant or ask the user to free space.`, 507, ); } } export function describeGuardrails(g: Guardrails): string { return [ g.approvalMode === "approve" ? "requests wait for approval" : "downloads start immediately", `max ${gb(g.maxRequestBytes)} per request`, `${gb(g.minFreeBytes)} must stay free`, `max ${g.maxOpenJobs} agent jobs at once`, g.allowedAuthors.length ? `authors: ${g.allowedAuthors.join(", ")}` : "any author", ].join(" · "); }