Files
Kaname/src/lib/library.ts
T
Pascal LinxweilerandClaude Opus 5.5 0e0445a418 API for agents: tokens, /api/v1 for downloads, verify, repair, tags
Brings back the token API that 0.15 removed with deployments, for
models only, ported onto the current code (local models, lean client
bundles, MiB-rounded disk space):

- Scoped bearer tokens (models:read, downloads:create, models:verify,
  tags:write), stored as SHA-256, managed in Settings -> API tokens.
  Only /api/v1 accepts them; the rest stays OIDC-only.
- /api/v1: Hub lookup, library with the search filters, download
  requests through the add-model/queue path (idempotent), repair of
  missing or broken files, verify / deep verify, tags, job status with
  ?wait=, cancelling or withdrawing the token's own jobs, disk space.
- Guardrails for downloads and repairs: approval (default ask), max
  size per request, minimum free space incl. reserved bytes, agent jobs
  at once, author allowlist (new downloads only). Approve/reject in the
  UI, "requested by" badges and filter, activity log per token.
- Migration 0027 adds api_tokens, agent_activity and requested_by
  columns on models and jobs; job state pending_approval.
- docs/api.md, docs/agent/SKILL.md and the kaname curl helper; DB-backed
  API tests. The login gate test now expects /api/v1 to be left to
  token auth.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:52:28 +01:00

120 lines
4.5 KiB
TypeScript

import "server-only";
import { and, asc, desc, eq, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
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";
import type { Tag } from "@/lib/tags";
export type LibraryRow = Awaited<ReturnType<typeof listLibrary>>[number];
/** Models with selected-file totals, quant labels, Hub metadata and user tags. */
export async function listLibrary() {
const d = db();
const rows = await d
.select({
id: models.id,
repoId: models.repoId,
source: models.source,
trackedRevision: models.trackedRevision,
pinnedSha: models.pinnedSha,
remoteSha: models.remoteSha,
status: models.status,
hubState: models.hubState,
updateDiff: models.updateDiff,
createdAt: models.createdAt,
downloadedAt: models.downloadedAt,
baseModels: models.baseModels,
architecture: models.architecture,
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)))
.groupBy(models.id)
.orderBy(desc(models.createdAt));
const selected = await d
.select({ modelId: modelFiles.modelId, path: modelFiles.path })
.from(modelFiles)
.where(eq(modelFiles.selected, true));
// Only model weights count as a quant (not MTP heads, mmproj or imatrix files).
const quants = groupBy(selected, (f) => f.modelId, (f) => (fileRole(f.path) === "model" ? quantGroup(f.path) : null));
const tagRows = await d
.select({ modelId: modelTags.modelId, id: tags.id, name: tags.name, color: tags.color })
.from(modelTags)
.innerJoin(tags, eq(tags.id, modelTags.tagId))
.orderBy(asc(tags.slug));
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),
);
return rows.map(({ updateDiff, ...r }) => ({
...r,
updateAvailable: !!updateDiff && updateDiff.sha === r.remoteSha && r.remoteSha !== r.pinnedSha,
author: r.repoId.split("/")[0],
families: modelFamilies(r.repoId, r.baseModels),
baseModels: r.baseModels ?? [],
hubTags: r.hubTags ?? [],
quants: [...(quants.get(r.id) ?? [])].sort(),
tags: tagsByModel.get(r.id) ?? [],
pendingApproval: pending.has(r.id),
}));
}
export async function getModel(id: string) {
const d = db();
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
if (!model) return null;
const files = await d
.select()
.from(modelFiles)
.where(eq(modelFiles.modelId, id))
.orderBy(asc(modelFiles.path));
return { model, files };
}
function groupBy<T>(items: T[], key: (t: T) => string, value: (t: T) => string | null) {
const out = new Map<string, Set<string>>();
for (const item of items) {
const v = value(item);
if (v == null) continue;
const k = key(item);
if (!out.has(k)) out.set(k, new Set());
out.get(k)!.add(v);
}
return out;
}
/** Look up a model by "org/name" (case-insensitive, like the Hub). */
export async function getModelByRepo(repoId: string) {
const row = await db()
.select({ id: models.id })
.from(models)
.where(sql`lower(${models.repoId}) = lower(${repoId})`)
.limit(1);
return row[0] ? getModel(row[0].id) : null;
}
export type RelatedModel = { repoId: string; quants: string[]; status: string };
/** Other models in the library that share a base model (e.g. another quant of the same Qwen). */
export async function relatedModels(modelId: string, baseModels: string[]): Promise<RelatedModel[]> {
if (baseModels.length === 0) return [];
const all = await listLibrary();
return all
.filter((m) => m.id !== modelId && m.baseModels.some((b) => baseModels.includes(b)))
.map((m) => ({ repoId: m.repoId, quants: m.quants, status: m.status }));
}