From 0e0445a4189fbf8816639c506fe690dbc4c6efa6 Mon Sep 17 00:00:00 2001 From: Pascal Linxweiler Date: Wed, 11 Nov 2026 21:52:28 +0100 Subject: [PATCH] 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 --- CHANGELOG.md | 37 + README.md | 9 + docs/agent/SKILL.md | 253 +++ docs/agent/kaname | 3 + docs/api.md | 330 ++++ drizzle/0027_api_tokens.sql | 31 + drizzle/meta/0027_snapshot.json | 1747 +++++++++++++++++ drizzle/meta/_journal.json | 7 + src/app/(app)/[org]/[repo]/download-card.tsx | 17 +- src/app/(app)/[org]/[repo]/page.tsx | 2 + src/app/(app)/jobs/[id]/job-live.tsx | 15 +- src/app/(app)/library-view.tsx | 12 +- .../api-tokens/guardrail-settings.tsx | 111 ++ src/app/(app)/settings/api-tokens/page.tsx | 24 + .../settings/api-tokens/token-settings.tsx | 389 ++++ src/app/(app)/settings/layout.tsx | 5 +- src/app/api/api-tokens/[id]/route.ts | 40 + src/app/api/api-tokens/route.ts | 23 + src/app/api/jobs/[id]/approve/route.ts | 17 + src/app/api/jobs/[id]/reject/route.ts | 16 + src/app/api/settings/agent/route.ts | 30 + src/app/api/v1/disk/route.ts | 34 + src/app/api/v1/downloads/route.ts | 49 + src/app/api/v1/hub/lookup/route.ts | 47 + src/app/api/v1/jobs/[id]/cancel/route.ts | 17 + src/app/api/v1/jobs/[id]/route.ts | 83 + src/app/api/v1/models/[id]/repair/route.ts | 20 + src/app/api/v1/models/[id]/route.ts | 40 + .../api/v1/models/[id]/tags/[name]/route.ts | 25 + src/app/api/v1/models/[id]/tags/route.ts | 21 + src/app/api/v1/models/[id]/verify/route.ts | 21 + src/app/api/v1/models/route.ts | 62 + src/app/api/v1/route.ts | 36 + src/app/api/v1/tags/route.ts | 15 + src/components/approval-bar.tsx | 62 + src/components/command-palette-dialog.tsx | 2 + src/components/job-actions.ts | 20 + src/components/requested-by-badge.tsx | 14 + src/components/user-menu.tsx | 6 +- src/lib/agent-activity.ts | 66 + src/lib/agent-downloads.ts | 267 +++ src/lib/agent-guardrails.ts | 136 ++ src/lib/agent-selection.ts | 62 + src/lib/agent.test.ts | 192 ++ src/lib/api-token-core.ts | 32 + src/lib/api-tokens.ts | 113 ++ src/lib/api-v1-filters.ts | 26 + src/lib/api-v1-models.test.ts | 294 +++ src/lib/api-v1.test.ts | 307 +++ src/lib/api-v1.ts | 54 + src/lib/db/enums.ts | 13 + src/lib/db/schema.ts | 51 + src/lib/endpoint-probe.test.ts | 9 +- src/lib/jobs.ts | 40 +- src/lib/library.ts | 8 +- src/lib/live-store.test.ts | 1 + src/lib/models.ts | 38 +- src/lib/search.test.ts | 2 + src/lib/search.ts | 16 +- src/lib/settings.ts | 20 + src/lib/token-scopes.ts | 10 + src/lib/wait.ts | 34 + src/proxy.ts | 7 +- 63 files changed, 5448 insertions(+), 42 deletions(-) create mode 100644 docs/agent/SKILL.md create mode 100755 docs/agent/kaname create mode 100644 docs/api.md create mode 100644 drizzle/0027_api_tokens.sql create mode 100644 drizzle/meta/0027_snapshot.json create mode 100644 src/app/(app)/settings/api-tokens/guardrail-settings.tsx create mode 100644 src/app/(app)/settings/api-tokens/page.tsx create mode 100644 src/app/(app)/settings/api-tokens/token-settings.tsx create mode 100644 src/app/api/api-tokens/[id]/route.ts create mode 100644 src/app/api/api-tokens/route.ts create mode 100644 src/app/api/jobs/[id]/approve/route.ts create mode 100644 src/app/api/jobs/[id]/reject/route.ts create mode 100644 src/app/api/settings/agent/route.ts create mode 100644 src/app/api/v1/disk/route.ts create mode 100644 src/app/api/v1/downloads/route.ts create mode 100644 src/app/api/v1/hub/lookup/route.ts create mode 100644 src/app/api/v1/jobs/[id]/cancel/route.ts create mode 100644 src/app/api/v1/jobs/[id]/route.ts create mode 100644 src/app/api/v1/models/[id]/repair/route.ts create mode 100644 src/app/api/v1/models/[id]/route.ts create mode 100644 src/app/api/v1/models/[id]/tags/[name]/route.ts create mode 100644 src/app/api/v1/models/[id]/tags/route.ts create mode 100644 src/app/api/v1/models/[id]/verify/route.ts create mode 100644 src/app/api/v1/models/route.ts create mode 100644 src/app/api/v1/route.ts create mode 100644 src/app/api/v1/tags/route.ts create mode 100644 src/components/approval-bar.tsx create mode 100644 src/components/requested-by-badge.tsx create mode 100644 src/lib/agent-activity.ts create mode 100644 src/lib/agent-downloads.ts create mode 100644 src/lib/agent-guardrails.ts create mode 100644 src/lib/agent-selection.ts create mode 100644 src/lib/agent.test.ts create mode 100644 src/lib/api-token-core.ts create mode 100644 src/lib/api-tokens.ts create mode 100644 src/lib/api-v1-filters.ts create mode 100644 src/lib/api-v1-models.test.ts create mode 100644 src/lib/api-v1.test.ts create mode 100644 src/lib/api-v1.ts create mode 100644 src/lib/token-scopes.ts create mode 100644 src/lib/wait.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cd1d7e..13f9aaa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,43 @@ step 1 (Hugging Face downloader) is released as a minor version. ## [Unreleased] +The API for AI agents is back, for models: a token-authenticated `/api/v1` lets an agent look up +models, download, verify, repair and tag them, within guardrails you set and, by default, only +after you approve each download or repair. + +No changes to `compose.yaml` or `.env`. If Kaname is behind a forward-auth proxy, let `/api/v1/` +through without forward auth (example in [docs/api.md](docs/api.md)). The new tables and columns are +added on start. + +### Added + +- **API tokens** (Settings → API tokens): create (shown once; only a SHA-256 hash is stored), last + used, change scopes, revoke, delete. Scopes: `models:read`, `downloads:create`, `models:verify`, + `tags:write`. Sent as `Authorization: Bearer kn_…`; only `/api/v1` accepts them, and it accepts + nothing else (the rest of Kaname stays OIDC-only). No token can delete models or files, update a + model, change settings or manage tokens. +- **`/api/v1`** ([docs/api.md](docs/api.md)), compact JSON with error messages that say what to do: + - `GET /api/v1/hub/lookup`, `GET /api/v1/models` (the library's search and filters, including + "requested by"), `GET /api/v1/models/{id}`, `GET /api/v1/tags`, `GET /api/v1/disk`. + - `POST /api/v1/downloads`: repo + pinned commit + a quant (with the recommended companion files, + as in Add model) or include globs, optional tags. Repeating a request returns the existing job. + - `POST /api/v1/models/{id}/repair`: downloads only the missing or broken files. + - `POST /api/v1/models/{id}/verify` (`{"deep": true}` hashes): never needs approval; the finished + job lists what's broken. + - `POST /api/v1/models/{id}/tags`, `DELETE /api/v1/models/{id}/tags/{name}`. + - `GET /api/v1/jobs/{id}?wait=900` holds the request until the job is done instead of polling; + `POST /api/v1/jobs/{id}/cancel` cancels or withdraws a job the token requested. +- **Guardrails for API downloads and repairs**: approval (default: ask me), max size per request + (60 GB), free space to keep, counting what open downloads still need (100 GB), agent jobs at once + (2), an optional author allowlist (new downloads only). +- **Approval**: an Approve / Reject bar on the model and job pages, "awaiting approval" in the + library. Rejecting removes a model the request added, or restores the previous file selection. +- **Requested by <token>** on models and jobs, with a "Requested by" filter in the library, and an + **activity log** per token that lists every request, including refusals with their error code. +- **Agent skill** ([docs/agent/SKILL.md](docs/agent/SKILL.md)) and the `kaname` curl helper + ([docs/agent/kaname](docs/agent/kaname)): how to check the library, look up, request, follow, + verify, repair and tag, and to wait for approval instead of retrying. + ## [0.21.0] - 2026-11-08 ### Added diff --git a/README.md b/README.md index 4394e7c..7dee581 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,9 @@ their speed and answer quality with [BetterBench](https://github.com/GGZ14/Bette - **Benchmark your endpoints:** speed runs, paired A/B tests and a quality eval against any OpenAI-compatible server, with the hardware you describe recorded next to every number; publish results to [launch80](https://launch80.com) if you like. +- **Let AI agents fetch models:** a token-authenticated API (`/api/v1`) to look up, download, + verify, repair and tag models, within guardrails you set and, by default, only after you approve + each download. A ready-made [agent skill](docs/agent/SKILL.md) explains it to the agent. - **Homelab-friendly:** a few containers, SQLite, OIDC single sign-on (e.g. Pocket ID), models on any folder or NAS share. Kaname needs no access to Docker. @@ -133,6 +136,12 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname Describe the machine behind it (GPUs, PCIe link, CPU, RAM, OS, engine build, quant, KV cache): Kaname can't see it, and these notes go into every run so results stay comparable. The API key stays on the server. +- **Agents and scripts:** create a token under Settings → API tokens (pick its scopes), set the + guardrails (approval, max size per request, free space to keep, jobs at once, allowed authors), + and hand the agent [docs/agent/SKILL.md](docs/agent/SKILL.md) with `KANAME_URL` and + `KANAME_TOKEN`. Its requests show up as **requested by <token>** with an Approve / Reject bar; + every request and refusal is in the token's activity log. Reference: [docs/api.md](docs/api.md). + Behind forward auth, let `/api/v1/` through (Kaname checks the token itself; example in the doc). - **Benchmarks:** from an endpoint's page, start a BetterBench **speed** run (generation, prompt processing, parallel requests), a paired **A/B** against another endpoint serving the same model, or the **quality** eval (tool calling, coding, long-context retrieval; deterministic). Runs go one diff --git a/docs/agent/SKILL.md b/docs/agent/SKILL.md new file mode 100644 index 0000000..f541ec9 --- /dev/null +++ b/docs/agent/SKILL.md @@ -0,0 +1,253 @@ +--- +name: kaname-models +description: Find, download, verify, repair and tag local LLMs (Hugging Face models, GGUF quants) on the user's Kaname server. Use when the user asks to get, download, add, check, fix or tag a model, asks which models are available locally, or how much disk space is left for models. +required_environment_variables: + - name: KANAME_URL + prompt: Kaname base URL, e.g. https://models.example.com (no trailing slash) + - name: KANAME_TOKEN + prompt: Kaname API token (kn_…), from Settings → API tokens +--- + +# Kaname: the user's local model library + +Kaname downloads models from Hugging Face onto the user's server, pinned to an exact commit. With +this skill you can: + +- see what is already downloaded, and how much disk space is left +- look up a Hugging Face repo (its commit, quants and sizes) +- request a download, and follow it until it's done +- verify a model's files, and repair the ones that are missing or broken +- add and remove tags on models +- cancel jobs that **you** requested + +You **cannot** delete models or files, update a model to a newer commit, change settings, or touch +jobs someone else started. When the user needs one of those, tell them to do it in Kaname's web UI. + +## Setup + +You need two environment variables: + +- `KANAME_URL`: e.g. `https://models.example.com` (no trailing slash) +- `KANAME_TOKEN`: the API token (`kn_…`). **Never print it, log it or put it in a URL.** + +The examples use `kaname`, a two-line wrapper around `curl` that adds the token and JSON headers. +Install it once: + +```bash +mkdir -p ~/.local/bin && curl -fsSL https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/branch/main/docs/agent/kaname -o ~/.local/bin/kaname && chmod +x ~/.local/bin/kaname +``` + +If `kaname` isn't available, write the full command every time instead: +`curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" …`. +Every command may run in a fresh shell, so don't rely on a shell function or alias. + +Every answer is JSON. Errors look like `{"error": {"code": "…", "message": "…"}}`, and the message +says what to do next. Read it before you do anything else. + +## 0. Check who you are and your limits + +```bash +kaname "$KANAME_URL/api/v1" +``` + +This returns your token name, your **scopes** (what you're allowed to do) and the **guardrails**: + +| Field | Default | Meaning | +| --- | --- | --- | +| `approvalMode` | `approve` | Your downloads and repairs wait until the user approves them. That's normal, not an error. | +| `maxRequestSize` | 60 GB | One request may download at most this much. | +| `minFreeSize` | 100 GB | This much must stay free on disk after your download. | +| `maxOpenAgentJobs` | 2 | At most this many agent downloads may be pending or running at once. | +| `allowedAuthors` | `[]` (any) | If not empty, new downloads must come from these Hugging Face authors. | + +| Scope | Lets you | +| --- | --- | +| `models:read` | look up repos, list models and tags, read jobs and disk space | +| `downloads:create` | request downloads and repairs, cancel your own downloads | +| `models:verify` | start verify and deep verify, cancel your own verify jobs | +| `tags:write` | add and remove tags on models | + +If a call answers `403 forbidden`, you lack the scope. Tell the user which one is missing; don't +try another way around it. + +## 1. Is the model already here? + +Always check before you download. + +```bash +kaname "$KANAME_URL/api/v1/models?q=qwen3%208b" +kaname "$KANAME_URL/api/v1/models?author=unsloth&quant=Q4_K_M&status=ready" +``` + +Filters: `q` (every word must match the repo, author, family, quant or tags), `author`, `family`, +`quant`, `tag`, `status`, `requested_by`. You can repeat a filter or separate values with commas +(OR within a filter, AND across filters). + +The `status` values are `pending`, `downloading`, `ready`, `incomplete`, `failed`, `deleting`, +`pending_approval`, `update_available`, `repo_missing` and `commit_missing`. + +If the model is there with `status: "ready"`, you're done. Don't request it again. For details on +one model (its files and their state, tags, latest job): + +```bash +kaname "$KANAME_URL/api/v1/models/" +``` + +`source: "local"` means a folder the user put there by hand, with no Hugging Face repo. Kaname +can't download into a local model or repair it, but it can verify it and tag it. + +## 2. Look up the repo on Hugging Face + +```bash +kaname "$KANAME_URL/api/v1/hub/lookup?repo=unsloth/Qwen3-8B-GGUF" +``` + +`repo` can also be a pasted Hugging Face URL. From the answer, note: + +- `sha`: the exact commit. You need it to request the download. +- `quants`: one entry per GGUF quant, with `size`. Pick one that fits what the user asked for and + is no bigger than `maxRequestSize`. If the user didn't say, `Q4_K_M` is a sensible default. +- `inLibrary`: not `null` if the repo is already in Kaname (see step 1). +- `gated`: if it isn't `false`, the download only works when the user's Hugging Face account has + accepted the model's terms. + +Check the free space before a big download: + +```bash +kaname "$KANAME_URL/api/v1/disk" # availableForRequests = what one request may still use +``` + +## 3. Request the download + +```bash +kaname -X POST "$KANAME_URL/api/v1/downloads" \ + -d '{"repoId":"unsloth/Qwen3-8B-GGUF","sha":"","quant":"Q4_K_M"}' +``` + +- `quant` downloads that quant's weight files (every split part), plus the companion files the user + picked in Kaname's settings (chat template, vision projector, …). +- For repos without GGUF quants (safetensors), send `"include": ["*.safetensors", "*.json"]` instead + of `quant`. Send exactly one of the two. +- Optional: `"tags": ["coding"]`. Run `GET /api/v1/tags` first and reuse the tags that already + exist. + +Kaname answers with one of these: + +| Answer | Meaning | What you do | +| --- | --- | --- | +| `201`, `state: "pending_approval"` | Waits for the user. | Tell the user what you requested (repo, quant, size) and that they need to approve it in Kaname. **Stop there. Don't retry and don't poll.** | +| `201`, `state: "queued"` | Starts on its own. | Follow it (step 4). | +| `200`, `created: false` | Exactly this was already requested. | You get the existing job back. Don't request it again. | + +If the repo is already in the library at the same commit, the request adds only the missing files +(for example another quant). A repo that's in the library at a different commit is refused: only +the user can update it. + +## 4. Follow a job + +```bash +kaname -m 960 "$KANAME_URL/api/v1/jobs/?wait=900" +``` + +With `?wait=900`, Kaname holds the request open until the job is finished, or up to 900 seconds. +One such call replaces a whole polling loop. Keep curl's `-m` a bit above the wait. Each call costs +you context, so make few of them: + +| `state` | What you do | +| --- | --- | +| `pending_approval` | Don't poll. Tell the user it waits for their approval and stop. Check again only when the user says they approved it (or, if they ask for it, once later from a scheduled task). | +| `queued`, `downloading`, `verifying` | One call with `?wait=900`. If it comes back with `timedOut: true`, tell the user the progress and the ETA (`progress.etaSeconds`) instead of waiting again and again. | +| `completed` | Tell the user it's ready. For a verify job, also read `verify` (see step 5). | +| `cancelled` | The user rejected or cancelled it. Don't ask again unless they tell you to. | +| `failed` | Report `error.message` to the user. Don't retry in a loop. | +| `interrupted` | Kaname restarted. Tell the user; they can resume it. | + +Add `&log=20` only when you need to explain a failure (the last lines of the download log). + +## 5. Verify and repair + +Run a verify when the user asks whether a model is intact, or after something went wrong: + +```bash +kaname -X POST "$KANAME_URL/api/v1/models//verify" # presence and size, takes seconds +kaname -X POST "$KANAME_URL/api/v1/models//verify" -d '{"deep":true}' # hashes every byte: slow, but thorough +``` + +A verify starts right away; it never needs approval. Follow it like any other job. When it has +finished, the job has a `verify` block: + +```json +"verify": { "ok": false, "missing": ["…gguf"], "sizeMismatch": [], "hashMismatch": [], "next": "POST /api/v1/models/…/repair …" } +``` + +If `ok` is `false`, repair it. That downloads only the files that are missing or broken: + +```bash +kaname -X POST "$KANAME_URL/api/v1/models//repair" +``` + +A repair counts as a download: same guardrails, and by default it waits for the user's approval +just like step 3. If nothing is broken, Kaname answers `409 nothing_to_repair`. Then don't repair; +run a deep verify if you suspect damage. Deep verify and repair aren't possible for local models. + +## 6. Tags + +```bash +kaname "$KANAME_URL/api/v1/tags" # existing tags, with how many models use each +kaname -X POST "$KANAME_URL/api/v1/models//tags" -d '{"name":"coding"}' # add (creates the tag if it's new) +kaname -X DELETE "$KANAME_URL/api/v1/models//tags/coding" # remove (by name, case-insensitive) +``` + +Reuse existing tags instead of inventing near-duplicates (`code` vs `coding`). Removing a tag from a +model doesn't delete the tag itself. Tag only what the user asked for, or what clearly fits their +existing scheme. + +## 7. Cancel your own job + +```bash +kaname -X POST "$KANAME_URL/api/v1/jobs//cancel" +``` + +This works only for jobs your token requested: + +- A job that's still `pending_approval` is withdrawn. If it was a brand-new model, the model leaves + the library again (`removedModel: true`). +- A queued or running job is stopped. Files that are already downloaded stay. + +For anything else you get `403 not_own_job`: tell the user they can cancel it in Kaname. + +## When a request is refused + +| `error.code` | What to do | +| --- | --- | +| `too_large` | Pick a smaller quant, or fewer files, that fits `maxRequestSize`. | +| `disk_space` | Pick a smaller quant, or tell the user the disk is full. | +| `too_many_jobs` | Your earlier downloads are still pending or running. Tell the user and stop. Don't wait in a loop. | +| `author_not_allowed` | Find the model from an allowed author, or ask the user. | +| `already_exists` | The repo is in the library at another commit; the user updates it in Kaname. | +| `busy` | That model already has a job pending or running. Tell the user and stop. | +| `nothing_to_repair` | Every file is present. Run a deep verify first if you suspect damage. | +| `local_model` | A local folder: nothing to download, and no hashes to compare against. Use a plain verify. | +| `not_own_job` | Only the user can cancel this job. | +| `gated_no_access`, `gated_no_token` | The user must accept the model's terms on Hugging Face (and Kaname needs a token). | +| `disk_unknown` | Kaname's worker is offline. Tell the user and stop. | +| `rate_limited` | Hugging Face is rate limiting. Try once more later, not in a loop. | +| `unauthorized`, `forbidden` | Your token is wrong or revoked, or it lacks a scope. Tell the user. | +| `invalid_request`, `invalid_json` | Fix the request as the message says. | + +Never work around a guardrail, for example by splitting one big download into several requests, or +by repairing a model to fetch files it never had. Everything you do is listed under your token's +name in Kaname, refusals included. + +## A complete example + +> User: "Get me Qwen3 8B, something that fits in about 6 GB." + +1. `kaname "$KANAME_URL/api/v1/models?q=qwen3%208b"`: nothing ready yet. +2. `kaname "$KANAME_URL/api/v1/hub/lookup?repo=unsloth/Qwen3-8B-GGUF"`: `Q4_K_M` is 5.0 GB; note `sha`. +3. `kaname -X POST "$KANAME_URL/api/v1/downloads" -d '{"repoId":"unsloth/Qwen3-8B-GGUF","sha":"…","quant":"Q4_K_M"}'` + answers `pending_approval`. +4. Tell the user: "I've requested unsloth/Qwen3-8B-GGUF Q4_K_M (5.0 GB). It's waiting for your + approval in Kaname." Then stop. +5. When the user says it's approved: `kaname -m 960 "$KANAME_URL/api/v1/jobs/?wait=900"`, then + report that it's done, or the progress and ETA. diff --git a/docs/agent/kaname b/docs/agent/kaname new file mode 100755 index 0000000..0898f2d --- /dev/null +++ b/docs/agent/kaname @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# curl with the Kaname API token and JSON headers. Usage: kaname [curl options] URL +exec curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" "$@" diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..f093698 --- /dev/null +++ b/docs/api.md @@ -0,0 +1,330 @@ +# Kaname API (`/api/v1`) + +A small JSON API for programs and AI agents: look up Hugging Face repos, list the library, request +downloads and follow them, verify and repair models, and tag them. Everything a token can do is +bounded by [guardrails](#guardrails). No token can delete models or files, update a model to +another commit, change settings, manage tokens, or touch jobs it didn't request. + +The rest of Kaname (the web UI and its internal `/api/*` routes) stays behind your OIDC login. Only +`/api/v1` accepts tokens, and it accepts *only* tokens: a browser session doesn't work there. + +For agents there's a ready-made skill: [docs/agent/SKILL.md](agent/SKILL.md). Give it to the agent +together with `KANAME_URL` and `KANAME_TOKEN`. + +- [Authentication](#authentication) +- [Errors](#errors) +- [Endpoints](#endpoints) +- [Waiting instead of polling](#waiting-instead-of-polling) +- [Guardrails](#guardrails) and [approval](#approval) +- [Activity](#activity) +- [Behind a forward-auth proxy (Traefik)](#behind-a-forward-auth-proxy-traefik) + +## Authentication + +Create a token in **Settings → API tokens**. It is shown once; Kaname stores only its SHA-256. +Send it with every request: + +``` +Authorization: Bearer kn_… +``` + +| Scope | Allows | +| --- | --- | +| `models:read` | Hub lookup, list models and tags, read jobs (and their log), disk space | +| `downloads:create` | Request downloads and repairs (within the guardrails); cancel its own downloads | +| `models:verify` | Start verify and deep verify; cancel its own verify jobs | +| `tags:write` | Add and remove tags on models (a new tag is created on first use) | + +A missing, unknown or revoked token gets `401`; a token without the needed scope gets `403`. The +settings page shows when each token was last used. **Scopes** changes what a token may do (from its +next request on); **Revoke** stops it immediately; a revoked token can be deleted to free its name. + +Everything a token requests is marked with its name ("requested by hermes") on the model and job +pages and in the library, where you can filter by it (**Requested by**). + +## Errors + +Errors are JSON with a message meant to be read and acted on: + +```json +{ "error": { "code": "too_large", "message": "exceeds max size per request 60.0 GB: requested 74.2 GB. Pick a smaller quant or fewer files." } } +``` + +| Status | Codes | +| --- | --- | +| 400 | `invalid_request` (also unknown fields), `invalid_json`, `empty_selection` (the quant or globs match nothing), `invalid_repo_id`, `invalid` (e.g. an empty tag name) | +| 401 / 403 | `unauthorized`, `forbidden` (scope), `not_own_job`, `author_not_allowed`, `gated_no_token`, `gated_no_access` | +| 404 | `not_found`, `repo_not_found`, `revision_not_found` | +| 409 | `already_exists` (the repo is in the library at another commit), `busy` (the model has a pending, queued or running job), `nothing_to_repair`, `local_model`, `not_cancellable`, `hub_missing` | +| 422 | `too_large` | +| 429 | `too_many_jobs`, `rate_limited` (Hugging Face) | +| 503 / 507 | `disk_unknown` (worker offline), `disk_space` | + +Sizes come as bytes plus a readable `"… GB"` field (decimal GB, like the Hub). + +## Endpoints + +| Method and path | Scope | +| --- | --- | +| [`GET /api/v1`](#get-apiv1) | any token | +| [`GET /api/v1/hub/lookup?repo=`](#get-apiv1hublookup) | `models:read` | +| [`GET /api/v1/models`](#get-apiv1models), [`GET /api/v1/models/{id}`](#get-apiv1modelsid) | `models:read` | +| [`GET /api/v1/tags`](#tags) | `models:read` | +| [`GET /api/v1/jobs/{id}`](#get-apiv1jobsid) | `models:read` | +| [`GET /api/v1/disk`](#get-apiv1disk) | `models:read` | +| [`POST /api/v1/downloads`](#post-apiv1downloads) | `downloads:create` | +| [`POST /api/v1/models/{id}/repair`](#post-apiv1modelsidrepair) | `downloads:create` | +| [`POST /api/v1/models/{id}/verify`](#post-apiv1modelsidverify) | `models:verify` | +| [`POST /api/v1/jobs/{id}/cancel`](#post-apiv1jobsidcancel) | `downloads:create` or `models:verify` (own jobs only) | +| [`POST /api/v1/models/{id}/tags`, `DELETE /api/v1/models/{id}/tags/{name}`](#tags) | `tags:write` | + +### `GET /api/v1` + +Who you are, your scopes, the current guardrails and the endpoint list. + +```bash +curl -s -H "Authorization: Bearer $KANAME_TOKEN" "$KANAME_URL/api/v1" +``` + +```json +{ + "token": { "name": "hermes", "scopes": ["models:read", "downloads:create"] }, + "guardrails": { "approvalMode": "approve", "maxRequestBytes": 60000000000, "maxRequestSize": "60.0 GB", + "minFreeBytes": 100000000000, "minFreeSize": "100.0 GB", "maxOpenAgentJobs": 2, "allowedAuthors": [] }, + "endpoints": ["…"] +} +``` + +### `GET /api/v1/hub/lookup` + +`?repo=org/name[&revision=main][&files=all]`. Resolves the revision to a commit SHA and lists quants +and files: the same data as the Add model dialog. `repo` may also be a Hub URL. Up to 200 files are +listed unless `files=all`. + +```json +{ + "repoId": "unsloth/Qwen3-8B-GGUF", "revision": "main", "sha": "9e6855bc…", "gated": false, + "lastModified": "2026-05-01T10:00:00.000Z", + "inLibrary": null, + "quants": [{ "quant": "Q4_K_M", "files": 1, "bytes": 5027783488, "size": "5.0 GB" }, "…"], + "fileCount": 31, "totalBytes": 104000000000, + "files": [{ "path": "Qwen3-8B-Q4_K_M.gguf", "bytes": 5027783488 }, "…"], + "filesTruncated": false +} +``` + +`inLibrary` is `{ modelId, pinnedSha, status }` when the repo is already in Kaname. + +### `GET /api/v1/models` + +The library, filtered like the library page: + +| Parameter | Meaning | +| --- | --- | +| `q` | Search text; every word must match (repo, author, family, quant, tags, …) | +| `author`, `family`, `quant`, `tag` | Facets; repeat or comma-separate values (OR within a facet, AND across) | +| `status` | `pending`, `downloading`, `ready`, `incomplete`, `failed`, `deleting`, `pending_approval`, `update_available`, `repo_missing`, `commit_missing` | +| `requested_by` | Token name | + +```json +{ "count": 1, "models": [{ "id": "01M…", "repoId": "unsloth/Qwen3-8B-GGUF", "source": "hub", "status": "ready", + "pendingApproval": false, "pinnedSha": "9e68…", "quants": ["Q4_K_M"], "tags": ["agent"], "selectedFiles": 2, + "selectedBytes": 5027783488, "onDiskBytes": 5027783488, "onDisk": "5.0 GB", "updateAvailable": false, + "hubState": "available", "requestedBy": "hermes", "createdAt": "…", "downloadedAt": "…" }] } +``` + +`source` is `local` for folders imported without a Hub repo; they have no `pinnedSha`. + +### `GET /api/v1/models/{id}` + +One model: status, pinned commit, tags, folder (`localPath`, relative to the models folder), the +selected files with their state (`pending`, `present`, `missing`, `size_mismatch`, `hash_mismatch`, +`verified`), the last verify time and the latest job. + +### `POST /api/v1/downloads` + +Request a download of a repo **at a pinned commit**: take `sha` from the lookup. + +| Field | | +| --- | --- | +| `repoId` | `"org/name"` | +| `sha` | The full 40-character commit SHA | +| `quant` | e.g. `"Q4_K_M"`: that quant's weight files (all split parts), plus the companion files ticked in Settings → Downloads (chat template, mmproj, …), as in the Add model dialog | +| `include` | Instead of `quant`: glob patterns, e.g. `["*.safetensors", "*.json"]` | +| `tags` | Optional user tags for the model | +| `revision` | Optional branch to track for update checks (default `main`) | + +```bash +curl -s -X POST -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" \ + -d '{"repoId":"unsloth/Qwen3-8B-GGUF","sha":"9e6855bc…","quant":"Q4_K_M"}' \ + "$KANAME_URL/api/v1/downloads" +``` + +```json +{ "created": true, "modelId": "01M…", "jobId": "01M…", "state": "pending_approval", + "requestedBytes": 5027783488, "requestedSize": "5.0 GB", "files": ["Qwen3-8B-Q4_K_M.gguf", "template"], + "message": "Requested; waiting for the user to approve it in Kaname. Do not retry or poll; tell the user and stop." } +``` + +- **201**: a new job, `state` `pending_approval` (approval mode *Ask me*) or `queued` (*Automatic*). +- **200** with `"created": false`: the same repo, commit and files were requested before; you get the + existing model and its latest job. Nothing is queued twice. +- If the repo is already in the library at the same commit, the request adds the files missing from + its selection (only the added bytes count against the guardrails). At another commit it is + refused: updating a model is done in the UI. A local model with the same name is refused too. + +It uses the same code as the Add model dialog: the file list is fetched again from the Hub at that +commit (the client's list isn't trusted). + +### `POST /api/v1/models/{id}/repair` + +Downloads again the selected files that aren't `present` or `verified` (after a verify found them +missing or broken, or after a failed download). The guardrails and approval apply as for a download; +only the author allowlist doesn't (the model is already in the library). `409 nothing_to_repair` if +every file is present; `409 local_model` for a local model. + +```json +{ "modelId": "01M…", "jobId": "01M…", "state": "pending_approval", "requestedBytes": 8000000000, + "requestedSize": "8.0 GB", "files": ["Qwen3-8B-Q8_0.gguf"], "message": "…" } +``` + +### `POST /api/v1/models/{id}/verify` + +Body optional: `{"deep": true}` hashes every file against the Hub (slow); without it, Kaname checks +each selected file's presence and size (seconds). Verify only reads files, so it never waits for +approval and doesn't count against the guardrails. Deep verify isn't possible for a local model. +Answers `201` with the `jobId`; the finished job carries a [`verify`](#get-apiv1jobsid) block. + +### `GET /api/v1/jobs/{id}` + +`[?wait=S][&log=N]`. Compact job state: + +```json +{ "id": "01M…", "modelId": "01M…", "repoId": "unsloth/Qwen3-8B-GGUF", "kind": "download", "purpose": "initial", + "state": "downloading", "cancelRequested": false, "requestedBy": "hermes", + "progress": { "doneBytes": 3000000000, "totalBytes": 5027783488, "percent": 59.7, "done": "3.0 GB", "total": "5.0 GB", + "speedBytesPerSecond": 52000000, "etaSeconds": 39 }, + "error": null, + "files": [{ "path": "Qwen3-8B-Q4_K_M.gguf", "state": "downloading", "doneBytes": 3000000000, "totalBytes": 5027783488 }], + "createdAt": "…", "startedAt": "…", "finishedAt": null, + "next": "Downloading; GET with ?wait=900 instead of polling." } +``` + +- `kind`: `download`, `verify`, `deep_verify` or `delete`. `purpose` (downloads): `initial`, `add`, + `import`, `repair`, `update`. +- `state`: `pending_approval`, `queued`, `downloading`, `verifying`, `completed`, `failed`, + `cancelled` (also when the user rejected the request), `interrupted`. +- A finished verify adds + `"verify": { "checked": 2, "missing": [], "sizeMismatch": [], "hashMismatch": [], "ok": true, "next": "…" }`. +- The `hf` log only with `?log=N` (the last N lines, at most 200). For `?wait=S` see + [Waiting instead of polling](#waiting-instead-of-polling). + +### `POST /api/v1/jobs/{id}/cancel` + +Only for jobs this token requested (`403 not_own_job` otherwise); download jobs need +`downloads:create`, verify jobs `models:verify`. + +- A job that waits for approval is **withdrawn**, exactly like a rejection: a model that only this + request added leaves the library again (`"removedModel": true`), and added files leave the + selection again. +- A queued or running job is stopped by the worker (`"state": "cancelling"`). Files already on disk + stay. + +### Tags + +- `GET /api/v1/tags`: every tag with the number of models using it: + `{ "count": 2, "tags": [{ "name": "coding", "models": 3 }, …] }`. +- `POST /api/v1/models/{id}/tags` with `{"name": "coding"}`: attaches the tag, creating it if no + tag of that name exists (names match case-insensitively). Answers with the model's tags. +- `DELETE /api/v1/models/{id}/tags/{name}`: detaches the tag (by name, case-insensitive; URL-encode + it). The tag itself stays; delete or rename tags in Settings → Tags. + +### `GET /api/v1/disk` + +Space on the models folder, as reported by the worker every few seconds: + +```json +{ "workerOnline": true, "freeBytes": 945600000000, "totalBytes": 2000000000000, "usedBytes": 1054400000000, + "reservedBytes": 105454144, "minFreeBytes": 100000000000, "availableForRequestsBytes": 845494545856, + "free": "945.6 GB", "total": "2000.0 GB", "availableForRequests": "845.5 GB" } +``` + +`reservedBytes` is what open downloads still have to fetch; `availableForRequests` is what a +request may use before it hits the minimum-free guardrail. + +## Waiting instead of polling + +Every status call costs an agent a round of its context. `GET /api/v1/jobs/{id}` takes `?wait=S` +(seconds, at most 900): the request is held until the job is settled (finished, failed, cancelled, +interrupted) or the time is up, then answers with the current state plus `waitedSeconds` and +`timedOut`. A job that waits for the user's approval answers right away: there's nothing to wait +for. Use one waiting call instead of a polling loop, with a wait shorter than your HTTP client's +timeout (and any proxy's). + +## Guardrails + +Settings → API tokens → **Guardrails for API downloads**. They apply to every token together and to +downloads and repairs; downloads you start in the UI aren't affected. + +| Setting | Default | Rejection | +| --- | --- | --- | +| Approval | **Ask me**: requests wait as *pending approval* until you approve or reject them | (not an error: `state: pending_approval`) | +| Max size per request | 60 GB | `422 too_large` | +| Keep free on the models folder | 100 GB, after the download and after what other open downloads still need | `507 disk_space` (`503 disk_unknown` if the worker is offline) | +| Agent jobs at once | 2 downloads or repairs (pending approval, queued or running) | `429 too_many_jobs` | +| Allowed authors | empty = any; e.g. `unsloth, ggml-org, Qwen` (case-insensitive). New downloads only | `403 author_not_allowed` | + +Verify, deep verify and tags never need approval and don't count against these limits; a model can +have only one job at a time either way (`409 busy`). + +### Approval + +A pending request shows an **Approve / Reject** bar on the model page and the job page, and +*awaiting approval* in the library (filter Status → awaiting approval). Approving queues it. +Rejecting cancels the job: a model that only that request added leaves the library again; for a +request that added files to an existing model, the previous selection is restored. + +## Activity + +Settings → API tokens → **Activity** next to each token lists what it did: every request that +creates or changes something (downloads, repairs, verifies, tags, cancels), whether it waits for +approval, and every refusal with its error code. + +## Behind a forward-auth proxy (Traefik) + +If Kaname sits behind forward auth (e.g. Traefik with Tinyauth or Pocket ID), the proxy would answer +API calls with a login redirect. Let `/api/v1/` through without forward auth; Kaname checks the +bearer token itself there. Everything else keeps forward auth. + +Two routers for the same host, the API one with a higher priority and no auth middleware: + +```yaml +# docker compose labels on the kaname "web" service +labels: + - traefik.enable=true + - traefik.http.services.kaname.loadbalancer.server.port=3000 + + # UI and internal API: forward auth as before + - traefik.http.routers.kaname.rule=Host(`models.example.com`) + - traefik.http.routers.kaname.entrypoints=websecure + - traefik.http.routers.kaname.tls=true + - traefik.http.routers.kaname.middlewares=tinyauth + - traefik.http.routers.kaname.service=kaname + + # Token API: no forward auth (bearer tokens are checked by Kaname) + - traefik.http.routers.kaname-api.rule=Host(`models.example.com`) && PathPrefix(`/api/v1/`) + - traefik.http.routers.kaname-api.entrypoints=websecure + - traefik.http.routers.kaname-api.tls=true + - traefik.http.routers.kaname-api.priority=100 + - traefik.http.routers.kaname-api.service=kaname +``` + +Notes: + +- Use ``PathPrefix(`/api/v1/`)`` with the trailing slash, so nothing else that starts with `/api/v1` + slips past forward auth. Kaname's own login gate also excludes exactly `/api/v1` and `/api/v1/…`. +- Don't exempt `/api` as a whole: the internal routes rely on the login session. +- Agents on the same network can also call Kaname directly (`http://:3000/api/v1/…`) without + going through the proxy. +- `?wait=` holds a request open for up to 15 minutes; raise the proxy's response timeout, or ask + agents to use a shorter wait. diff --git a/drizzle/0027_api_tokens.sql b/drizzle/0027_api_tokens.sql new file mode 100644 index 0000000..8649477 --- /dev/null +++ b/drizzle/0027_api_tokens.sql @@ -0,0 +1,31 @@ +CREATE TABLE `agent_activity` ( + `id` text PRIMARY KEY NOT NULL, + `token_id` text NOT NULL, + `token_name` text NOT NULL, + `action` text NOT NULL, + `target_type` text, + `target_id` text, + `outcome` text NOT NULL, + `code` text, + `message` text, + `created_at` integer NOT NULL +); +--> statement-breakpoint +CREATE INDEX `agent_activity_token_idx` ON `agent_activity` (`token_id`,`created_at`);--> statement-breakpoint +CREATE TABLE `api_tokens` ( + `id` text PRIMARY KEY NOT NULL, + `name` text NOT NULL, + `prefix` text NOT NULL, + `hash` text NOT NULL, + `scopes` text NOT NULL, + `last_used_at` integer, + `revoked_at` integer, + `created_at` integer NOT NULL +); +--> statement-breakpoint +CREATE UNIQUE INDEX `api_tokens_hash_unique` ON `api_tokens` (`hash`);--> statement-breakpoint +CREATE UNIQUE INDEX `api_tokens_name_uq` ON `api_tokens` (`name`);--> statement-breakpoint +ALTER TABLE `jobs` ADD `requested_by_token_id` text;--> statement-breakpoint +ALTER TABLE `jobs` ADD `requested_by` text;--> statement-breakpoint +ALTER TABLE `models` ADD `requested_by_token_id` text;--> statement-breakpoint +ALTER TABLE `models` ADD `requested_by` text; \ No newline at end of file diff --git a/drizzle/meta/0027_snapshot.json b/drizzle/meta/0027_snapshot.json new file mode 100644 index 0000000..fae73e8 --- /dev/null +++ b/drizzle/meta/0027_snapshot.json @@ -0,0 +1,1747 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "c2d130a8-964b-42a6-812b-6fbc4e04934f", + "prevId": "28ecf2b3-57f9-43fd-a258-b798d9c16108", + "tables": { + "agent_activity": { + "name": "agent_activity", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "token_id": { + "name": "token_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_name": { + "name": "token_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code": { + "name": "code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "agent_activity_token_idx": { + "name": "agent_activity_token_idx", + "columns": [ + "token_id", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "api_tokens": { + "name": "api_tokens", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prefix": { + "name": "prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "hash": { + "name": "hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scopes": { + "name": "scopes", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "api_tokens_hash_unique": { + "name": "api_tokens_hash_unique", + "columns": [ + "hash" + ], + "isUnique": true + }, + "api_tokens_name_uq": { + "name": "api_tokens_name_uq", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "benchmark_logs": { + "name": "benchmark_logs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ts": { + "name": "ts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stream": { + "name": "stream", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "line": { + "name": "line", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "benchmark_logs_idx": { + "name": "benchmark_logs_idx", + "columns": [ + "run_id", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "benchmark_publications": { + "name": "benchmark_publications", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'preview'" + }, + "template": { + "name": "template", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'bench.betterbench.v1'" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "payload_bytes": { + "name": "payload_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "previewed_at": { + "name": "previewed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "confirmed_by": { + "name": "confirmed_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "confirmed_at": { + "name": "confirmed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "guid": { + "name": "guid", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "published_at": { + "name": "published_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "benchmark_publications_run_idx": { + "name": "benchmark_publications_run_idx", + "columns": [ + "run_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "benchmark_runs": { + "name": "benchmark_runs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "endpoint_id": { + "name": "endpoint_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "endpoint_b_id": { + "name": "endpoint_b_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tool": { + "name": "tool", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'betterbench'" + }, + "settings": { + "name": "settings", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "snapshot": { + "name": "snapshot", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "phase": { + "name": "phase", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cancel_requested_at": { + "name": "cancel_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "has_report": { + "name": "has_report", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'run'" + }, + "snapshot_b": { + "name": "snapshot_b", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ab": { + "name": "ab", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "quality": { + "name": "quality", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "meta": { + "name": "meta", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "meta_b": { + "name": "meta_b", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "system": { + "name": "system", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "benchmark_runs_created_idx": { + "name": "benchmark_runs_created_idx", + "columns": [ + "created_at" + ], + "isUnique": false + }, + "benchmark_runs_state_idx": { + "name": "benchmark_runs_state_idx", + "columns": [ + "state", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "endpoints": { + "name": "endpoints", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "base_url": { + "name": "base_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "api_key": { + "name": "api_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "engine": { + "name": "engine", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hardware": { + "name": "hardware", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "probe": { + "name": "probe", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "endpoints_name_uq": { + "name": "endpoints_name_uq", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "job_files": { + "name": "job_files", + "columns": { + "job_id": { + "name": "job_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model_file_id": { + "name": "model_file_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expected_bytes": { + "name": "expected_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "done_bytes": { + "name": "done_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + } + }, + "indexes": {}, + "foreignKeys": { + "job_files_job_id_jobs_id_fk": { + "name": "job_files_job_id_jobs_id_fk", + "tableFrom": "job_files", + "tableTo": "jobs", + "columnsFrom": [ + "job_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "job_files_model_file_id_model_files_id_fk": { + "name": "job_files_model_file_id_model_files_id_fk", + "tableFrom": "job_files", + "tableTo": "model_files", + "columnsFrom": [ + "model_file_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "job_files_job_id_model_file_id_pk": { + "columns": [ + "job_id", + "model_file_id" + ], + "name": "job_files_job_id_model_file_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "job_logs": { + "name": "job_logs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "job_id": { + "name": "job_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ts": { + "name": "ts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stream": { + "name": "stream", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "line": { + "name": "line", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "job_logs_job_idx": { + "name": "job_logs_job_idx", + "columns": [ + "job_id", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "job_logs_job_id_jobs_id_fk": { + "name": "job_logs_job_id_jobs_id_fk", + "tableFrom": "job_logs", + "tableTo": "jobs", + "columnsFrom": [ + "job_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "jobs": { + "name": "jobs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_sha": { + "name": "target_sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "attempt": { + "name": "attempt", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "total_bytes": { + "name": "total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "done_bytes": { + "name": "done_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "speed_bps": { + "name": "speed_bps", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "eta_seconds": { + "name": "eta_seconds", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "exit_code": { + "name": "exit_code", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cancel_requested_at": { + "name": "cancel_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requested_by_token_id": { + "name": "requested_by_token_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requested_by": { + "name": "requested_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "jobs_state_idx": { + "name": "jobs_state_idx", + "columns": [ + "state" + ], + "isUnique": false + }, + "jobs_model_idx": { + "name": "jobs_model_idx", + "columns": [ + "model_id" + ], + "isUnique": false + }, + "jobs_finished_idx": { + "name": "jobs_finished_idx", + "columns": [ + "finished_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "jobs_model_id_models_id_fk": { + "name": "jobs_model_id_models_id_fk", + "tableFrom": "jobs", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "local_folders": { + "name": "local_folders", + "columns": { + "path": { + "name": "path", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "files": { + "name": "files", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file_count": { + "name": "file_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total_bytes": { + "name": "total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "commit": { + "name": "commit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "readme": { + "name": "readme", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "scanned_at": { + "name": "scanned_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "model_files": { + "name": "model_files", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blob_oid": { + "name": "blob_oid", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lfs_sha256": { + "name": "lfs_sha256", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "selected": { + "name": "selected", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "model_files_model_path_uq": { + "name": "model_files_model_path_uq", + "columns": [ + "model_id", + "path" + ], + "isUnique": true + } + }, + "foreignKeys": { + "model_files_model_id_models_id_fk": { + "name": "model_files_model_id_models_id_fk", + "tableFrom": "model_files", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "model_revisions": { + "name": "model_revisions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pinned_at": { + "name": "pinned_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "superseded_at": { + "name": "superseded_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "model_revisions_model_idx": { + "name": "model_revisions_model_idx", + "columns": [ + "model_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "model_revisions_model_id_models_id_fk": { + "name": "model_revisions_model_id_models_id_fk", + "tableFrom": "model_revisions", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "model_tags": { + "name": "model_tags", + "columns": { + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tag_id": { + "name": "tag_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "model_tags_tag_idx": { + "name": "model_tags_tag_idx", + "columns": [ + "tag_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "model_tags_model_id_models_id_fk": { + "name": "model_tags_model_id_models_id_fk", + "tableFrom": "model_tags", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "model_tags_tag_id_tags_id_fk": { + "name": "model_tags_tag_id_tags_id_fk", + "tableFrom": "model_tags", + "tableTo": "tags", + "columnsFrom": [ + "tag_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "model_tags_model_id_tag_id_pk": { + "columns": [ + "model_id", + "tag_id" + ], + "name": "model_tags_model_id_tag_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "models": { + "name": "models", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "repo_type": { + "name": "repo_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'model'" + }, + "repo_id": { + "name": "repo_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'hub'" + }, + "tracked_revision": { + "name": "tracked_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "pinned_sha": { + "name": "pinned_sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "local_readme": { + "name": "local_readme", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "local_path": { + "name": "local_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "include_patterns": { + "name": "include_patterns", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "exclude_patterns": { + "name": "exclude_patterns", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "remote_sha": { + "name": "remote_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_at": { + "name": "last_checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_check_error": { + "name": "last_check_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hub_state": { + "name": "hub_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hub_missing_since": { + "name": "hub_missing_since", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "update_diff": { + "name": "update_diff", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_verified_at": { + "name": "last_verified_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "downloaded_at": { + "name": "downloaded_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "base_models": { + "name": "base_models", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "base_relation": { + "name": "base_relation", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "author_avatar_url": { + "name": "author_avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "architecture": { + "name": "architecture", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pipeline_tag": { + "name": "pipeline_tag", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "license": { + "name": "license", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hub_tags": { + "name": "hub_tags", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata_fetched_at": { + "name": "metadata_fetched_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requested_by_token_id": { + "name": "requested_by_token_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requested_by": { + "name": "requested_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "models_repo_uq": { + "name": "models_repo_uq", + "columns": [ + "repo_type", + "repo_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tags": { + "name": "tags", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "tags_slug_uq": { + "name": "tags_slug_uq", + "columns": [ + "slug" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "worker_state": { + "name": "worker_state", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "instance_id": { + "name": "instance_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pid": { + "name": "pid", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hf_version": { + "name": "hf_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "models_dir_free_bytes": { + "name": "models_dir_free_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "models_dir_total_bytes": { + "name": "models_dir_total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "heartbeat_at": { + "name": "heartbeat_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scan_requested_at": { + "name": "scan_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_scan_at": { + "name": "last_scan_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_scan_found": { + "name": "last_scan_found", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index e7dc631..67d933b 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -190,6 +190,13 @@ "when": 1794093954553, "tag": "0026_local_readme", "breakpoints": true + }, + { + "idx": 27, + "version": "6", + "when": 1794429640033, + "tag": "0027_api_tokens", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/app/(app)/[org]/[repo]/download-card.tsx b/src/app/(app)/[org]/[repo]/download-card.tsx index 9958f93..472c360 100644 --- a/src/app/(app)/[org]/[repo]/download-card.tsx +++ b/src/app/(app)/[org]/[repo]/download-card.tsx @@ -2,7 +2,9 @@ import { DownloadIcon, ShieldCheckIcon, WrenchIcon } from "lucide-react"; import Link from "next/link"; +import { useRouter } from "next/navigation"; import { useState } from "react"; +import { ApprovalBar } from "@/components/approval-bar"; import { cancelJob, startDownload, startRepair, startVerify } from "@/components/job-actions"; import { JobProgress, JobStateBadge } from "@/components/job-progress"; import { Button } from "@/components/ui/button"; @@ -36,6 +38,8 @@ export function DownloadCard({ const jobs = snapshot?.jobs ?? []; const latest = jobs[0]; const open = latest && OPEN.includes(latest.state) ? latest : undefined; + const pending = latest?.state === "pending_approval" ? latest : undefined; + const router = useRouter(); const files = open ? groupJobFiles(snapshot?.files ?? []) : []; // The newest verify, unless a download ran after it (its result would be stale). const lastCheck = jobs.find((j) => VERIFY_KINDS.includes(j.kind) || j.kind === "download"); @@ -61,12 +65,13 @@ export function DownloadCard({ : latest?.state === "failed" && latest.kind === "download" ? "Retry" : "Download missing"; - const canDownload = !open && !local && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot; - const canVerify = !open && (!neverRan || local) && status !== "deleting" && !!snapshot; - const needsRepair = !open && !local && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete"); + const canDownload = !open && !pending && !local && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot; + const canVerify = !open && !pending && (!neverRan || local) && status !== "deleting" && !!snapshot; + const needsRepair = !open && !pending && !local && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete"); let hint = local ? "A local folder: Kaname keeps its files as they are." : "Downloads the selected files at the pinned commit."; - if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline."; + if (pending) hint = "Requested through the API; waits for your approval."; + else if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline."; else if (open) hint = "Runs in the background; you can close this page."; else if (status === "deleting") hint = "Deleting…"; else if (hubMissing && status !== "ready") hint = "Can't download: no longer available on Hugging Face. Local files are kept."; @@ -87,7 +92,9 @@ export function DownloadCard({

