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

+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;