API for agents: tokens, /api/v1 for downloads, verify, repair, tags
Brings back the token API that 0.15 removed with deployments, for models only, ported onto the current code (local models, lean client bundles, MiB-rounded disk space): - Scoped bearer tokens (models:read, downloads:create, models:verify, tags:write), stored as SHA-256, managed in Settings -> API tokens. Only /api/v1 accepts them; the rest stays OIDC-only. - /api/v1: Hub lookup, library with the search filters, download requests through the add-model/queue path (idempotent), repair of missing or broken files, verify / deep verify, tags, job status with ?wait=, cancelling or withdrawing the token's own jobs, disk space. - Guardrails for downloads and repairs: approval (default ask), max size per request, minimum free space incl. reserved bytes, agent jobs at once, author allowlist (new downloads only). Approve/reject in the UI, "requested by" badges and filter, activity log per token. - Migration 0027 adds api_tokens, agent_activity and requested_by columns on models and jobs; job state pending_approval. - docs/api.md, docs/agent/SKILL.md and the kaname curl helper; DB-backed API tests. The login gate test now expects /api/v1 to be left to token auth. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7d1a8fb85a
commit
0e0445a418
63 files changed
+5448
-42
No files matched your search
+330
@@ -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://<host>: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.
|
||||
Reference in new issue
Block a user