Files
Kaname/src/lib/settings.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

180 lines
7.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import "server-only";
import { eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { settings, workerState } from "@/lib/db/schema";
import { APPROVAL_MODES, type Guardrails, parseGuardrails } from "@/lib/agent-guardrails";
import { type Backdrop, BACKDROP_KEY, parseBackdrop } from "@/lib/backdrop";
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";
import { nextScanAt, parseScanSchedule, SCAN_SCHEDULE_KEY, type ScanSchedule, ScanScheduleError, validateScanSchedule } from "@/lib/folder-scan";
import { DEFAULT_RECOMMENDED_ROLES, RECOMMENDABLE_ROLES } from "@/lib/recommend";
const FILE_ROLES_KEY = "labels.fileRoles";
export const FILE_ROLE_LABEL_MAX = 24;
type StoredRoles = Partial<Record<FileRole, { label?: string; color?: string }>>;
async function read<T>(key: string): Promise<T | null> {
try {
const row = await db().query.settings.findFirst({ where: eq(settings.key, key) });
return (row?.value as T) ?? null;
} catch {
return null; // table missing before the first migration
}
}
async function write(key: string, value: unknown) {
await db()
.insert(settings)
.values({ key, value })
.onConflictDoUpdate({ target: settings.key, set: { value, updatedAt: new Date() } });
}
/** Label text and color per file role: defaults merged with what was saved in Settings. */
export async function getFileRoleStyles(): Promise<FileRoleStyles> {
const stored = (await read<StoredRoles>(FILE_ROLES_KEY)) ?? {};
const out = {} as FileRoleStyles;
for (const role of FILE_ROLE_ORDER) {
const s = stored[role] ?? {};
out[role] = {
label: typeof s.label === "string" && s.label.trim() ? s.label.trim() : FILE_ROLES[role].label,
color: isLabelColor(s.color) ? s.color : FILE_ROLES[role].color,
};
}
return out;
}
export class SettingsError extends Error {
status = 400;
code = "invalid";
}
/** Save label/color overrides. Values equal to the default are not stored. */
export async function saveFileRoleStyles(input: Record<string, { label?: unknown; color?: unknown }>): Promise<FileRoleStyles> {
const stored: StoredRoles = {};
for (const [role, v] of Object.entries(input)) {
if (!(role in FILE_ROLES)) throw new SettingsError(`Unknown file label "${role}".`);
const def = FILE_ROLES[role as FileRole];
const entry: { label?: string; color?: string } = {};
if (v.label !== undefined) {
if (typeof v.label !== "string" || !v.label.trim() || v.label.trim().length > FILE_ROLE_LABEL_MAX) {
throw new SettingsError(`Label for "${role}" must be 1–${FILE_ROLE_LABEL_MAX} characters.`);
}
if (v.label.trim() !== def.label) entry.label = v.label.trim();
}
if (v.color !== undefined) {
if (!isLabelColor(v.color)) throw new SettingsError(`Unknown color "${String(v.color)}".`);
if (v.color !== def.color) entry.color = v.color;
}
if (entry.label || entry.color) stored[role as FileRole] = entry;
}
await write(FILE_ROLES_KEY, stored);
return getFileRoleStyles();
}
const RECOMMENDED_KEY = "downloads.recommendedRoles";
/** File kinds picked automatically along with model weights (Settings → Downloads). */
export async function getRecommendedRoles(): Promise<FileRole[]> {
const stored = await read<unknown>(RECOMMENDED_KEY);
if (!Array.isArray(stored)) return DEFAULT_RECOMMENDED_ROLES;
return RECOMMENDABLE_ROLES.filter((r) => stored.includes(r));
}
export async function saveRecommendedRoles(roles: string[]): Promise<FileRole[]> {
const unknown = roles.find((r) => !RECOMMENDABLE_ROLES.includes(r as FileRole));
if (unknown) throw new SettingsError(`"${unknown}" can't be recommended.`);
await write(RECOMMENDED_KEY, RECOMMENDABLE_ROLES.filter((r) => roles.includes(r)));
return getRecommendedRoles();
}
/** Download speed limit in bytes per second (Settings → Downloads), or null for no limit. */
export async function getDownloadSpeedLimit(): Promise<number | null> {
return parseSpeedLimit(await read<unknown>(SPEED_LIMIT_KEY));
}
export async function saveDownloadSpeedLimit(bytesPerSecond: number | null): Promise<number | null> {
if (bytesPerSecond != null && (!Number.isFinite(bytesPerSecond) || bytesPerSecond < MIN_SPEED_LIMIT)) {
throw new SettingsError("The speed limit must be at least 0.1 MB/s, or empty for no limit.");
}
if (bytesPerSecond == null) await db().delete(settings).where(eq(settings.key, SPEED_LIMIT_KEY));
else await write(SPEED_LIMIT_KEY, Math.round(bytesPerSecond));
return getDownloadSpeedLimit();
}
/** When the worker scans the models folder for importable folders (Settings → Downloads). */
export async function getScanSchedule(): Promise<ScanSchedule> {
return parseScanSchedule(await read<unknown>(SCAN_SCHEDULE_KEY));
}
export async function saveScanSchedule(input: unknown): Promise<ScanSchedule> {
try {
await write(SCAN_SCHEDULE_KEY, validateScanSchedule(input));
} catch (err) {
if (err instanceof ScanScheduleError) throw new SettingsError(err.message);
throw err;
}
return getScanSchedule();
}
export type ScanStatus = {
schedule: ScanSchedule;
lastScanAt: number | null;
lastScanFound: number | null;
/** A "Scan now" the worker hasn't started yet. */
requested: boolean;
nextScanAt: number | null;
};
export async function getScanStatus(): Promise<ScanStatus> {
const [schedule, ws] = await Promise.all([
getScanSchedule(),
db().query.workerState.findFirst({ columns: { lastScanAt: true, lastScanFound: true, scanRequestedAt: true }, where: eq(workerState.id, "worker") }),
]);
const last = ws?.lastScanAt ?? null;
const next = schedule.every === "manual" ? null : last ? nextScanAt(schedule, last) : new Date();
return {
schedule,
lastScanAt: last?.getTime() ?? null,
lastScanFound: ws?.lastScanFound ?? null,
requested: !!ws?.scanRequestedAt && (!last || ws.scanRequestedAt > last),
nextScanAt: next?.getTime() ?? null,
};
}
/** The custom picture behind the page headers (Settings → Appearance), or null for the built-in painting. */
export async function getBackdrop(): Promise<Backdrop | null> {
return parseBackdrop(await read<unknown>(BACKDROP_KEY));
}
export async function saveBackdrop(input: unknown): Promise<Backdrop | null> {
if (input == null) {
await db().delete(settings).where(eq(settings.key, BACKDROP_KEY));
return null;
}
const backdrop = parseBackdrop(input);
if (!backdrop) throw new SettingsError("That picture couldn't be read. Try another image.");
await write(BACKDROP_KEY, backdrop);
return backdrop;
}
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;
}