{hint}

- {showProgress && } + {pending && router.push("/")} />} + + {showProgress && !pending && } {latest?.state === "failed" && latest.errorMessage && (
diff --git a/src/app/(app)/[org]/[repo]/page.tsx b/src/app/(app)/[org]/[repo]/page.tsx
index 489bbdb..10ccd3e 100644
--- a/src/app/(app)/[org]/[repo]/page.tsx
+++ b/src/app/(app)/[org]/[repo]/page.tsx
@@ -41,6 +41,7 @@ import { JobsTab } from "./jobs-tab";
 import { LocalModelCardSection, ModelCardSection, ModelCardSkeleton } from "./model-card";
 import { DeleteModelButton } from "./delete-model-button";
 import { TagEditor } from "./tag-editor";
+import { RequestedByBadge } from "@/components/requested-by-badge";
 import { UpdateBanner } from "./update-banner";
 
 export const dynamic = "force-dynamic";
@@ -154,6 +155,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
           
           )}
           
+          
           {local && (
             (null);
   const [follow, setFollow] = useState(true);
@@ -45,7 +49,8 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
           {jobLabel(job)} ·{" "}
           
             {job.repoId}
-          
+          {" "}
+          
         
       }
       painting={{ view: 0.5, focus: [0.3, 0.55], anchor: [0.7, 0.45] }}
@@ -67,6 +72,8 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
       }
     >
 
+      {job.state === "pending_approval" &&  router.push("/")} />}
+
       
         
           
@@ -82,6 +89,12 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
             
Duration
{formatDuration(duration)}
+ {job.requestedBy && ( + <> +
Requested by
+
{job.requestedBy} (API token)
+ + )} {job.exitCode != null && ( <>
Exit code
diff --git a/src/app/(app)/library-view.tsx b/src/app/(app)/library-view.tsx index fa58e7f..dddd0a3 100644 --- a/src/app/(app)/library-view.tsx +++ b/src/app/(app)/library-view.tsx @@ -8,6 +8,7 @@ import { JobProgress, JobStateBadge } from "@/components/job-progress"; import { LocalTime } from "@/components/local-time"; import { HUB_STATE_LABEL, HubStateBadge } from "@/components/hub-state-badge"; import { MODEL_STATUS, ModelStatusBadge } from "@/components/model-status-badge"; +import { RequestedByBadge } from "@/components/requested-by-badge"; import { TagBadge, TagDot } from "@/components/tag-badge"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; @@ -27,13 +28,14 @@ import { type Filters, matchesFilters, matchesQuery, + PENDING_APPROVAL, queryTerms, type SearchableModel, searchText, } from "@/lib/search"; import { FacetFilter } from "./facet-filter"; -const OPEN = ["queued", "downloading", "verifying"]; +const OPEN = ["pending_approval", "queued", "downloading", "verifying"]; const PAGE_SIZES = [10, 25, 50, 100]; const FACET_LABEL: Record = { @@ -42,9 +44,10 @@ const FACET_LABEL: Record = { quant: "Quant", tag: "Tag", status: "Status", + requester: "Requested by", }; -const statusLabel = (v: string) => MODEL_STATUS[v as ModelStatus]?.label ?? v; +const statusLabel = (v: string) => (v === PENDING_APPROVAL ? "awaiting approval" : (MODEL_STATUS[v as ModelStatus]?.label ?? v)); function toSearchable(r: LibraryRow): SearchableModel { const m: SearchableModel = { @@ -65,6 +68,8 @@ function toSearchable(r: LibraryRow): SearchableModel { : r.updateAvailable ? "update available" : null, + requestedBy: r.requestedBy, + pendingApproval: r.pendingApproval, }; return { ...m, text: searchText(m) }; } @@ -208,6 +213,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
{base && base !== r.repoId && base {base}} {r.architecture && {r.architecture}} + {r.tags.map((t) => ( + + + + ); +} diff --git a/src/app/(app)/settings/api-tokens/page.tsx b/src/app/(app)/settings/api-tokens/page.tsx new file mode 100644 index 0000000..f97f783 --- /dev/null +++ b/src/app/(app)/settings/api-tokens/page.tsx @@ -0,0 +1,24 @@ +import type { Metadata } from "next"; +import { listActivity } from "@/lib/agent-activity"; +import { listTokens } from "@/lib/api-tokens"; +import { getGuardrails } from "@/lib/settings"; +import { GuardrailSettings } from "./guardrail-settings"; +import { TokenSettings } from "./token-settings"; + +export const dynamic = "force-dynamic"; +export const metadata: Metadata = { title: "API tokens · Settings" }; + +export default async function ApiTokenSettingsPage() { + const [tokens, guardrails] = await Promise.all([listTokens(), getGuardrails()]); + const activity = Object.fromEntries( + await Promise.all( + tokens.map(async (t) => [t.id, (await listActivity(t.id, 50)).map((a) => ({ ...a, createdAt: a.createdAt.toISOString() }))] as const), + ), + ); + return ( +
+ + +
+ ); +} diff --git a/src/app/(app)/settings/api-tokens/token-settings.tsx b/src/app/(app)/settings/api-tokens/token-settings.tsx new file mode 100644 index 0000000..70476e5 --- /dev/null +++ b/src/app/(app)/settings/api-tokens/token-settings.tsx @@ -0,0 +1,389 @@ +"use client"; + +import { BotIcon, PlusIcon, Trash2Icon } from "lucide-react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { toast } from "sonner"; +import { CopyButton } from "@/components/copy-button"; +import { LocalTime } from "@/components/local-time"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, + AlertDialogTrigger, +} from "@/components/ui/alert-dialog"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Input } from "@/components/ui/input"; +import { SCOPE_LABEL } from "@/lib/token-scopes"; +import type { ApiTokenRow } from "@/lib/api-tokens"; +import { TOKEN_SCOPES, type TokenScope } from "@/lib/db/enums"; + +/** Bearer tokens for /api/v1 (e.g. an AI agent). The token is shown once, then only its prefix. */ +export function TokenSettings({ + tokens, + activity, +}: { + tokens: ApiTokenRow[]; + activity: Record; +}) { + const [created, setCreated] = useState<{ + name: string; + token: string; + } | null>(null); + return ( + + + API tokens + + For programs and agents calling Kaname's API at{" "} + /api/v1 with{" "} + + Authorization: Bearer <token> + + . No token can delete models or files, change settings, or manage + tokens. The guide for agents is in{" "} + docs/agent/SKILL.md. + + + + + {created && ( +
+

+ Token “{created.name}” created. Copy it now: it is not + shown again. +

+
+ + {created.token} + + +
+
+ )} + {tokens.length === 0 ? ( +

No tokens yet.

+ ) : ( +
+ {tokens.map((t) => ( + + ))} +
+ )} +
+
+ ); +} + +function NewTokenForm({ + onCreated, +}: { + onCreated: (t: { name: string; token: string }) => void; +}) { + const router = useRouter(); + const [name, setName] = useState(""); + const [scopes, setScopes] = useState(["models:read"]); + const [busy, setBusy] = useState(false); + + async function create(e: React.FormEvent) { + e.preventDefault(); + setBusy(true); + try { + const res = await fetch("/api/api-tokens", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ name, scopes }), + }); + const json = await res.json().catch(() => ({})); + if (!res.ok) + return toast.error( + json.error?.message ?? `Could not create the token (${res.status})`, + ); + onCreated({ name: name.trim().toLowerCase(), token: json.token }); + setName(""); + router.refresh(); + } finally { + setBusy(false); + } + } + + return ( +
+
+ + setName(e.target.value.toLowerCase().replace(/[^a-z0-9._-]/g, "")) + } + placeholder="Name, e.g. hermes" + aria-label="Token name" + className="max-w-56" + /> + +
+
+ {TOKEN_SCOPES.map((s) => ( + + ))} +
+

+ The name is shown as “requested by” on everything the token + asks for. +

+
+ ); +} + +function TokenRow({ + token, + activity, +}: { + token: ApiTokenRow; + activity: ActivityItem[]; +}) { + const router = useRouter(); + const revoked = !!token.revokedAt; + const [editing, setEditing] = useState(false); + const [scopes, setScopes] = useState(token.scopes); + const [showActivity, setShowActivity] = useState(false); + + async function saveScopes() { + const res = await fetch(`/api/api-tokens/${token.id}`, { + method: "PATCH", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ scopes }), + }); + const json = await res.json().catch(() => ({})); + if (!res.ok) + return void toast.error(json.error?.message ?? `Failed (${res.status})`); + toast.success(`Scopes of "${token.name}" changed`); + setEditing(false); + router.refresh(); + } + + async function act(method: "POST" | "DELETE") { + const res = await fetch(`/api/api-tokens/${token.id}`, { method }); + const json = await res.json().catch(() => ({})); + if (!res.ok) toast.error(json.error?.message ?? `Failed (${res.status})`); + else + toast.success( + method === "POST" + ? `Token "${token.name}" revoked` + : `Token "${token.name}" deleted`, + ); + router.refresh(); + } + + return ( +
+
+ + {token.name} + + {token.prefix}… + + + {token.scopes.map((s) => ( + + {s} + + ))} + + {revoked && revoked} + + {token.lastUsedAt ? ( + <> + used + + ) : ( + "never used" + )} + + {activity.length > 0 && ( + + )} + {!revoked && ( + + )} + + }> + {revoked ? : "Revoke"} + + + + + {revoked ? "Delete" : "Revoke"} token “{token.name} + ”? + + + {revoked + ? "The entry goes away and the name can be used again. Models it requested keep their “requested by” label." + : "It stops working immediately. Downloads it already requested are not affected."} + + + + Cancel + act(revoked ? "DELETE" : "POST")} + > + {revoked ? "Delete" : "Revoke"} + + + + +
+ {editing && ( +
+ {TOKEN_SCOPES.map((s) => ( + + ))} + +
+ )} + {showActivity && } +
+ ); +} + +export type ActivityItem = { + id: string; + action: string; + targetType: string | null; + targetId: string | null; + outcome: string; + code: string | null; + message: string | null; + createdAt: string; +}; + +const TARGET_HREF: Record string> = { + model: (id) => `/models/${id}`, + job: (id) => `/jobs/${id}`, +}; + +/** What the token did, newest first: outcome, and the reason when a guardrail refused it. */ +function ActivityList({ items }: { items: ActivityItem[] }) { + return ( +
    + {items.map((a) => ( +
  • + + + + {a.action} + + {a.outcome === "refused" + ? `refused: ${a.code}` + : a.outcome === "pending_approval" + ? "awaiting approval" + : "ok"} + + {a.targetType && a.targetId && TARGET_HREF[a.targetType] && ( + + {a.targetType} + + )} + {a.message && ( + {a.message} + )} +
  • + ))} +
+ ); +} diff --git a/src/app/(app)/settings/layout.tsx b/src/app/(app)/settings/layout.tsx index eef417c..1f0aa84 100644 --- a/src/app/(app)/settings/layout.tsx +++ b/src/app/(app)/settings/layout.tsx @@ -1,4 +1,4 @@ -import { DownloadIcon, PaletteIcon, TagIcon, TagsIcon } from "lucide-react"; +import { BotIcon, DownloadIcon, PaletteIcon, TagIcon, TagsIcon } from "lucide-react"; import { PageHero } from "@/components/hero/page-hero"; import { SettingsNav } from "./settings-nav"; @@ -7,13 +7,14 @@ const SECTIONS = [ { href: "/settings/tags", label: "Tags", icon: }, { href: "/settings/downloads", label: "Downloads", icon: }, { href: "/settings/appearance", label: "Appearance", icon: }, + { href: "/settings/api-tokens", label: "API tokens", icon: }, ]; export default function SettingsLayout({ children }: LayoutProps<"/settings">) { return (
diff --git a/src/app/api/api-tokens/[id]/route.ts b/src/app/api/api-tokens/[id]/route.ts new file mode 100644 index 0000000..e19d4eb --- /dev/null +++ b/src/app/api/api-tokens/[id]/route.ts @@ -0,0 +1,40 @@ +import { NextResponse } from "next/server"; +import { z } from "zod"; +import { withAuth } from "@/lib/api-auth"; +import { apiError } from "@/lib/api-errors"; +import { deleteToken, revokeToken, TokenError, updateTokenScopes } from "@/lib/api-tokens"; + +/** Revoke a token: it stops working immediately. */ +export const POST = withAuth>(async (_req, { params }) => { + try { + await revokeToken((await params).id); + return NextResponse.json({ ok: true }); + } catch (err) { + if (err instanceof TokenError) return apiError(err.status, err.code, err.message); + throw err; + } +}); + +/** Change an active token's scopes. */ +export const PATCH = withAuth>(async (req, { params }) => { + try { + const { scopes } = z.object({ scopes: z.array(z.string()).max(20) }).parse(await req.json()); + await updateTokenScopes((await params).id, scopes); + return NextResponse.json({ ok: true }); + } catch (err) { + if (err instanceof TokenError) return apiError(err.status, err.code, err.message); + if (err instanceof z.ZodError) return apiError(400, "invalid_request", "scopes must be a list of scope names."); + throw err; + } +}); + +/** Delete a revoked token (frees its name). */ +export const DELETE = withAuth>(async (_req, { params }) => { + try { + await deleteToken((await params).id); + return new NextResponse(null, { status: 204 }); + } catch (err) { + if (err instanceof TokenError) return apiError(err.status, err.code, err.message); + throw err; + } +}); diff --git a/src/app/api/api-tokens/route.ts b/src/app/api/api-tokens/route.ts new file mode 100644 index 0000000..c055324 --- /dev/null +++ b/src/app/api/api-tokens/route.ts @@ -0,0 +1,23 @@ +import { NextResponse } from "next/server"; +import { z } from "zod"; +import { withAuth } from "@/lib/api-auth"; +import { apiError, handleApiError } from "@/lib/api-errors"; +import { createToken, listTokens, TokenError } from "@/lib/api-tokens"; + +export const dynamic = "force-dynamic"; + +/** API tokens for machine clients (Settings → API tokens). Never includes the tokens themselves. */ +export const GET = withAuth(async () => NextResponse.json(await listTokens())); + +const Body = z.object({ name: z.string().max(40), scopes: z.array(z.string()).min(1).max(10) }); + +/** Create a token. The response is the only time the token is shown. */ +export const POST = withAuth(async (req) => { + try { + const body = Body.parse(await req.json()); + return NextResponse.json(await createToken(body.name, body.scopes), { status: 201, headers: { "Cache-Control": "no-store" } }); + } catch (err) { + if (err instanceof TokenError) return apiError(err.status, err.code, err.message); + return handleApiError(err); + } +}); diff --git a/src/app/api/jobs/[id]/approve/route.ts b/src/app/api/jobs/[id]/approve/route.ts new file mode 100644 index 0000000..89b8e56 --- /dev/null +++ b/src/app/api/jobs/[id]/approve/route.ts @@ -0,0 +1,17 @@ +import { NextResponse } from "next/server"; +import { approveJob } from "@/lib/agent-downloads"; +import { withAuth } from "@/lib/api-auth"; +import { apiError } from "@/lib/api-errors"; +import { JobError } from "@/lib/jobs"; + +/** Let a download requested through the API start. */ +export const POST = withAuth>(async (_req, { params }) => { + const { id } = await params; + try { + await approveJob(id); + return NextResponse.json({ ok: true }); + } catch (err) { + if (err instanceof JobError) return apiError(err.status, err.code, err.message); + throw err; + } +}); diff --git a/src/app/api/jobs/[id]/reject/route.ts b/src/app/api/jobs/[id]/reject/route.ts new file mode 100644 index 0000000..dae3c8f --- /dev/null +++ b/src/app/api/jobs/[id]/reject/route.ts @@ -0,0 +1,16 @@ +import { NextResponse } from "next/server"; +import { rejectJob } from "@/lib/agent-downloads"; +import { withAuth } from "@/lib/api-auth"; +import { apiError } from "@/lib/api-errors"; +import { JobError } from "@/lib/jobs"; + +/** Turn down a download requested through the API (a model only it added leaves the library). */ +export const POST = withAuth>(async (_req, { params }) => { + const { id } = await params; + try { + return NextResponse.json(await rejectJob(id)); + } catch (err) { + if (err instanceof JobError) return apiError(err.status, err.code, err.message); + throw err; + } +}); diff --git a/src/app/api/settings/agent/route.ts b/src/app/api/settings/agent/route.ts new file mode 100644 index 0000000..eb57a25 --- /dev/null +++ b/src/app/api/settings/agent/route.ts @@ -0,0 +1,30 @@ +import { NextResponse } from "next/server"; +import { z } from "zod"; +import { APPROVAL_MODES } from "@/lib/agent-guardrails"; +import { withAuth } from "@/lib/api-auth"; +import { apiError, handleApiError } from "@/lib/api-errors"; +import { getGuardrails, saveGuardrails, SettingsError } from "@/lib/settings"; + +export const dynamic = "force-dynamic"; + +/** Guardrails for downloads requested through the API. */ +export const GET = withAuth(async () => NextResponse.json(await getGuardrails())); + +const Body = z + .object({ + approvalMode: z.enum(APPROVAL_MODES), + maxRequestBytes: z.number(), + minFreeBytes: z.number(), + maxOpenJobs: z.number().int(), + allowedAuthors: z.array(z.string()).max(100), + }) + .partial(); + +export const PUT = withAuth(async (req) => { + try { + return NextResponse.json(await saveGuardrails(Body.parse(await req.json()))); + } catch (err) { + if (err instanceof SettingsError) return apiError(err.status, err.code, err.message); + return handleApiError(err); + } +}); diff --git a/src/app/api/v1/disk/route.ts b/src/app/api/v1/disk/route.ts new file mode 100644 index 0000000..bb3a9e2 --- /dev/null +++ b/src/app/api/v1/disk/route.ts @@ -0,0 +1,34 @@ +import { reservedBytes } from "@/lib/agent-downloads"; +import { withToken } from "@/lib/api-tokens"; +import { size, v1Catch, v1Json } from "@/lib/api-v1"; +import { getGuardrails } from "@/lib/settings"; +import { getWorkerStatus } from "@/lib/worker-status"; + +export const dynamic = "force-dynamic"; + +/** + * Space on the models folder (reported by the worker every few seconds), what open downloads + * still need, and how much an agent request may use before hitting the minimum-free guardrail. + */ +export const GET = withToken("models:read", async () => { + try { + const [w, reserved, g] = await Promise.all([getWorkerStatus(), reservedBytes(), getGuardrails()]); + const free = w.online ? w.modelsDirFreeBytes : null; + const total = w.online ? w.modelsDirTotalBytes : null; + const available = free == null ? null : Math.max(0, free - reserved - g.minFreeBytes); + return v1Json({ + workerOnline: w.online, + freeBytes: free, + totalBytes: total, + usedBytes: free != null && total != null ? total - free : null, + reservedBytes: reserved, + minFreeBytes: g.minFreeBytes, + availableForRequestsBytes: available, + free: size(free), + total: size(total), + availableForRequests: size(available), + }); + } catch (err) { + return v1Catch(err); + } +}); diff --git a/src/app/api/v1/downloads/route.ts b/src/app/api/v1/downloads/route.ts new file mode 100644 index 0000000..69751b8 --- /dev/null +++ b/src/app/api/v1/downloads/route.ts @@ -0,0 +1,49 @@ +import { z } from "zod"; +import { act } from "@/lib/agent-activity"; +import { requestDownload } from "@/lib/agent-downloads"; +import { withToken } from "@/lib/api-tokens"; +import { size, v1Catch, v1Json } from "@/lib/api-v1"; +import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client"; + +export const dynamic = "force-dynamic"; + +const Body = z + .object({ + repoId: z.string().trim().regex(REPO_ID_RE, 'must be "org/name"'), + sha: z.string().trim().regex(SHA_RE, "must be the full 40-character commit SHA from GET /api/v1/hub/lookup"), + revision: z.string().trim().min(1).max(255).optional(), + quant: z.string().trim().min(1).max(64).optional(), + include: z.array(z.string().trim().min(1).max(1024)).min(1).max(100).optional(), + tags: z.array(z.string()).max(20).optional(), + }) + .strict() + .refine((b) => !!b.quant !== !!b.include, { message: 'pass exactly one of "quant" (e.g. "Q4_K_M") or "include" (globs)' }); + +/** + * Request a download, within the guardrails. 201: queued or waiting for approval; 200: the same + * repo + commit + files was requested before, nothing new was queued. + */ +export const POST = withToken("downloads:create", async (req, { token }) => { + try { + const body = Body.parse(await req.json()); + const r = await act(token, "download.request", { type: "model" }, async () => { + const out = await requestDownload(token, body); + return { ...out, id: out.modelId }; + }); + return v1Json( + { + created: r.created, + modelId: r.modelId, + jobId: r.jobId, + state: r.state, + requestedBytes: r.requestedBytes, + requestedSize: size(r.requestedBytes), + files: r.files, + message: r.message.replace("{jobId}", r.jobId ?? "{jobId}"), + }, + r.created ? 201 : 200, + ); + } catch (err) { + return v1Catch(err); + } +}); diff --git a/src/app/api/v1/hub/lookup/route.ts b/src/app/api/v1/hub/lookup/route.ts new file mode 100644 index 0000000..c3246ab --- /dev/null +++ b/src/app/api/v1/hub/lookup/route.ts @@ -0,0 +1,47 @@ +import { eq } from "drizzle-orm"; +import { quantSummary } from "@/lib/agent-selection"; +import { withToken } from "@/lib/api-tokens"; +import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1"; +import { db } from "@/lib/db/client"; +import { models } from "@/lib/db/schema"; +import { lookupRepo, normalizeRepoInput } from "@/lib/hub/lookup"; + +export const dynamic = "force-dynamic"; + +/** Files listed inline up to this count; more with ?files=all. */ +const FILE_LIMIT = 200; + +/** + * Resolve a Hub repo (+ revision, default main) to its commit SHA, with the quants and files and + * their sizes: what a download request needs. The same lookup the Add model dialog uses. + */ +export const GET = withToken("models:read", async (req) => { + try { + const url = new URL(req.url); + const repo = url.searchParams.get("repo")?.trim(); + if (!repo) return v1Error(400, "invalid_request", 'Pass the repo as ?repo=org/name, e.g. ?repo=unsloth/Qwen3-8B-GGUF.'); + const { repoId, revision: urlRevision } = normalizeRepoInput(repo); + const revision = url.searchParams.get("revision")?.trim() || urlRevision || "main"; + const r = await lookupRepo(repoId, revision); + const all = url.searchParams.get("files") === "all"; + const model = r.existingModelId + ? await db().query.models.findFirst({ columns: { id: true, pinnedSha: true, status: true }, where: eq(models.id, r.existingModelId) }) + : null; + return v1Json({ + repoId: r.repoId, + revision: r.revision, + sha: r.sha, + gated: r.gated, + lastModified: r.lastModified, + inLibrary: model ? { modelId: model.id, pinnedSha: model.pinnedSha, status: model.status } : null, + quants: quantSummary(r.files).map((q) => ({ ...q, size: size(q.bytes) })), + fileCount: r.files.length, + totalBytes: r.files.reduce((s, f) => s + f.size, 0), + files: (all ? r.files : r.files.slice(0, FILE_LIMIT)).map((f) => ({ path: f.path, bytes: f.size })), + filesTruncated: !all && r.files.length > FILE_LIMIT, + next: 'POST /api/v1/downloads with {"repoId", "sha", "quant"} (or "include": [globs]).', + }); + } catch (err) { + return v1Catch(err); + } +}); diff --git a/src/app/api/v1/jobs/[id]/cancel/route.ts b/src/app/api/v1/jobs/[id]/cancel/route.ts new file mode 100644 index 0000000..c013726 --- /dev/null +++ b/src/app/api/v1/jobs/[id]/cancel/route.ts @@ -0,0 +1,17 @@ +import { act } from "@/lib/agent-activity"; +import { cancelOwnJob } from "@/lib/agent-downloads"; +import { withToken } from "@/lib/api-tokens"; +import { v1Catch, v1Json } from "@/lib/api-v1"; + +export const dynamic = "force-dynamic"; + +/** Cancel a job this token requested (a pending request is withdrawn). Other jobs are the user's. */ +export const POST = withToken>(["downloads:create", "models:verify"], async (_req, { params, token }) => { + try { + const { id } = await params; + const r = await act(token, "job.cancel", { type: "job", id }, () => cancelOwnJob(token, id)); + return v1Json(r, 202); + } catch (err) { + return v1Catch(err); + } +}); diff --git a/src/app/api/v1/jobs/[id]/route.ts b/src/app/api/v1/jobs/[id]/route.ts new file mode 100644 index 0000000..50135eb --- /dev/null +++ b/src/app/api/v1/jobs/[id]/route.ts @@ -0,0 +1,83 @@ +import { withToken } from "@/lib/api-tokens"; +import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1"; +import { getJob, listJobFiles, listJobLogs } from "@/lib/jobs"; +import { parseWait, waitFor } from "@/lib/wait"; + +export const dynamic = "force-dynamic"; + +const MAX_LOG = 200; + +const NEXT: Record = { + pending_approval: "Waiting for the user to approve it. Don't retry or poll; tell the user and stop.", + queued: "Waiting for a free slot; GET with ?wait=900 instead of polling.", + downloading: "Downloading; GET with ?wait=900 instead of polling.", + verifying: "Checking the files; GET with ?wait=900 instead of polling.", + completed: "Done.", + failed: "Failed; see error. Tell the user; retrying the same request returns this job.", + cancelled: "Cancelled or rejected. Don't request it again unless the user asks.", + interrupted: "Interrupted by a Kaname restart; the user can resume it.", +}; + +const SETTLED = new Set(["pending_approval", "completed", "failed", "cancelled", "interrupted"]); + +/** What a finished verify found, and what to do about it. */ +function verifyResult(job: NonNullable>>) { + if ((job.kind !== "verify" && job.kind !== "deep_verify") || job.state !== "completed" || !job.result) return undefined; + const r = job.result; + const problems = (r.missing?.length ?? 0) + (r.sizeMismatch?.length ?? 0) + (r.hashMismatch?.length ?? 0); + return { + checked: r.checked ?? null, + missing: r.missing ?? [], + sizeMismatch: r.sizeMismatch ?? [], + hashMismatch: r.hashMismatch ?? [], + ok: problems === 0, + next: problems === 0 ? "All files are fine." : `POST /api/v1/models/${job.modelId}/repair downloads the ${problems} broken file(s) again.`, + }; +} + +/** + * Job state with per-file progress. ?wait= (max 900) blocks until it is finished or waits for + * approval. The hf log only with ?log=N (last N lines, max 200). + */ +export const GET = withToken>("models:read", async (req, { params }) => { + try { + const id = (await params).id; + const q = new URL(req.url).searchParams; + const { value: job, waitedS, timedOut } = await waitFor(() => getJob(id), (j) => !j || SETTLED.has(j.state), parseWait(q), { signal: req.signal }); + if (!job) return v1Error(404, "not_found", "No job with this id."); + const n = Math.min(MAX_LOG, Math.max(0, Number(q.get("log")) || 0)); + const files = await listJobFiles(id); + const log = n > 0 ? (await listJobLogs(id, 0, n)).map((l) => `${new Date(l.ts).toISOString()} [${l.stream}] ${l.line}`) : undefined; + const verify = verifyResult(job); + return v1Json({ + id: job.id, + modelId: job.modelId, + repoId: job.repoId, + kind: job.kind, + purpose: job.purpose, + state: job.state, + cancelRequested: job.cancelRequested, + requestedBy: job.requestedBy, + progress: { + doneBytes: job.doneBytes, + totalBytes: job.totalBytes, + percent: job.totalBytes > 0 ? Math.round((job.doneBytes / job.totalBytes) * 1000) / 10 : 0, + done: size(job.doneBytes), + total: size(job.totalBytes), + speedBytesPerSecond: job.speedBps, + etaSeconds: job.etaSeconds, + }, + error: job.errorCode || job.errorMessage ? { code: job.errorCode, message: job.errorMessage } : null, + ...(verify ? { verify } : {}), + files: files.map((f) => ({ path: f.path, state: f.state, doneBytes: f.doneBytes, totalBytes: f.expectedBytes })), + createdAt: new Date(job.createdAt).toISOString(), + startedAt: job.startedAt ? new Date(job.startedAt).toISOString() : null, + finishedAt: job.finishedAt ? new Date(job.finishedAt).toISOString() : null, + next: verify?.next ?? NEXT[job.state] ?? null, + ...(waitedS ? { waitedSeconds: waitedS, timedOut } : {}), + ...(log ? { log } : {}), + }); + } catch (err) { + return v1Catch(err); + } +}); diff --git a/src/app/api/v1/models/[id]/repair/route.ts b/src/app/api/v1/models/[id]/repair/route.ts new file mode 100644 index 0000000..5c0e034 --- /dev/null +++ b/src/app/api/v1/models/[id]/repair/route.ts @@ -0,0 +1,20 @@ +import { act } from "@/lib/agent-activity"; +import { requestRepair } from "@/lib/agent-downloads"; +import { withToken } from "@/lib/api-tokens"; +import { size, v1Catch, v1Json } from "@/lib/api-v1"; + +export const dynamic = "force-dynamic"; + +/** + * Download again the selected files that are missing or broken, within the guardrails (and, by + * default, after the user approves it). Run verify first to find out what's broken. + */ +export const POST = withToken>("downloads:create", async (_req, { params, token }) => { + try { + const { id } = await params; + const r = await act(token, "model.repair", { type: "model", id }, () => requestRepair(token, id)); + return v1Json({ ...r, requestedSize: size(r.requestedBytes), message: r.message.replace("{jobId}", r.jobId) }, 201); + } catch (err) { + return v1Catch(err); + } +}); diff --git a/src/app/api/v1/models/[id]/route.ts b/src/app/api/v1/models/[id]/route.ts new file mode 100644 index 0000000..0015380 --- /dev/null +++ b/src/app/api/v1/models/[id]/route.ts @@ -0,0 +1,40 @@ +import { withToken } from "@/lib/api-tokens"; +import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1"; +import { listModelJobs } from "@/lib/jobs"; +import { getModel } from "@/lib/library"; +import { modelTagList } from "@/lib/tags"; + +export const dynamic = "force-dynamic"; + +/** One model: status, pinned commit, selected files with their state, tags and its latest job. */ +export const GET = withToken>("models:read", async (_req, { params }) => { + try { + const data = await getModel((await params).id); + if (!data) return v1Error(404, "not_found", "No model with this id. List models with GET /api/v1/models."); + const { model, files } = data; + const selected = files.filter((f) => f.selected); + const onDisk = selected.filter((f) => f.state === "present" || f.state === "verified").reduce((s, f) => s + f.size, 0); + const [[job], tags] = await Promise.all([listModelJobs(model.id, 1), modelTagList(model.id)]); + return v1Json({ + id: model.id, + repoId: model.repoId, + source: model.source, + status: model.status, + trackedRevision: model.source === "local" ? null : model.trackedRevision, + pinnedSha: model.source === "local" ? null : model.pinnedSha, + hubState: model.hubState, + localPath: model.localPath, + requestedBy: model.requestedBy, + tags: tags.map((t) => t.name), + onDiskBytes: onDisk, + onDisk: size(onDisk), + files: selected.map((f) => ({ path: f.path, bytes: f.size, state: f.state })), + latestJob: job ? { id: job.id, kind: job.kind, purpose: job.purpose, state: job.state, requestedBy: job.requestedBy } : null, + lastVerifiedAt: model.lastVerifiedAt?.toISOString() ?? null, + createdAt: model.createdAt.toISOString(), + downloadedAt: model.downloadedAt?.toISOString() ?? null, + }); + } catch (err) { + return v1Catch(err); + } +}); diff --git a/src/app/api/v1/models/[id]/tags/[name]/route.ts b/src/app/api/v1/models/[id]/tags/[name]/route.ts new file mode 100644 index 0000000..375f874 --- /dev/null +++ b/src/app/api/v1/models/[id]/tags/[name]/route.ts @@ -0,0 +1,25 @@ +import { act } from "@/lib/agent-activity"; +import { withToken } from "@/lib/api-tokens"; +import { v1Catch, v1Error, v1Json } from "@/lib/api-v1"; +import { getModel } from "@/lib/library"; +import { modelTagList, normalizeTagName, removeTag } from "@/lib/tags"; + +export const dynamic = "force-dynamic"; + +/** Detach a tag (by name, case-insensitive) from a model. The tag itself stays. */ +export const DELETE = withToken>("tags:write", async (_req, { params, token }) => { + try { + const { id, name } = await params; + if (!(await getModel(id))) return v1Error(404, "not_found", "No model with this id. List models with GET /api/v1/models."); + const { slug } = normalizeTagName(decodeURIComponent(name)); + const tag = (await modelTagList(id)).find((t) => t.name.toLowerCase() === slug); + if (!tag) return v1Error(404, "not_found", `This model has no tag "${decodeURIComponent(name)}".`); + await act(token, "tag.remove", { type: "model", id }, async () => { + await removeTag(id, tag.id); + return { id }; + }); + return v1Json({ modelId: id, removed: tag.name, tags: (await modelTagList(id)).map((t) => t.name) }); + } catch (err) { + return v1Catch(err); + } +}); diff --git a/src/app/api/v1/models/[id]/tags/route.ts b/src/app/api/v1/models/[id]/tags/route.ts new file mode 100644 index 0000000..ffc6574 --- /dev/null +++ b/src/app/api/v1/models/[id]/tags/route.ts @@ -0,0 +1,21 @@ +import { z } from "zod"; +import { act } from "@/lib/agent-activity"; +import { withToken } from "@/lib/api-tokens"; +import { v1Catch, v1Json } from "@/lib/api-v1"; +import { addTag, modelTagList } from "@/lib/tags"; + +export const dynamic = "force-dynamic"; + +const Body = z.object({ name: z.string() }).strict(); + +/** Attach a tag to a model; a tag that doesn't exist yet is created (names match case-insensitively). */ +export const POST = withToken>("tags:write", async (req, { params, token }) => { + try { + const { id } = await params; + const { name } = Body.parse(await req.json()); + const tag = await act(token, "tag.add", { type: "model", id }, () => addTag(id, name)); + return v1Json({ modelId: id, tag: tag.name, tags: (await modelTagList(id)).map((t) => t.name) }, 201); + } catch (err) { + return v1Catch(err); + } +}); diff --git a/src/app/api/v1/models/[id]/verify/route.ts b/src/app/api/v1/models/[id]/verify/route.ts new file mode 100644 index 0000000..1d85a61 --- /dev/null +++ b/src/app/api/v1/models/[id]/verify/route.ts @@ -0,0 +1,21 @@ +import { z } from "zod"; +import { act } from "@/lib/agent-activity"; +import { requestVerify } from "@/lib/agent-downloads"; +import { withToken } from "@/lib/api-tokens"; +import { optionalJson, v1Catch, v1Json } from "@/lib/api-v1"; + +export const dynamic = "force-dynamic"; + +const Body = z.object({ deep: z.boolean().optional() }).strict(); + +/** Check the model's selected files: presence and size, or with {"deep": true} their hashes. */ +export const POST = withToken>("models:verify", async (req, { params, token }) => { + try { + const { id } = await params; + const { deep = false } = Body.parse(await optionalJson(req)); + const r = await act(token, deep ? "model.deep_verify" : "model.verify", { type: "model", id }, () => requestVerify(token, id, deep)); + return v1Json(r, 201); + } catch (err) { + return v1Catch(err); + } +}); diff --git a/src/app/api/v1/models/route.ts b/src/app/api/v1/models/route.ts new file mode 100644 index 0000000..2ce5617 --- /dev/null +++ b/src/app/api/v1/models/route.ts @@ -0,0 +1,62 @@ +import { withToken } from "@/lib/api-tokens"; +import { parseModelFilters } from "@/lib/api-v1-filters"; +import { size, v1Catch, v1Json } from "@/lib/api-v1"; +import { listLibrary } from "@/lib/library"; +import { matchesFilters, matchesQuery, type SearchableModel } from "@/lib/search"; + +export const dynamic = "force-dynamic"; + +/** + * The local library, filtered like the library page: ?q= (all terms must match) and facets + * author, family, quant, tag, status, requested_by (repeat or comma-separate values). + * Status values: pending, downloading, ready, incomplete, failed, deleting, pending_approval, + * update_available, repo_missing, commit_missing. + */ +export const GET = withToken("models:read", async (req) => { + try { + const { query, filters } = parseModelFilters(new URL(req.url).searchParams); + const rows = await listLibrary(); + const out = rows + .filter((r) => { + const m: SearchableModel = { + repoId: r.repoId, + author: r.author, + families: r.families, + baseModels: r.baseModels, + architecture: r.architecture, + quants: r.quants, + tags: r.tags.map((t) => t.name), + hubTags: r.hubTags, + pipelineTag: r.pipelineTag, + license: r.license, + status: r.status, + hubStatus: r.hubState && r.hubState !== "available" ? r.hubState : r.updateAvailable ? "update_available" : null, + requestedBy: r.requestedBy, + pendingApproval: r.pendingApproval, + }; + return matchesQuery(m, query) && matchesFilters(m, filters); + }) + .map((r) => ({ + id: r.id, + repoId: r.repoId, + source: r.source, + status: r.status, + pendingApproval: r.pendingApproval, + pinnedSha: r.source === "local" ? null : r.pinnedSha, + quants: r.quants, + tags: r.tags.map((t) => t.name), + selectedFiles: r.fileCount, + selectedBytes: r.totalBytes, + onDiskBytes: r.presentBytes, + onDisk: size(r.presentBytes), + updateAvailable: r.updateAvailable, + hubState: r.hubState, + requestedBy: r.requestedBy, + createdAt: r.createdAt.toISOString(), + downloadedAt: r.downloadedAt?.toISOString() ?? null, + })); + return v1Json({ count: out.length, models: out }); + } catch (err) { + return v1Catch(err); + } +}); diff --git a/src/app/api/v1/route.ts b/src/app/api/v1/route.ts new file mode 100644 index 0000000..bbe9ee6 --- /dev/null +++ b/src/app/api/v1/route.ts @@ -0,0 +1,36 @@ +import { withToken } from "@/lib/api-tokens"; +import { size, v1Json } from "@/lib/api-v1"; +import { getGuardrails } from "@/lib/settings"; + +export const dynamic = "force-dynamic"; + +/** Who am I, what may I do, and within which limits. Any valid token. */ +export const GET = withToken(null, async (_req, { token }) => { + const g = await getGuardrails(); + return v1Json({ + token: { name: token.name, scopes: token.scopes }, + guardrails: { + approvalMode: g.approvalMode, + maxRequestBytes: g.maxRequestBytes, + maxRequestSize: size(g.maxRequestBytes), + minFreeBytes: g.minFreeBytes, + minFreeSize: size(g.minFreeBytes), + maxOpenAgentJobs: g.maxOpenJobs, + allowedAuthors: g.allowedAuthors, + }, + endpoints: [ + "GET /api/v1/hub/lookup?repo=org/name[&revision=main][&files=all] models:read", + "GET /api/v1/models[?q=&author=&family=&quant=&tag=&status=&requested_by=] models:read", + "GET /api/v1/models/{id} models:read", + "GET /api/v1/tags models:read", + "GET /api/v1/jobs/{id}[?wait=900][&log=50] models:read", + "GET /api/v1/disk models:read", + "POST /api/v1/downloads {repoId, sha, quant | include[], tags?, revision?} downloads:create", + "POST /api/v1/models/{id}/repair downloads:create", + "POST /api/v1/models/{id}/verify {deep?} models:verify", + "POST /api/v1/jobs/{id}/cancel (jobs of this token only) downloads:create | models:verify", + "POST /api/v1/models/{id}/tags {name} tags:write", + "DELETE /api/v1/models/{id}/tags/{name} tags:write", + ], + }); +}); diff --git a/src/app/api/v1/tags/route.ts b/src/app/api/v1/tags/route.ts new file mode 100644 index 0000000..36a9560 --- /dev/null +++ b/src/app/api/v1/tags/route.ts @@ -0,0 +1,15 @@ +import { withToken } from "@/lib/api-tokens"; +import { v1Catch, v1Json } from "@/lib/api-v1"; +import { listTags } from "@/lib/tags"; + +export const dynamic = "force-dynamic"; + +/** Every tag with how many models use it, so an agent reuses existing tags instead of inventing near-duplicates. */ +export const GET = withToken("models:read", async () => { + try { + const tags = await listTags(); + return v1Json({ count: tags.length, tags: tags.map((t) => ({ name: t.name, models: Number(t.count) })) }); + } catch (err) { + return v1Catch(err); + } +}); diff --git a/src/components/approval-bar.tsx b/src/components/approval-bar.tsx new file mode 100644 index 0000000..eea7bd2 --- /dev/null +++ b/src/components/approval-bar.tsx @@ -0,0 +1,62 @@ +"use client"; + +import { BotIcon, CheckIcon, XIcon } from "lucide-react"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { approveJob, rejectJob } from "@/components/job-actions"; +import { Button } from "@/components/ui/button"; +import { formatBytes } from "@/lib/format"; + +const WHAT: Record = { + add: " of additional files", + repair: " to repair missing or broken files", +}; + +/** A download requested through the API that waits for approval: who asked, how much, approve/reject. */ +export function ApprovalBar({ job, onRemoved }: { job: { id: string; requestedBy: string | null; totalBytes: number; purpose: string | null }; onRemoved?: () => void }) { + const router = useRouter(); + const [busy, setBusy] = useState(false); + + async function run(fn: () => Promise) { + setBusy(true); + try { + await fn(); + router.refresh(); + } finally { + setBusy(false); + } + } + + return ( +
+

+ + + {job.requestedBy ?? "An API token"} asks to download {job.purpose === "repair" ? "up to " : ""} + {formatBytes(job.totalBytes)} + {WHAT[job.purpose ?? ""] ?? ""}. It starts once you approve it. + +

+
+ + +
+
+ ); +} diff --git a/src/components/command-palette-dialog.tsx b/src/components/command-palette-dialog.tsx index ce9471e..ebaa613 100644 --- a/src/components/command-palette-dialog.tsx +++ b/src/components/command-palette-dialog.tsx @@ -2,6 +2,7 @@ import { Dialog } from "@base-ui/react/dialog"; import { + BotIcon, BoxIcon, CornerDownLeftIcon, DownloadIcon, @@ -99,6 +100,7 @@ export function CommandPaletteDialog({ open, setOpen }: { open: boolean; setOpen { id: "s:speed", group: "Settings", title: "Download speed limit", icon: DownloadIcon, hint: "Downloads", keywords: "bandwidth mb/s", run: go("/settings/downloads") }, { id: "s:recommended", group: "Settings", title: "Recommended files", icon: DownloadIcon, hint: "Downloads", keywords: "mmproj mtp template quant", run: go("/settings/downloads") }, { id: "s:scan", group: "Settings", title: "Models folder scan schedule", icon: ScanSearchIcon, hint: "Downloads", keywords: "daily weekly monthly nas", run: go("/settings/downloads#scan") }, + { id: "s:tokens", group: "Settings", title: "API tokens", icon: BotIcon, keywords: "agent api token guardrails approval bearer", run: go("/settings/api-tokens") }, { id: "s:backdrop", group: "Settings", title: "Background picture", icon: PaletteIcon, hint: "Appearance", keywords: "image upload dot matrix painting header wallpaper", run: go("/settings/appearance") }, ]; for (const m of index?.models ?? []) { diff --git a/src/components/job-actions.ts b/src/components/job-actions.ts index 871203c..6e0be11 100644 --- a/src/components/job-actions.ts +++ b/src/components/job-actions.ts @@ -35,3 +35,23 @@ export async function startUpdate(modelId: string): Promise { if (ok) toast.success("Update queued"); return ok; } + +/** Let a download requested through the API start. */ +export async function approveJob(jobId: string): Promise { + const ok = await post(`/api/jobs/${jobId}/approve`); + if (ok) toast.success("Approved; the download is queued"); + return ok; +} + +/** Returns whether the model left the library (it was only added by this request), or null on error. */ +export async function rejectJob(jobId: string): Promise<{ removedModel: boolean } | null> { + const res = await fetch(`/api/jobs/${jobId}/reject`, { method: "POST" }); + const body = await res.json().catch(() => ({})); + if (!res.ok) { + toast.error(body.error?.message ?? `Request failed (${res.status})`); + return null; + } + pokeLive(); + toast.info(body.removedModel ? "Rejected; the model was removed from the library" : "Rejected"); + return body; +} diff --git a/src/components/requested-by-badge.tsx b/src/components/requested-by-badge.tsx new file mode 100644 index 0000000..674bcf2 --- /dev/null +++ b/src/components/requested-by-badge.tsx @@ -0,0 +1,14 @@ +import { BotIcon } from "lucide-react"; +import { Badge } from "@/components/ui/badge"; +import { cn } from "@/lib/utils"; + +/** "requested by hermes": added or downloaded through the API with that token. */ +export function RequestedByBadge({ name, className }: { name: string | null | undefined; className?: string }) { + if (!name) return null; + return ( + + + {name} + + ); +} diff --git a/src/components/user-menu.tsx b/src/components/user-menu.tsx index 977b074..04a5215 100644 --- a/src/components/user-menu.tsx +++ b/src/components/user-menu.tsx @@ -1,6 +1,6 @@ "use client"; -import { DownloadIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react"; +import { BotIcon, DownloadIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react"; import Link from "next/link"; import { useTheme } from "next-themes"; import { useTransition } from "react"; @@ -71,6 +71,10 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio Downloads + }> + + API tokens + diff --git a/src/lib/agent-activity.ts b/src/lib/agent-activity.ts new file mode 100644 index 0000000..5c6655e --- /dev/null +++ b/src/lib/agent-activity.ts @@ -0,0 +1,66 @@ +import "server-only"; +import { desc, eq } from "drizzle-orm"; +import type { TokenIdentity } from "@/lib/api-tokens"; +import { db } from "@/lib/db/client"; +import { agentActivity } from "@/lib/db/schema"; + +export type ActivityOutcome = "ok" | "pending_approval" | "refused"; + +/** Record what a token did (or was refused); never fails the request it belongs to. */ +export async function logActivity( + token: TokenIdentity, + action: string, + x: { targetType?: string; targetId?: string | null; outcome: ActivityOutcome; code?: string | null; message?: string | null }, +): Promise { + try { + await db() + .insert(agentActivity) + .values({ + tokenId: token.id, + tokenName: token.name, + action, + targetType: x.targetType ?? null, + targetId: x.targetId ?? null, + outcome: x.outcome, + code: x.code ?? null, + message: x.message?.slice(0, 500) ?? null, + }); + } catch (err) { + console.error("[agent-activity]", err); + } +} + +export type ActivityRow = typeof agentActivity.$inferSelect; + +export async function listActivity(tokenId: string, limit = 100): Promise { + return db().select().from(agentActivity).where(eq(agentActivity.tokenId, tokenId)).orderBy(desc(agentActivity.createdAt)).limit(limit); +} + +/** An error with a code and an HTTP status below 500: a refusal the agent caused, worth logging. */ +function refusal(err: unknown): { code: string; message: string } | null { + const e = err as { code?: unknown; status?: unknown; message?: unknown }; + if (typeof e?.code === "string" && typeof e.status === "number" && e.status < 500) return { code: e.code, message: String(e.message ?? "") }; + if (err instanceof Error && err.name === "ZodError") return { code: "invalid_request", message: err.message.slice(0, 300) }; + return null; +} + +/** + * Run an agent action and record it: ok, pending approval (when the result's state says so) or + * refused with the error code. The error is rethrown for the route to answer. + */ +export async function act(token: TokenIdentity, action: string, target: { type: string; id?: string | null }, fn: () => Promise): Promise { + try { + const r = await fn(); + const { id, state } = r as { id?: unknown; state?: unknown }; + await logActivity(token, action, { + targetType: target.type, + targetId: target.id ?? (typeof id === "string" ? id : null), + outcome: state === "pending_approval" ? "pending_approval" : "ok", + }); + return r; + } catch (err) { + const why = refusal(err); + if (why) await logActivity(token, action, { targetType: target.type, targetId: target.id ?? null, outcome: "refused", code: why.code, message: why.message }); + throw err; + } +} diff --git a/src/lib/agent-downloads.ts b/src/lib/agent-downloads.ts new file mode 100644 index 0000000..0ffb903 --- /dev/null +++ b/src/lib/agent-downloads.ts @@ -0,0 +1,267 @@ +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, queueVerify, requestCancel } 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"; + +// What an API token can make Kaname do: request downloads and repairs (within the guardrails, and +// by default only after approval in the UI), verify models, cancel its own jobs. Uses the same +// add-model and queue code as the UI. + +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 { + const [r] = await db() + .select({ n: sql`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 downloads that are pending approval, queued or running (all tokens). */ +export async function openAgentJobs(): Promise { + const [r] = await db() + .select({ n: sql`count(*)` }) + .from(jobs) + .where(and(isNotNull(jobs.requestedByTokenId), eq(jobs.kind, "download"), inArray(jobs.state, [...OPEN_STATES]))); + return Number(r.n); +} + +export 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 or poll; tell the user and stop.`; + } + if (state === "queued" || state === "downloading" || state === "verifying") return `${created ? "Queued" : "Already queued"}; GET /api/v1/jobs/{jobId}?wait=900 until it is done.`; + if (state === "completed" || state === "ready") return "Already downloaded."; + return `The last download ended as "${state}"; POST /api/v1/models/{modelId}/repair to fetch what's missing, or ask the user.`; +} + +/** 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) }); +} + +async function checkSpace(g: Guardrails, repoId: string, requestBytes: number, opts: { author?: boolean } = {}) { + const worker = await getWorkerStatus(); + checkGuardrails( + g, + { + repoId, + requestBytes, + freeBytes: worker.online ? worker.modelsDirFreeBytes : null, + reservedBytes: await reservedBytes(), + openAgentJobs: await openAgentJobs(), + }, + opts, + ); +} + +/** + * 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 { + 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?.source === "local") { + throw new ModelError("local_model", `${existing.repoId} is a local model (a folder without a Hub repo); Kaname doesn't download into it.`, 409); + } + 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 job 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); + await checkSpace(g, hub.repoId, requestBytes); + + 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 findModel(modelId: string) { + const model = await db().query.models.findFirst({ where: eq(models.id, modelId) }); + if (!model) throw new ModelError("not_found", "No model with this id. List models with GET /api/v1/models.", 404); + return model; +} + +/** + * Download again what's missing or broken (after a verify found problems, or a download that + * failed). Same guardrails as a download, apart from the author allowlist: the model is already in + * the library. Waits for approval like a download. + */ +export async function requestRepair( + token: TokenIdentity, + modelId: string, + guardrails?: Guardrails, +): Promise<{ modelId: string; jobId: string; state: string; requestedBytes: number; files: string[]; message: string }> { + const g = guardrails ?? (await getGuardrails()); + const model = await findModel(modelId); + if (model.source === "local") throw new JobError("local_model", "This is a local model without a Hugging Face repo: there's nothing to download.", 409); + const selected = await db() + .select({ path: modelFiles.path, size: modelFiles.size, state: modelFiles.state }) + .from(modelFiles) + .where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true))); + const broken = selected.filter((f) => f.state !== "present" && f.state !== "verified"); + if (broken.length === 0) { + throw new ModelError( + "nothing_to_repair", + "Every selected file is present. If you suspect damage, POST /api/v1/models/{id}/verify with {\"deep\": true} first; repair only what it reports.".replace("{id}", modelId), + 409, + ); + } + const requestBytes = broken.reduce((s, f) => s + f.size, 0); + await checkSpace(g, model.repoId, requestBytes, { author: false }); + const pendingApproval = g.approvalMode === "approve"; + const { jobId } = await queueDownload(modelId, "repair", { pendingApproval, requestedBy: { tokenId: token.id, name: token.name } }); + const state = pendingApproval ? "pending_approval" : "queued"; + return { modelId, jobId, state, requestedBytes: requestBytes, files: broken.map((f) => f.path).sort(), message: stateMessage(state, true) }; +} + +/** Verify (size + hf metadata) or deep verify (hashes); reads files only, so no approval. */ +export async function requestVerify(token: TokenIdentity, modelId: string, deep: boolean): Promise<{ modelId: string; jobId: string; state: string; message: string }> { + await findModel(modelId); + const { jobId } = await queueVerify(modelId, deep, { requestedBy: { tokenId: token.id, name: token.name } }); + return { + modelId, + jobId, + state: "queued", + message: `Queued; GET /api/v1/jobs/${jobId}?wait=900 until it is done. The result lists missing and broken files; repair them with POST /api/v1/models/${modelId}/repair.`, + }; +} + +/** + * Cancel a job this token requested: a download or repair waiting for approval is withdrawn (like + * a rejection), anything queued or running is stopped by the worker. + */ +export async function cancelOwnJob(token: TokenIdentity, jobId: string): Promise<{ jobId: string; state: string; removedModel: boolean; message: string }> { + const job = await db().query.jobs.findFirst({ where: eq(jobs.id, jobId) }); + if (!job) throw new JobError("not_found", "No job with this id.", 404); + if (job.requestedByTokenId !== token.id) { + throw new JobError("not_own_job", "This job wasn't requested with your token; only the user can cancel it in Kaname.", 403); + } + const scope = job.kind === "download" ? "downloads:create" : "models:verify"; + if (!token.scopes.includes(scope)) throw new JobError("not_own_job", `Cancelling a ${job.kind} job needs the scope "${scope}".`, 403); + if (job.state === "pending_approval") { + const { removedModel } = await rejectJob(jobId, "Withdrawn by the requesting API token."); + return { jobId, state: "cancelled", removedModel, message: removedModel ? "Withdrawn; the model it added left the library again." : "Withdrawn." }; + } + await requestCancel(jobId); + return { jobId, state: "cancelling", removedModel: false, message: `Cancelling; GET /api/v1/jobs/${jobId}?wait=60 to see it stop. Files already downloaded stay.` }; +} + +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 { + 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, reason = "Rejected by the user."): Promise<{ removedModel: boolean }> { + const job = await pendingJob(jobId); + const res = await db() + .update(jobs) + .set({ state: "cancelled", finishedAt: new Date(), errorMessage: reason }) + .where(and(eq(jobs.id, job.id), eq(jobs.state, "pending_approval"))) + .returning({ id: jobs.id }); + if (res.length === 0) throw new JobError("not_cancellable", "This job was approved or rejected in the meantime.", 409); + 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`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 }; +} diff --git a/src/lib/agent-guardrails.ts b/src/lib/agent-guardrails.ts new file mode 100644 index 0000000..28dca15 --- /dev/null +++ b/src/lib/agent-guardrails.ts @@ -0,0 +1,136 @@ +// 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. + * `author: false` skips the allowlist (a repair of a model that is already in the library). + */ +export function checkGuardrails(g: Guardrails, x: GuardrailInput, opts: { author?: boolean } = {}): void { + if (opts.author !== false) 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(" · "); +} diff --git a/src/lib/agent-selection.ts b/src/lib/agent-selection.ts new file mode 100644 index 0000000..94e6ef0 --- /dev/null +++ b/src/lib/agent-selection.ts @@ -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(); + 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[] { + const have = new Set(selected); + return requested.filter((p) => !have.has(p)); +} diff --git a/src/lib/agent.test.ts b/src/lib/agent.test.ts new file mode 100644 index 0000000..7507394 --- /dev/null +++ b/src/lib/agent.test.ts @@ -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, x: Partial, 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")); + }); +}); diff --git a/src/lib/api-token-core.ts b/src/lib/api-token-core.ts new file mode 100644 index 0000000..35eca0d --- /dev/null +++ b/src/lib/api-token-core.ts @@ -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); +} diff --git a/src/lib/api-tokens.ts b/src/lib/api-tokens.ts new file mode 100644 index 0000000..8017e32 --- /dev/null +++ b/src/lib/api-tokens.ts @@ -0,0 +1,113 @@ +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"; +import { SCOPE_LABEL } from "@/lib/token-scopes"; + +export class TokenError extends Error { + constructor( + public code: "invalid" | "exists" | "not_found", + message: string, + public status = 400, + ) { + super(message); + } +} + +export type ApiTokenRow = Omit; + +/** lastUsedAt is written at most this often per token, not on every request. */ +const TOUCH_MS = 60_000; + +export async function listTokens(): Promise { + 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 { + 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); +} + +/** Change what an active token may do (takes effect on its next request). */ +export async function updateTokenScopes(id: string, scopes: string[]): Promise { + const s = [...new Set(scopes)]; + if (s.length === 0 || !s.every(isScope)) throw new TokenError("invalid", "Pick at least one valid scope."); + const res = await db() + .update(apiTokens) + .set({ scopes: s as TokenScope[] }) + .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 revoked.", 404); +} + +/** Only revoked tokens can be deleted (frees the name; "requested by" labels keep it). */ +export async function deleteToken(id: string): Promise { + 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 { + 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 = (req: Request, ctx: Ctx & { token: TokenIdentity }) => Promise | Response; + +/** + * Wraps a /api/v1 route: requires `Authorization: Bearer ` with one of `scopes` (null: any + * valid token). Login sessions don't count here; the rest of the app is OIDC-only. + */ +export function withToken(scopes: TokenScope | TokenScope[] | null, handler: Handler) { + const need = scopes == null ? [] : Array.isArray(scopes) ? scopes : [scopes]; + 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 (need.length > 0 && !need.some((s) => token.scopes.includes(s))) { + const what = need.map((s) => `"${s}" (${SCOPE_LABEL[s].toLowerCase()})`).join(" or "); + return v1Error(403, "forbidden", `This token lacks the scope ${what}; it has: ${token.scopes.join(", ")}. Ask the user to grant it in Settings → API tokens.`); + } + return handler(req, { ...ctx, token }); + }; +} diff --git a/src/lib/api-v1-filters.ts b/src/lib/api-v1-filters.ts new file mode 100644 index 0000000..02e204d --- /dev/null +++ b/src/lib/api-v1-filters.ts @@ -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 = { + 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 }; +} diff --git a/src/lib/api-v1-models.test.ts b/src/lib/api-v1-models.test.ts new file mode 100644 index 0000000..0a9a984 --- /dev/null +++ b/src/lib/api-v1-models.test.ts @@ -0,0 +1,294 @@ +// /api/v1 actions on models already in the library: verify, repair, tags, cancelling a token's own +// jobs, and the activity log. Temporary SQLite database and a stubbed Hugging Face API. +// 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"; +import { eq } from "drizzle-orm"; + +const dir = mkdtempSync(join(tmpdir(), "kaname-api-models-")); +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".repeat(40); + +/** Fake Hub with one repo, for the download requests in here. */ +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)\/([^/]+)/); + const id = m && ["acme/Fresh-GGUF", "local/Folder"].find((k) => k.toLowerCase() === decodeURIComponent(m[1]).toLowerCase()); + if (!m || !id) return new Response("not found", { status: 404 }); + if (m[2] === "revision") return Response.json({ id, sha: SHA, gated: false, private: false, tags: [] }); + return Response.json([{ type: "file", path: "Fresh-Q4_K_M.gguf", size: 3 * GB, oid: "0".repeat(40), lfs: { oid: "e".repeat(64), size: 3 * GB } }]); +}) as typeof fetch; + +type Mods = { + db: typeof import("./db/client"); + schema: typeof import("./db/schema"); + tokens: typeof import("./api-tokens"); + settings: typeof import("./settings"); + activity: typeof import("./agent-activity"); + downloads: typeof import("../app/api/v1/downloads/route"); + job: typeof import("../app/api/v1/jobs/[id]/route"); + cancel: typeof import("../app/api/v1/jobs/[id]/cancel/route"); + model: typeof import("../app/api/v1/models/[id]/route"); + verify: typeof import("../app/api/v1/models/[id]/verify/route"); + repair: typeof import("../app/api/v1/models/[id]/repair/route"); + tags: typeof import("../app/api/v1/models/[id]/tags/route"); + tag: typeof import("../app/api/v1/models/[id]/tags/[name]/route"); + tagList: typeof import("../app/api/v1/tags/route"); +}; +let M: Mods; +let agent: { id: string; token: string }; // every scope +let other: { id: string; token: string }; // every scope, a different agent +let reader: string; + +const HUB_MODEL = "01M7000000000000000000000A"; +const LOCAL_MODEL = "01M7000000000000000000000B"; + +type Handler = (req: Request, ctx: never) => Promise; +const call = async (handler: Handler, path: string, opts: { token?: string; body?: unknown; method?: string; params?: Record } = {}) => { + const req = new Request(`http://kaname.test${path}`, { + method: opts.method ?? (opts.body !== undefined ? "POST" : "GET"), + headers: { ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}), "Content-Type": "application/json" }, + body: opts.body !== undefined ? 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 }; // eslint-disable-line @typescript-eslint/no-explicit-any +}; +const post = (handler: Handler, path: string, token: string, params: Record, body: unknown = {}) => call(handler, path, { token, body, params }); + +async function setFiles(modelId: string, states: Record) { + const { db } = M.db; + for (const [path, state] of Object.entries(states)) { + await db() + .update(M.schema.modelFiles) + .set({ state }) + .where((await import("drizzle-orm")).and(eq(M.schema.modelFiles.modelId, modelId), eq(M.schema.modelFiles.path, path))); + } +} + +async function finishJob(jobId: string, result?: Record) { + await M.db.db().update(M.schema.jobs).set({ state: "completed", finishedAt: new Date(), result }).where(eq(M.schema.jobs.id, jobId)); +} + +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"), + activity: await import("./agent-activity"), + downloads: await import("../app/api/v1/downloads/route"), + job: await import("../app/api/v1/jobs/[id]/route"), + cancel: await import("../app/api/v1/jobs/[id]/cancel/route"), + model: await import("../app/api/v1/models/[id]/route"), + verify: await import("../app/api/v1/models/[id]/verify/route"), + repair: await import("../app/api/v1/models/[id]/repair/route"), + tags: await import("../app/api/v1/models/[id]/tags/route"), + tag: await import("../app/api/v1/models/[id]/tags/[name]/route"), + tagList: await import("../app/api/v1/tags/route"), + }; + const all = ["models:read", "downloads:create", "models:verify", "tags:write"]; + agent = await M.tokens.createToken("hermes", all); + other = await M.tokens.createToken("other", all); + reader = (await M.tokens.createToken("reader", ["models:read"])).token; + + const d = M.db.db(); + const now = new Date(); + await d.insert(M.schema.workerState).values({ id: "worker", startedAt: now, heartbeatAt: now, modelsDirFreeBytes: 500 * GB, modelsDirTotalBytes: 2000 * GB }); + // A Hub model from an author that is not on the allowlist set below, and a local folder model. + await d.insert(M.schema.models).values([ + { id: HUB_MODEL, repoId: "TheBloke/Old-GGUF", pinnedSha: SHA, localPath: "TheBloke/Old-GGUF", includePatterns: ["*.gguf"], status: "ready" }, + { id: LOCAL_MODEL, repoId: "local/Folder", source: "local", pinnedSha: "", localPath: "local/Folder", includePatterns: ["*"], status: "ready" }, + ]); + await d.insert(M.schema.modelFiles).values([ + { modelId: HUB_MODEL, path: "Old-Q4_K_M.gguf", size: 4 * GB, selected: true, state: "present" }, + { modelId: HUB_MODEL, path: "Old-Q8_0.gguf", size: 8 * GB, selected: true, state: "present" }, + { modelId: HUB_MODEL, path: "README.md", size: 1000, selected: false }, + { modelId: LOCAL_MODEL, path: "weights.gguf", size: 1 * GB, selected: true, state: "present" }, + ]); + await M.settings.saveGuardrails({ allowedAuthors: ["unsloth"] }); +}); + +after(() => { + globalThis.fetch = realFetch; + (globalThis as { __kanameDb?: { client?: { close(): void } } }).__kanameDb?.client?.close(); + try { + rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); + } catch { + // A leftover temp dir is harmless. + } +}); + +describe("scopes", () => { + it("each action needs its own scope", async () => { + const p = { id: HUB_MODEL }; + assert.equal((await post(M.verify.POST, `/api/v1/models/${HUB_MODEL}/verify`, reader, p)).status, 403); + assert.equal((await post(M.repair.POST, `/api/v1/models/${HUB_MODEL}/repair`, reader, p)).status, 403); + const r = await post(M.tags.POST, `/api/v1/models/${HUB_MODEL}/tags`, reader, p, { name: "x" }); + assert.equal(r.status, 403); + assert.match(r.body.error.message, /tags:write/); + }); +}); + +describe("verify", () => { + let jobId: string; + + it("queues a verify right away, marked with the token (no approval needed)", async () => { + const r = await post(M.verify.POST, `/api/v1/models/${HUB_MODEL}/verify`, agent.token, { id: HUB_MODEL }); + assert.equal(r.status, 201); + assert.equal(r.body.state, "queued"); + jobId = r.body.jobId; + const job = await M.db.db().query.jobs.findFirst({ where: eq(M.schema.jobs.id, jobId) }); + assert.equal(job!.kind, "verify"); + assert.equal(job!.requestedBy, "hermes"); + }); + + it("accepts a POST without a body, and refuses a second job while one is open", async () => { + const req = new Request(`http://kaname.test/api/v1/models/${HUB_MODEL}/verify`, { method: "POST", headers: { Authorization: `Bearer ${agent.token}` } }); + const res = await M.verify.POST(req, { params: Promise.resolve({ id: HUB_MODEL }) } as never); + assert.equal(res.status, 409); + assert.equal(((await res.json()) as { error: { code: string } }).error.code, "busy"); + }); + + it("the finished job reports what's broken and points to repair", async () => { + await finishJob(jobId, { checked: 2, missing: ["Old-Q8_0.gguf"], sizeMismatch: [], hashMismatch: [] }); + const r = await call(M.job.GET, `/api/v1/jobs/${jobId}`, { token: reader, params: { id: jobId } }); + assert.equal(r.body.verify.ok, false); + assert.deepEqual(r.body.verify.missing, ["Old-Q8_0.gguf"]); + assert.match(r.body.next, /\/repair/); + }); + + it("deep verify is refused for a local model, plain verify works", async () => { + const deep = await post(M.verify.POST, `/api/v1/models/${LOCAL_MODEL}/verify`, agent.token, { id: LOCAL_MODEL }, { deep: true }); + assert.equal(deep.status, 409); + assert.equal(deep.body.error.code, "local_model"); + const plain = await post(M.verify.POST, `/api/v1/models/${LOCAL_MODEL}/verify`, agent.token, { id: LOCAL_MODEL }); + assert.equal(plain.status, 201); + await finishJob(plain.body.jobId); + }); + + it("unknown models are a 404", async () => { + const r = await post(M.verify.POST, "/api/v1/models/nope/verify", agent.token, { id: "nope" }); + assert.equal(r.status, 404); + }); +}); + +describe("repair", () => { + it("refuses when nothing is broken", async () => { + await setFiles(HUB_MODEL, { "Old-Q8_0.gguf": "present" }); + const r = await post(M.repair.POST, `/api/v1/models/${HUB_MODEL}/repair`, agent.token, { id: HUB_MODEL }); + assert.equal(r.status, 409); + assert.equal(r.body.error.code, "nothing_to_repair"); + }); + + it("asks for approval for just the broken files; the author allowlist doesn't apply", async () => { + await setFiles(HUB_MODEL, { "Old-Q8_0.gguf": "hash_mismatch" }); + const r = await post(M.repair.POST, `/api/v1/models/${HUB_MODEL}/repair`, agent.token, { id: HUB_MODEL }); + assert.equal(r.status, 201, JSON.stringify(r.body)); + assert.equal(r.body.state, "pending_approval"); + assert.deepEqual(r.body.files, ["Old-Q8_0.gguf"]); + assert.equal(r.body.requestedSize, "8.0 GB"); + const model = await M.db.db().query.models.findFirst({ where: eq(M.schema.models.id, HUB_MODEL) }); + assert.equal(model!.status, "ready", "a pending job doesn't change the model's status"); + }); + + it("a local model can't be repaired", async () => { + await setFiles(LOCAL_MODEL, { "weights.gguf": "missing" }); + const r = await post(M.repair.POST, `/api/v1/models/${LOCAL_MODEL}/repair`, agent.token, { id: LOCAL_MODEL }); + assert.equal(r.status, 409); + assert.equal(r.body.error.code, "local_model"); + }); +}); + +describe("cancelling a token's own jobs", () => { + it("another token can't cancel it", async () => { + const pending = await M.db.db().query.jobs.findFirst({ where: eq(M.schema.jobs.state, "pending_approval") }); + const r = await post(M.cancel.POST, `/api/v1/jobs/${pending!.id}/cancel`, other.token, { id: pending!.id }); + assert.equal(r.status, 403); + assert.equal(r.body.error.code, "not_own_job"); + }); + + it("withdrawing a pending repair keeps the model", async () => { + const pending = await M.db.db().query.jobs.findFirst({ where: eq(M.schema.jobs.state, "pending_approval") }); + const r = await post(M.cancel.POST, `/api/v1/jobs/${pending!.id}/cancel`, agent.token, { id: pending!.id }); + assert.equal(r.status, 202); + assert.equal(r.body.state, "cancelled"); + assert.equal(r.body.removedModel, false); + assert.ok(await M.db.db().query.models.findFirst({ where: eq(M.schema.models.id, HUB_MODEL) })); + }); + + it("withdrawing a pending new download removes the model it added", async () => { + await M.settings.saveGuardrails({ allowedAuthors: [] }); + const d = await call(M.downloads.POST, "/api/v1/downloads", { token: agent.token, body: { repoId: "acme/Fresh-GGUF", sha: SHA, quant: "Q4_K_M" } }); + assert.equal(d.status, 201, JSON.stringify(d.body)); + const r = await post(M.cancel.POST, `/api/v1/jobs/${d.body.jobId}/cancel`, agent.token, { id: d.body.jobId }); + assert.equal(r.body.removedModel, true); + assert.equal(await M.db.db().query.models.findFirst({ where: eq(M.schema.models.id, d.body.modelId) }), undefined); + }); + + it("a running job gets a cancel request", async () => { + await M.settings.saveGuardrails({ approvalMode: "auto" }); + const d = await call(M.downloads.POST, "/api/v1/downloads", { token: agent.token, body: { repoId: "acme/Fresh-GGUF", sha: SHA, quant: "Q4_K_M" } }); + assert.equal(d.body.state, "queued"); + const r = await post(M.cancel.POST, `/api/v1/jobs/${d.body.jobId}/cancel`, agent.token, { id: d.body.jobId }); + assert.equal(r.body.state, "cancelling"); + const job = await M.db.db().query.jobs.findFirst({ where: eq(M.schema.jobs.id, d.body.jobId) }); + assert.ok(job!.cancelRequestedAt); + await M.settings.saveGuardrails({ approvalMode: "approve" }); + await finishJob(d.body.jobId); + }); + + it("downloading into a local model is refused", async () => { + const r = await call(M.downloads.POST, "/api/v1/downloads", { token: agent.token, body: { repoId: "local/Folder", sha: SHA, include: ["*"] } }); + assert.equal(r.status, 409); + assert.equal(r.body.error.code, "local_model"); + }); +}); + +describe("tags", () => { + it("adds a tag (created on first use) and lists it", async () => { + const r = await post(M.tags.POST, `/api/v1/models/${HUB_MODEL}/tags`, agent.token, { id: HUB_MODEL }, { name: "Roleplay" }); + assert.equal(r.status, 201); + assert.deepEqual(r.body.tags, ["Roleplay"]); + const list = await call(M.tagList.GET, "/api/v1/tags", { token: reader }); + assert.deepEqual(list.body.tags, [{ name: "Roleplay", models: 1 }]); + const model = await call(M.model.GET, `/api/v1/models/${HUB_MODEL}`, { token: reader, params: { id: HUB_MODEL } }); + assert.deepEqual(model.body.tags, ["Roleplay"]); + }); + + it("removes a tag by name, case-insensitively; unknown names are a 404", async () => { + const missing = await call(M.tag.DELETE, `/api/v1/models/${HUB_MODEL}/tags/nope`, { token: agent.token, method: "DELETE", params: { id: HUB_MODEL, name: "nope" } }); + assert.equal(missing.status, 404); + const r = await call(M.tag.DELETE, `/api/v1/models/${HUB_MODEL}/tags/roleplay`, { token: agent.token, method: "DELETE", params: { id: HUB_MODEL, name: "roleplay" } }); + assert.equal(r.status, 200); + assert.deepEqual(r.body.tags, []); + }); + + it("rejects empty and overlong names", async () => { + const r = await post(M.tags.POST, `/api/v1/models/${HUB_MODEL}/tags`, agent.token, { id: HUB_MODEL }, { name: " " }); + assert.equal(r.status, 400); + }); +}); + +describe("activity log", () => { + it("records what the token did, including refusals with their code", async () => { + const rows = await M.activity.listActivity(agent.id); + const actions = rows.map((r) => `${r.action}:${r.outcome}${r.code ? `:${r.code}` : ""}`); + assert.ok(actions.includes("model.verify:ok"), actions.join(", ")); + assert.ok(actions.includes("model.repair:refused:nothing_to_repair"), actions.join(", ")); + assert.ok(actions.includes("model.repair:pending_approval"), actions.join(", ")); + assert.ok(actions.includes("job.cancel:ok"), actions.join(", ")); + assert.ok(actions.includes("tag.add:refused:invalid"), actions.join(", ")); + assert.ok(!rows.some((r) => r.tokenId !== agent.id)); + }); +}); diff --git a/src/lib/api-v1.test.ts b/src/lib/api-v1.test.ts new file mode 100644 index 0000000..cf1c391 --- /dev/null +++ b/src/lib/api-v1.test.ts @@ -0,0 +1,307 @@ +// /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 = { + "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, path: string, opts: { token?: string; body?: unknown; params?: Record } = {}) => { + 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 }; // 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); + // Free space is reported in whole MiB. + assert.ok(Math.abs(disk.body.availableForRequestsBytes - 2 * GB) < 2 ** 20, String(disk.body.availableForRequestsBytes)); + 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); + }); +}); diff --git a/src/lib/api-v1.ts b/src/lib/api-v1.ts new file mode 100644 index 0000000..e671631 --- /dev/null +++ b/src/lib/api-v1.ts @@ -0,0 +1,54 @@ +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> = { + 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 || 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`; +} + +/** A JSON body, or {} when there is none (POST without a body is fine for actions). */ +export async function optionalJson(req: Request): Promise { + const text = await req.text(); + return text.trim() ? JSON.parse(text) : {}; +} diff --git a/src/lib/db/enums.ts b/src/lib/db/enums.ts index fc65706..8354a0d 100644 --- a/src/lib/db/enums.ts +++ b/src/lib/db/enums.ts @@ -44,6 +44,7 @@ export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update", "re export type JobPurpose = (typeof JOB_PURPOSES)[number]; export const JOB_STATES = [ + "pending_approval", // requested through the API, waits for someone to approve it in the UI "queued", "downloading", "verifying", @@ -73,6 +74,18 @@ export type JobFileState = (typeof JOB_FILE_STATES)[number]; export const LOG_STREAMS = ["stdout", "stderr", "system"] as const; export type LogStream = (typeof LOG_STREAMS)[number]; +// API tokens (programs and AI agents, /api/v1) + +/** + * What a token may do. No scope can delete models or files, change settings or manage tokens. + * downloads:create also covers repair (it downloads); models:verify covers verify and deep verify. + */ +export const TOKEN_SCOPES = ["models:read", "downloads:create", "models:verify", "tags:write"] as const; +export type TokenScope = (typeof TOKEN_SCOPES)[number]; + +export const AGENT_OUTCOMES = ["ok", "pending_approval", "refused"] as const; +export type AgentOutcome = (typeof AGENT_OUTCOMES)[number]; + // Endpoints and benchmarks export const ENDPOINT_ENGINES = ["llama.cpp", "vllm", "sglang", "ollama", "other"] as const; diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts index e2de650..46230fd 100644 --- a/src/lib/db/schema.ts +++ b/src/lib/db/schema.ts @@ -9,6 +9,7 @@ import { } from "drizzle-orm/sqlite-core"; import { ulid } from "ulid"; import { + AGENT_OUTCOMES, BENCHMARK_KINDS, type BenchmarkPhase, BENCHMARK_STATES, @@ -26,6 +27,7 @@ import { MODEL_STATUSES, PUBLICATION_STATES, type QualitySection, + type TokenScope, } from "./enums"; // The enum arrays live in ./enums (no dependencies), so client components can use them without @@ -83,6 +85,8 @@ export type JobResult = { removed?: 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( @@ -137,6 +141,9 @@ export const models = sqliteTable( /** Hub tags, minus noise like arxiv:/region:/deploy:. */ hubTags: text("hub_tags", { mode: "json" }).$type(), metadataFetchedAt: ts("metadata_fetched_at"), + /** Added through the API: the token (its id, and its name at the time). */ + requestedByTokenId: text("requested_by_token_id"), + requestedBy: text("requested_by"), createdAt: createdAt(), updatedAt: updatedAt(), }, @@ -242,6 +249,9 @@ export const jobs = sqliteTable( result: text("result", { mode: "json" }).$type(), /** 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 (its id, 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(), @@ -288,6 +298,47 @@ export const jobLogs = sqliteTable( (t) => [index("job_logs_job_idx").on(t.jobId, t.id)], ); +// --------------------------------------------------------------------------- +// API tokens for programs and AI agents (only /api/v1 accepts them) +// --------------------------------------------------------------------------- + +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().notNull(), + lastUsedAt: ts("last_used_at"), + revokedAt: ts("revoked_at"), + createdAt: createdAt(), + }, + (t) => [uniqueIndex("api_tokens_name_uq").on(t.name)], +); + +/** What tokens did: every request that creates or changes something, and every refusal. */ +export const agentActivity = sqliteTable( + "agent_activity", + { + id: id(), + tokenId: text("token_id").notNull(), + tokenName: text("token_name").notNull(), + /** e.g. "download.request", "model.verify", "model.repair", "tag.add", "job.cancel". */ + action: text("action").notNull(), + targetType: text("target_type"), + targetId: text("target_id"), + outcome: text("outcome", { enum: AGENT_OUTCOMES }).notNull(), + /** The error code of a refusal. */ + code: text("code"), + message: text("message"), + createdAt: createdAt(), + }, + (t) => [index("agent_activity_token_idx").on(t.tokenId, t.createdAt)], +); + // --------------------------------------------------------------------------- // App settings (key/value, edited on the Settings page) // --------------------------------------------------------------------------- diff --git a/src/lib/endpoint-probe.test.ts b/src/lib/endpoint-probe.test.ts index be130ae..5bcd1ab 100644 --- a/src/lib/endpoint-probe.test.ts +++ b/src/lib/endpoint-probe.test.ts @@ -88,13 +88,14 @@ describe("probing a server", () => { }); describe("login gate", () => { - // proxy.ts gates every page and API route except Auth.js, the login page and static files. + // proxy.ts gates every page and API route except Auth.js, the token API (/api/v1, which checks + // its bearer token in each route), the login page and static files. 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("gates every API route, including the old token API paths", () => { - for (const p of ["/api/endpoints", "/api/endpoints/x/test", "/api/benchmarks", "/api/v1", "/api/v1/models", "/settings", "/loginx", "/"]) assert.ok(gated(p), p); - for (const p of ["/api/auth/signin", "/login", "/_next/static/x.js", "/favicon.ico"]) assert.ok(!gated(p), p); + it("gates every API route except Auth.js and the token API", () => { + for (const p of ["/api/endpoints", "/api/endpoints/x/test", "/api/benchmarks", "/api/api-tokens", "/api/v1x", "/settings", "/loginx", "/"]) assert.ok(gated(p), p); + for (const p of ["/api/auth/signin", "/api/v1", "/api/v1/models", "/login", "/_next/static/x.js", "/favicon.ico"]) assert.ok(!gated(p), p); }); }); diff --git a/src/lib/jobs.ts b/src/lib/jobs.ts index 29668af..06081b1 100644 --- a/src/lib/jobs.ts +++ b/src/lib/jobs.ts @@ -16,7 +16,7 @@ import { export class JobError extends Error { constructor( - public code: "not_found" | "busy" | "nothing_selected" | "not_cancellable" | "hub_missing" | "local_model", + public code: "not_found" | "busy" | "nothing_selected" | "not_cancellable" | "hub_missing" | "local_model" | "not_own_job", message: string, public status: number, ) { @@ -24,11 +24,14 @@ export class JobError extends Error { } } -/** Jobs that block another job for the same model. */ -export 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). */ +/** Who asked for a job through the API (token id + its name at the time). */ +export type RequestedBy = { tokenId: string; name: string }; + +/** True if the model has a pending, queued or running job (only one job per model at a time). */ export async function hasOpenJob(modelId: string): Promise { const open = await db().query.jobs.findFirst({ columns: { id: true }, @@ -40,12 +43,13 @@ export async function hasOpenJob(modelId: string): Promise { /** * 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) }); @@ -53,7 +57,7 @@ export async function queueDownload( if (model.source === "local") throw new JobError("local_model", "This is a local model without a Hugging Face repo: there's nothing to download.", 409); const missing = hubMissingMessage(model); if (missing) throw new JobError("hub_missing", missing, 409); - if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409); + if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a pending, queued or running job.", 409); const files = await d .select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size }) @@ -66,32 +70,36 @@ export async function queueDownload( 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: "queued", + state: options.pendingApproval ? "pending_approval" : "queued", targetSha: model.pinnedSha, totalBytes: files.reduce((s, f) => s + f.size, 0), 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 }; } /** Queue a verify (size + hf metadata) or deep verify (hashes) of the selected files. Local only. */ -export async function queueVerify(modelId: string, deep: boolean): Promise<{ jobId: string }> { +export async function queueVerify(modelId: string, deep: boolean, options: { requestedBy?: RequestedBy } = {}): Promise<{ jobId: string }> { const d = db(); const model = await d.query.models.findFirst({ where: eq(models.id, modelId) }); if (!model) throw new JobError("not_found", "Model not found.", 404); if (deep && model.source === "local") { throw new JobError("local_model", "A local model has no Hub hashes to compare with. Use Verify (existence and size).", 409); } - if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409); + if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a pending, queued or running job.", 409); const files = await d .select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size }) .from(modelFiles) @@ -107,6 +115,8 @@ export async function queueVerify(modelId: string, deep: boolean): Promise<{ job kind: deep ? "deep_verify" : "verify", targetSha: model.pinnedSha, totalBytes: files.reduce((s, f) => s + f.size, 0), + requestedByTokenId: options.requestedBy?.tokenId ?? null, + requestedBy: options.requestedBy?.name ?? null, }), ...chunk( files.map((f) => ({ jobId, modelFileId: f.id, path: f.path, expectedBytes: f.size })), @@ -124,8 +134,9 @@ export async function requestCancel(jobId: string): Promise { .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) }); + const job = await db().query.jobs.findFirst({ columns: { id: true, state: true }, 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 download waits for approval. Approve or reject it instead.", 409); throw new JobError("not_cancellable", "This job is not running anymore.", 409); } } @@ -151,6 +162,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; @@ -183,12 +196,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 & { repoId: string }; +type JobRow = Omit & { repoId: string }; function toSnapshot(r: JobRow): JobSnapshot { const { cancelRequestedAt, createdAt, startedAt, finishedAt, ...rest } = r; diff --git a/src/lib/library.ts b/src/lib/library.ts index 18406f9..c283ed0 100644 --- a/src/lib/library.ts +++ b/src/lib/library.ts @@ -1,7 +1,7 @@ import "server-only"; import { and, asc, desc, eq, sql } from "drizzle-orm"; import { db } from "@/lib/db/client"; -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,6 +30,7 @@ export async function listLibrary() { pipelineTag: models.pipelineTag, license: models.license, hubTags: models.hubTags, + requestedBy: models.requestedBy, fileCount: sql`count(${modelFiles.id})`, totalBytes: sql`coalesce(sum(${modelFiles.size}), 0)`, /** Selected files that are on disk (present or verified). */ @@ -55,6 +56,10 @@ export async function listLibrary() { const tagsByModel = new Map(); 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, @@ -64,6 +69,7 @@ export async function listLibrary() { hubTags: r.hubTags ?? [], quants: [...(quants.get(r.id) ?? [])].sort(), tags: tagsByModel.get(r.id) ?? [], + pendingApproval: pending.has(r.id), })); } diff --git a/src/lib/live-store.test.ts b/src/lib/live-store.test.ts index 0717601..8379d7b 100644 --- a/src/lib/live-store.test.ts +++ b/src/lib/live-store.test.ts @@ -24,6 +24,7 @@ function job(id: string, state: string): JobSnapshot { errorMessage: null, result: null, cancelRequested: false, + requestedBy: null, createdAt: 0, startedAt: null, finishedAt: null, diff --git a/src/lib/models.ts b/src/lib/models.ts index c8d246f..16f9a6b 100644 --- a/src/lib/models.ts +++ b/src/lib/models.ts @@ -6,7 +6,7 @@ import { jobFiles, jobs, localFolders, modelFiles, modelRevisions, models } from import { hubMissingMessage } from "@/lib/hub/availability"; import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client"; import { metadataColumns } from "@/lib/hub/refresh"; -import { hasOpenJob, queueDownload } from "@/lib/jobs"; +import { hasOpenJob, queueDownload, type RequestedBy } from "@/lib/jobs"; import { getLocalFolder, localFolderExists, requestFolderScan } from "@/lib/local-folders"; import { purgeModelRows } from "@/lib/model-purge"; import { contentId } from "@/lib/update-diff"; @@ -14,7 +14,7 @@ import { escapeGlob, isSelected, matchesAny, type SelectionRule } from "@/lib/se export class ModelError extends Error { constructor( - public code: "already_exists" | "empty_selection" | "not_found" | "busy" | "hub_missing" | "no_update" | "local_model", + public code: "already_exists" | "empty_selection" | "not_found" | "busy" | "hub_missing" | "no_update" | "local_model" | "nothing_to_repair", message: string, public status: number, ) { @@ -35,6 +35,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; @@ -83,6 +85,8 @@ export async function addModel(input: { includePatterns: input.rule.include, excludePatterns: input.rule.exclude, ...metadataColumns(info.metadata, avatar), + requestedByTokenId: input.requestedBy?.tokenId ?? null, + requestedBy: input.requestedBy?.name ?? null, }), d.insert(modelRevisions).values({ modelId, sha: info.sha }), ...chunk(fileRows, INSERT_CHUNK).map((c) => d.insert(modelFiles).values(c)), @@ -247,7 +251,11 @@ function chunk(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); @@ -257,9 +265,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 job 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])); @@ -279,10 +287,28 @@ 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 { + 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))), + ]); +} + /** * Remove files from a model: take them out of the selection rule (exact-path excludes, and their * exact includes dropped), mark them unselected, and queue a delete job that removes them from diff --git a/src/lib/search.test.ts b/src/lib/search.test.ts index 9b3aecd..e410cba 100644 --- a/src/lib/search.test.ts +++ b/src/lib/search.test.ts @@ -56,6 +56,8 @@ const model = (over: Partial): SearchableModel => ({ license: "apache-2.0", status: "ready", hubStatus: null, + requestedBy: null, + pendingApproval: false, ...over, }); diff --git a/src/lib/search.ts b/src/lib/search.ts index 4abbda1..ea045f1 100644 --- a/src/lib/search.ts +++ b/src/lib/search.ts @@ -14,15 +14,22 @@ 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; /** The text search terms are matched against (searchText), computed once per model. */ text?: string; }; -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; -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) { @@ -35,7 +42,9 @@ export function facetValues(m: SearchableModel, facet: Facet): string[] { case "tag": return m.tags; case "status": - return [m.status, m.hubStatus].filter((v): v is string => !!v); + return [m.status, m.hubStatus, m.pendingApproval ? PENDING_APPROVAL : null].filter((v): v is string => !!v); + case "requester": + return m.requestedBy ? [m.requestedBy] : []; } } @@ -54,6 +63,7 @@ export function searchText(m: SearchableModel): string { m.license, m.status, m.hubStatus, + m.requestedBy, ] .filter(Boolean) .join(" ") diff --git a/src/lib/settings.ts b/src/lib/settings.ts index bc801b8..c052425 100644 --- a/src/lib/settings.ts +++ b/src/lib/settings.ts @@ -2,6 +2,7 @@ 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"; @@ -157,3 +158,22 @@ export async function saveBackdrop(input: unknown): Promise { 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 { + return parseGuardrails(await read(GUARDRAILS_KEY)); +} + +export async function saveGuardrails(input: Partial): Promise { + 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; +} diff --git a/src/lib/token-scopes.ts b/src/lib/token-scopes.ts new file mode 100644 index 0000000..0b40546 --- /dev/null +++ b/src/lib/token-scopes.ts @@ -0,0 +1,10 @@ +// What each API token scope allows, for the settings UI. Pure, safe for the browser. + +import type { TokenScope } from "@/lib/db/enums"; + +export const SCOPE_LABEL: Record = { + "models:read": "Look up Hub repos, list models and tags, read jobs and disk space", + "downloads:create": "Request downloads and repairs, cancel its own downloads (within the guardrails)", + "models:verify": "Start verify and deep verify, cancel its own verify jobs", + "tags:write": "Add and remove tags on models (creates a tag on first use)", +}; diff --git a/src/lib/wait.ts b/src/lib/wait.ts new file mode 100644 index 0000000..b16c473 --- /dev/null +++ b/src/lib/wait.ts @@ -0,0 +1,34 @@ +// `?wait=` on /api/v1 status endpoints: instead of an agent polling (each call costs it a +// round of context), the request blocks until the state is settled or the time is up. Pure apart +// from the timers. + +export const MAX_WAIT_S = 900; +const POLL_MS = 1_000; + +/** `?wait=` as seconds, clamped to 0–900 (absent or invalid: 0, answer right away). */ +export function parseWait(params: URLSearchParams): number { + const n = Number(params.get("wait")); + return Number.isFinite(n) && n > 0 ? Math.min(MAX_WAIT_S, Math.floor(n)) : 0; +} + +/** + * Loads `load()` until `settled` holds, `seconds` pass or the client goes away; returns the last + * value and how long it waited. Re-reads the database once a second (cheap with SQLite). + */ +export async function waitFor( + load: () => Promise, + settled: (v: T) => boolean, + seconds: number, + opts: { signal?: AbortSignal; pollMs?: number; now?: () => number } = {}, +): Promise<{ value: T; waitedS: number; timedOut: boolean }> { + const now = opts.now ?? Date.now; + const start = now(); + const deadline = start + seconds * 1000; + let value = await load(); + while (!settled(value) && now() < deadline && !opts.signal?.aborted) { + await new Promise((r) => setTimeout(r, Math.min(opts.pollMs ?? POLL_MS, Math.max(0, deadline - now())))); + value = await load(); + } + const waitedS = Math.round((now() - start) / 1000); + return { value, waitedS, timedOut: !settled(value) && seconds > 0 }; +} diff --git a/src/proxy.ts b/src/proxy.ts index 78eee87..d27a225 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -26,7 +26,8 @@ export async function proxy(req: NextRequest, event: NextFetchEvent) { } export const config = { - // Everything except the Auth.js endpoints, the login page and static assets. - // Exact exclusions only: an org like "loginx" must still go through the gate. - matcher: ["/((?!api/auth/|login$|_next/static/|_next/image/|favicon\\.ico$).*)"], + // Everything except the Auth.js endpoints, the token-authenticated API (/api/v1, checked by + // withToken in each route), the login page and static assets. + // Exact exclusions only: an org like "loginx" or a path like "/api/v1x" must still go through the gate. + matcher: ["/((?!api/auth/|api/v1/|api/v1$|login$|_next/static/|_next/image/|favicon\\.ico$).*)"], };