Compare commits

..
29 Commits
Author SHA1 Message Date
Pascal LinxweilerandClaude Opus 5.5 8447289649 Release 0.23.0: run without login
Release / release (push) Successful in 2m59s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:20:49 +01:00
Pascal LinxweilerandClaude Opus 5.5 a13ac85f7c Run without login when OIDC isn't configured
With OIDC_ISSUER, OIDC_CLIENT_ID and OIDC_CLIENT_SECRET empty (or at the
.env.example placeholders) Kaname needs no login. With all three set, OIDC
works as before; only some set is an error. /api/v1 still requires tokens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:18:47 +01:00
Pascal LinxweilerandClaude Opus 5.5 1fe61142f4 README: show the full compose.yaml and .env in the install steps
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:16:38 +01:00
Pascal LinxweilerandClaude Opus 5.5 15d8ae155e Simplify compose files and .env.example
Folders, port and image are written straight into compose.yaml; the
KANAME_DATA_DIR, KANAME_MODELS_DIR, WEB_PORT and KANAME_IMAGE variables
are gone. .env.example is down to the settings people actually set.
README and CHANGELOG updated accordingly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:14:15 +01:00
Pascal LinxweilerandClaude Opus 5.5 5bc1ad1395 Release 0.22.0: API for agents
Release / release (push) Successful in 4m16s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:55:01 +01:00
Pascal LinxweilerandClaude Opus 5.5 0e0445a418 API for agents: tokens, /api/v1 for downloads, verify, repair, tags
Brings back the token API that 0.15 removed with deployments, for
models only, ported onto the current code (local models, lean client
bundles, MiB-rounded disk space):

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:52:28 +01:00
Pascal LinxweilerandClaude Opus 5.5 7d1a8fb85a Revert CivitAI downloads
Removes the CivitAI work again (765dac2, a1acd8c): the API client and
link parser, CIVITAI_TOKEN, adding CivitAI models, migration 0027 and
the model page changes. Kaname downloads from Hugging Face only, as in
0.21.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:32:02 +01:00
Pascal LinxweilerandClaude Opus 5.5 a1acd8c0a5 CivitAI: add models from civitai.com / civitai.red links
Paste a CivitAI model link (civitai.com, .red or .green), a download
link or an AIR id into "Add model": pick a version and its files, and
whether to follow new versions. The model is stored as source "civitai"
with repoId civitai/<modelId>, pinned to the version id, in the folder
civitai/<id>-<name>; files keep CivitAI's SHA-256 for deep verify.
Early access and creator-required logins are caught before anything is
queued.

Migration 0027 adds models.display_name, nsfw and source_card, and
model_files.civitai (file id and attributes). The model page links to
CivitAI instead of the Hub, and Hub checks, updates and adding files
are refused for CivitAI models for now. The worker fails CivitAI
download jobs until it can run them (next step).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:14:14 +01:00
Pascal LinxweilerandClaude Opus 5.5 765dac2ed2 CivitAI: API client, input parser and CIVITAI_TOKEN
First step towards CivitAI downloads. Lookups of models, versions and
download access (login required, early access with its deadline), and a
parser for civitai.com / .red / .green links, download links and AIR ids.
Nothing uses it yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:06:01 +01:00
Pascal LinxweilerandClaude Opus 5.5 29e6893a17 Release 0.21.0: reload local models
Release / release (push) Successful in 2m57s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 00:55:08 +01:00
Pascal LinxweilerandClaude Opus 5.5 80d71a1bc9 Local models: Reload button, scans keep their files in step
Files tab → Reload asks the worker for a scan and waits until it has
finished. Every scan now syncs local models' file lists with their
folders (new, resized, removed files; README) and settles the status.
Skipped while a job runs, and for a folder that is gone or too big.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 00:55:03 +01:00
Pascal LinxweilerandClaude Opus 5.5 f862717158 Release 0.20.0: README.md as the model card of local models
Release / release (push) Successful in 2m52s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 00:27:26 +01:00
Pascal LinxweilerandClaude Opus 5.5 d27e79bba0 Local models: the folder's README.md is the model card
The worker reads README.md when it scans the models folder (the web
app can't see it) and stores it on the folder and, after import, on
the model; every scan refreshes it for local models. Relative images
and links are dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 00:27:17 +01:00
Pascal LinxweilerandClaude Opus 5.5 5a8893e7db Release 0.19.0: import folders without a Hub repo
Release / release (push) Successful in 6m0s
Add model → Found in the models folder → Import → "Add as local model"
adds a folder that isn't on Hugging Face as it is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 00:15:07 +01:00
Pascal LinxweilerandClaude Opus 5.5 80ccf800df Import folders without a Hub repo as local models
The Import form gets "Add as local model": every file in the folder,
kept as it is, named after the folder. A new models.source column
(hub | local) marks them; local models skip Hub checks, metadata,
downloads, updates and deep verify, and Verify checks existence and
size only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 00:14:56 +01:00
Pascal LinxweilerandClaude Opus 5.5 90d6007b55 package-lock: fix the 0.18.0 bump
Release / release (push) Successful in 2m55s
The release commit bumped @eslint/core's entry instead of Kaname's own
(the lockfile's root version was still 0.16.0). Restore @eslint/core and
set the root version to 0.18.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:14:47 +01:00
Pascal LinxweilerandClaude Opus 5.5 85d79b6f7a Release 0.18.0: your own background picture
Release / release (push) Successful in 3m3s
Settings → Appearance: upload an image to draw it as the dot matrix
behind every page header instead of The Creation of Adam.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:13:54 +01:00
Pascal LinxweilerandClaude Opus 5.5 02756ddf90 Custom background picture for the dot matrix headers
Settings → Appearance: upload an image and every page header draws it as
the dot matrix instead of The Creation of Adam, with a clickable focus
point and a switch back to the built-in painting. The browser turns the
image into a brightness grid; only that grid is saved as a setting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:13:48 +01:00
pascallinxweiler 422e46bf65 Release 0.17.0: bump package.json, finalize changelog section
Release / release (push) Successful in 4m47s
The v0.17.0 tag was cut on a tree where package.json was still 0.16.0,
so the Release workflow's version-match check aborted before building.
Bump the version and move the Unreleased changelog entry to [0.17.0]
so tag and package.json agree.
2026-11-02 19:44:40 +01:00
Claude 67cd0c945a Docker: standalone server, bundled worker, no caches in the image
Release / release (push) Failing after 10s
The runtime stage copied the whole production node_modules (495 MB, with
shadcn's CLI tree, the SWC compiler and sharp) and all of .next (163 MB, 119 MB
of it Turbopack's build cache). The image is now 427 MB instead of 1.04 GB:

- Next.js standalone output (NEXT_OUTPUT=standalone, set by the Dockerfile; a
  local `next build`/`next start` is unchanged): server.js with only the traced
  node_modules (39 MB). images.unoptimized (nothing uses next/image) keeps sharp
  and libvips out of the server's trace; /_next/image answers 404.
- build:worker bundles drizzle-orm, zod and ulid into dist/*.mjs and keeps only
  @libsql/client and libsql external; the standalone node_modules has both.
- npm's cache and .next/cache are BuildKit cache mounts: reused by the next
  build on the same machine (Next build 30 s -> 12 s after a code change), never
  in a layer.
- Release archives (BetterBench, both L80 tarballs) are fetched in their own
  stage; only the L80 binary is copied, BetterBench is installed from a bind
  mount.
- shadcn and tw-animate-css (CSS imports, build time only) move to
  devDependencies; package-lock.json regenerated with npm 11 (the image's npm).

Verified by building the image and running web, worker and sandbox from it:
pages and /api/live answer, the worker migrates, takes the lease and finds hf,
BetterBench and L80, all three healthchecks pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
2026-11-01 21:23:51 +00:00
Claude 6b779debf7 DB: indexes for the polling queries
- jobs(finished_at): the live view's "open or finished in the last 5 minutes"
  query, run once a second per visible tab, was a full scan of the job
  history; it is now a multi-index lookup (0.23 -> 0.04 ms at 2,000 jobs).
- benchmark_runs(state, created_at): the worker's look for the next queued run
  every 2 s scanned every run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
2026-11-01 21:04:45 +00:00
Claude 6f4932e04d Hub: reuse commit trees, ask for SHAs only, stream the model card
- listFiles() keeps the last trees it fetched by repo@SHA (a commit's files
  never change; capped at 50,000 files): adding a model right after the lookup
  no longer downloads the whole tree again. Callers get copies.
- addModel() fetches the author's avatar in parallel with the file list.
- The Hub check resolves revisions with resolveRevision(): /revision/<rev> with
  expand=sha, as huggingface_hub's model_info(expand=...) does, instead of the
  full model info (file list, card data, the Spaces using the model). Falls
  back to the full request if an answer comes without a SHA.
- The Model card tab renders inside <Suspense>: the page no longer waits for
  the README to arrive from the Hub (up to the 20 s timeout when it's slow).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
2026-11-01 21:04:05 +00:00
Claude d58bff3437 Worker: write only what changed, sample downloads less
- The models folder scan compared nothing and rewrote local_folders on every
  run (delete all, insert all, each folder's file list included), every 2
  minutes by default: ~1 MB of SQLite writes per scan with three large import
  folders. It now inserts new folders, updates changed ones and deletes gone
  ones; unchanged rows (compared by counts, commit and the stored JSON text)
  aren't written.
- Download progress and the speed limit share one ProgressSampler. A file found
  complete isn't stat'ed or its hf metadata re-read again during the run, and
  with every file complete the partial files aren't listed. Before, every
  sample looked at every file, 5 times a second with a speed limit set. The
  check after hf exits still looks at every file.
- A benchmark's phase is written when its step changes, not for every
  progress line BetterBench prints.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
2026-11-01 21:01:11 +00:00
Claude d10a491042 Client bundles: no drizzle in the browser, lazy palette, one copy of the painting
- The enum arrays move from schema.ts to src/lib/db/enums.ts (no imports),
  which schema.ts re-exports. The endpoint form and benchmark start imported
  ENDPOINT_ENGINES/QUALITY_SECTIONS from the schema, which put drizzle-orm,
  every table definition and ulid (18 KB gzipped) on the endpoint pages. An
  ESLint rule now refuses value imports from the schema in client code.
- The ⌘K palette dialog is its own chunk, loaded on first open and preloaded
  when you hover or focus Search or press ⌘/Ctrl.
- The dot painting's brightness grid was copied into 10 page chunks (~10 KB
  gzipped each); it is now one async chunk, parsed once per tab. The canvas
  skips redraws when size, pixel ratio and theme are unchanged (the
  ResizeObserver's first callback drew everything a second time) and draws at
  most once per frame while resizing.

First-load JS per route drops by 10-29 KB gzipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
2026-11-01 20:57:53 +00:00
Claude 2e56351e96 Benchmarks: lean list queries
listBenchmarks() selected every column of every run, including the raw A/B
series, all quality eval items, hardware facts and descriptions, while lists
show only the snapshot, settings, headline numbers and the quality score. With
200 runs /api/benchmarks returned 732 KB, re-fetched every 3 s while a run was
active; the table used about 55 KB of it.

- listBenchmarks() returns lean rows: the headline numbers are computed on the
  server from the summary, the quality score comes from json_extract().
- The model page asks for 5 runs (it shows 5), the ⌘K index for 300.
- getBenchmark()/getBenchmarks() keep the full rows for detail and compare;
  cancel and delete only read the state.
- ListRow (lists) and RunRow (detail) are separate types.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
2026-11-01 20:52:12 +00:00
Claude 7239ba2692 Library: load import folder files on demand, memoize search
The library page passed every importable folder's full file list (up to 5,000
entries each, from the worker's scan) into a client component, though it is
only used after clicking Import. With three such folders that was 84% of a
1.3 MB page, re-sent on every refresh after a job finished.

- listLocalFolders() returns path, commit and counts only; the Import button
  fetches one folder's files from GET /api/local-folders?path=…
- addModel() checks that an import folder exists without loading its files.
- LibraryView builds each model's search text once and memoizes the visible
  rows and facet counts; the facet sort uses one Intl.Collator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
2026-11-01 20:49:18 +00:00
Claude 76d851896e Live updates: one poller per tab instead of SSE streams
Every useLive() call opened its own EventSource, and the library page and a
model's Jobs tab call it twice. Over plain HTTP a browser allows 6 connections
per host, so with three library tabs open the third took ~10 s to load and its
requests never got an answer; a fourth tab didn't load.

- /api/live answers one short request with the job snapshot (left out when the
  client already has that version) and, for job pages, new log lines.
- src/lib/live-store.ts runs one poller per query per tab, shared by every
  component showing it, paused while the tab is hidden, with backoff on errors.
  One router.refresh() per finished job instead of one per component.
- The worker dot reads the status from that poll; it only asks /api/status
  (every 10 s) when nothing else is polled.
- The worker status no longer carries the heartbeat time (it changed every 5 s,
  so every idle stream re-sent its snapshot) and rounds free space to MiB.
- Removes /api/stream: its sleep() added an abort listener per second to the
  request signal and never removed it.
- Job actions poll right away after starting or cancelling a job; drops
  approveJob/rejectJob, whose routes went away in 0.15.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
2026-11-01 20:46:54 +00:00
Pascal LinxweilerandClaude Opus 5.5 16c3fcc113 README: banner under a new name (Gitea caches images for 6 h)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:16:46 +01:00
Pascal LinxweilerandClaude Opus 5.5 aab48d6181 README: new banner for the 0.16 look
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:12:24 +01:00
133 changed files with 13383 additions and 892 deletions

No files matched your search

+20 -56
View File
@@ -1,64 +1,28 @@
# Kaname settings. Copy to .env next to compose.yaml and fill in the "Required" part; everything
# else has working defaults. Full reference: https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Configuration
# Kaname settings: copy to .env next to compose.yaml and fill in.
# All options: https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Configuration
# ---------------------------------------------------------------------------
# Required
# ---------------------------------------------------------------------------
# Read-only Hugging Face token (needed for gated repos, higher rate limits)
HF_TOKEN=
MAX_CONCURRENT_DOWNLOADS=1
UPDATE_CHECK_INTERVAL_HOURS=12
# The address you open Kaname at in the browser (no trailing slash). The OIDC redirect URI to
# register with your provider is <AUTH_URL>/api/auth/callback/pocket-id
# Login (optional). Leave OIDC_* empty (or at these placeholders) to run without any login:
# then anyone who can reach Kaname can use it. To require an OIDC login, set all three.
# AUTH_URL is the address you open Kaname at; register
# <AUTH_URL>/api/auth/callback/pocket-id as redirect URI with your OIDC provider.
# AUTH_SECRET: any random string (openssl rand -base64 32); empty = generated on first start.
AUTH_SECRET=
AUTH_URL=http://localhost:3000
# OIDC provider (e.g. Pocket ID): authorization code flow with PKCE
OIDC_ISSUER=https://auth.example.com
OIDC_CLIENT_ID=
OIDC_CLIENT_SECRET=
# ---------------------------------------------------------------------------
# Recommended
# ---------------------------------------------------------------------------
# Hugging Face token: read-only is enough. Needed for gated/private repos, recommended anyway
# (higher rate limits). Stays on the server; never sent to the browser or written to logs.
HF_TOKEN=
# Optional, comma-separated: only members of these groups (`groups` claim) can log in.
# Optional, comma-separated: only these groups may log in
OIDC_ALLOWED_GROUPS=
# ---------------------------------------------------------------------------
# Folders, port and image (deploy/compose.yaml)
# ---------------------------------------------------------------------------
# SQLite database and benchmark results. Must be on local disk, not NFS.
KANAME_DATA_DIR=./data
# Downloaded models. Can be a NAS share mounted on the host, e.g. /mnt/nas/models.
KANAME_MODELS_DIR=./models
# Host port of the web UI
WEB_PORT=3000
# The user Kaname runs as (and owns the files it writes). Set these to the owner of your models
# folder, e.g. the uid/gid of a NAS share (`ls -ln /mnt/nas/models`). New, empty folders are set up
# for this user automatically.
PUID=1000
PGID=1000
# Image tag, e.g. 0.16.0 (default: latest). KANAME_IMAGE replaces the registry/name if you build or
# mirror the image yourself.
KANAME_VERSION=
KANAME_IMAGE=
# ---------------------------------------------------------------------------
# Optional
# ---------------------------------------------------------------------------
# Random secret for session cookies. Empty: generated on first start and kept in the data folder.
AUTH_SECRET=
# launch80.com publish token (comes with the launch80 Supporter role). Lets you publish a benchmark
# run as a public launch80 page, after a preview and an explicit confirmation. Stays on the server.
L80_TOKEN=
MAX_CONCURRENT_DOWNLOADS=1
# How often the worker checks every model on the Hub (still there? newer commit?); 0 disables it
UPDATE_CHECK_INTERVAL_HOURS=12
# 1 (default): hf downloads over plain HTTP, so progress can be measured from bytes on disk.
# 0: use Xet (chunk-level dedup on updates). Files over 50 GB always use Xet.
HF_HUB_DISABLE_XET=1
# Optional: pin an image version (default: latest)
# KANAME_VERSION=0.23.0
# Optional: user/group Kaname runs as (default 1000); set to the owner of your models folder
# PUID=1000
# PGID=1000
# Optional: launch80.com publish token, to publish benchmark runs
# L80_TOKEN=
+136
View File
@@ -4,6 +4,142 @@ All notable changes to this project are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); each milestone of
step 1 (Hugging Face downloader) is released as a minor version.
## [Unreleased]
## [0.23.0] - 2026-11-11
Kaname can run without any login: leave the `OIDC_*` settings empty and it opens straight into
the library.
**Upgrading:** `deploy/compose.yaml` and `.env.example` are simpler: folders, port and image are
written straight into `compose.yaml` (`./data`, `./models`, `3000`). `KANAME_DATA_DIR`,
`KANAME_MODELS_DIR`, `WEB_PORT` and `KANAME_IMAGE` are gone; if you set them, put those values into
`compose.yaml` instead. `KANAME_VERSION`, `PUID` and `PGID` still work.
### Added
- **Running without login:** leave `OIDC_ISSUER`, `OIDC_CLIENT_ID` and `OIDC_CLIENT_SECRET` empty
(or at the `.env.example` placeholders) and Kaname needs no login; anyone who can reach it can use
it. With all three set, OIDC login works as before. Only some of them set is an error on start.
`/api/v1` still requires API tokens either way.
### Changed
- Simpler `deploy/compose.yaml` (no YAML anchors or variables) and a short `.env.example`.
## [0.22.0] - 2026-11-11
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 &lt;token&gt;** 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
- **Reload a local model** (Files tab → **Reload**): reads the folder again, so files you added,
changed or removed and README.md edits show up right away. Every scan of the models folder (on its
schedule, or Rescan) now also brings local models' file lists up to date, not only their README.
## [0.20.0] - 2026-11-08
### Added
- **Local models have a model card again:** the folder's `README.md`. The worker reads it when it
scans the models folder (the web app can't see that folder), so edits show up after the next
scan. Relative images and links in it are left out.
## [0.19.0] - 2026-11-08
### Added
- **Import a folder that isn't on Hugging Face** (Add model → Found in the models folder → Import →
**Add as local model**): Kaname adds every file in the folder as it is, named after the folder.
Local models have no pinned commit, model card or model tree, and no Hub checks, updates or
downloads. Verify still checks that each file is there with the right size; deep verify isn't
offered because there are no Hub hashes to compare with.
## [0.18.0] - 2026-11-02
### Added
- **Your own background picture** (Settings → Appearance): upload an image and every page header
draws it as the dot matrix instead of *The Creation of Adam*; click the preview to choose the part
that stays in view. The browser turns it into dots, so only those are saved (not the image).
**Use the built-in painting** switches back.
## [0.17.0] - 2026-11-02
### Fixed
- **Several open tabs no longer stall Kaname.** Every tab with live progress kept one or two
connections open, and over plain HTTP a browser allows six per server: the third tab loaded
slowly and a fourth not at all. Live updates are now short requests, one poller per tab shared by
everything on the page, paused while the tab is in the background. The server also no longer
grows in memory while a tab stays open, and an idle page no longer redraws every 5 seconds.
### Changed
- **Lighter library page**: folders found in the models folder no longer bring their whole file
list (up to 5,000 entries each) into the page; **Import** loads it when you click it. Search and
filter counts are computed once per change instead of on every progress update.
- **Lighter benchmark lists**: the Benchmarks and Endpoints pages, a model's sidebar and the ⌘K
search load only what they show (headline numbers, the quality score), not every run's full
results; the list refreshed every 3 s during a run now sends a fraction of the data.
- **Less JavaScript per page** (10–29 KB gzipped less on every page): the dot painting's data is
loaded once and cached instead of being part of each page, the ⌘K search loads when you first
reach for it, and the endpoint pages no longer include database code. The painting is drawn once
per page view instead of twice, and at most once per frame while the window is resized.
- **Less disk activity**: the models folder scan writes only folders that changed (it rewrote
every found folder's file list each time, every 2 minutes by default), and download progress
no longer re-checks files that are already complete, which matters on network shares. A
benchmark's current step is written when it changes, not for every line BetterBench prints.
- **Fewer and smaller Hugging Face requests**: adding a model right after looking it up reuses the
file list it just fetched (a commit's files never change), the author's avatar loads alongside,
and the regular Hub check asks only for the commit SHA instead of the full model info.
- The **Model card** tab shows the page at once and the card when it arrives from the Hub.
- Database indexes for the queries the live view and the worker repeat every few seconds (the
migration runs by itself on start).
- **The image is 427 MB instead of 1.04 GB.** The web server runs as Next.js standalone output
(only the files it uses instead of all of `node_modules`), the worker is bundled, and neither the
build cache nor the downloaded archives end up in the image; build-only packages (`shadcn`,
`tw-animate-css`) are dev dependencies. The worker container used about 40 MB at idle instead of
about 190 MB in our test. Building the image again after a code change reuses npm's and Next's
caches (the Next build went from 30 to 12 seconds). Nothing changes in `compose.yaml` or `.env`.
## [0.16.0] - 2026-10-30
A new look, a search for everything (⌘K / Ctrl+K), removing single files, and an easier deployment
+35 -26
View File
@@ -9,43 +9,52 @@ FROM node AS build
ENV NEXT_TELEMETRY_DISABLED=1
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
# npm's download cache and Turbopack's build cache (.next/cache) are cache mounts: kept between
# builds on the same machine, never part of an image layer.
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build \
&& npm run build:worker \
&& npm prune --omit=dev
# Standalone output: the web server plus only the node_modules files it uses. The worker, migrate
# and sandbox scripts are bundled (esbuild) and only need @libsql/client from those.
RUN --mount=type=cache,target=/app/.next/cache \
NEXT_OUTPUT=standalone npm run build \
&& npm run build:worker
# --- downloads ---------------------------------------------------------------
# Pinned release archives, in their own stage: only what is installed from them reaches the image.
FROM python:3.13-slim-trixie AS downloads
# BetterBench (Apache-2.0), the benchmark run against endpoints. Not on PyPI: the release
# archive is pinned by checksum; flags used by src/worker/betterbench.ts are verified per version.
ARG BETTERBENCH_VERSION=0.6.1
ADD --checksum=sha256:f0a9d7fcc411c809ff87a0a22e2d76f6662b426431d2ae9fa273bc2644464db7 \
https://codeload.github.com/GGZ14/BetterBench/tar.gz/refs/tags/v${BETTERBENCH_VERSION} /downloads/betterbench.tar.gz
# L80 CLI (launch80.com): publishes a BetterBench run as a shareable page. Release archives pinned
# by checksum (from the release's checksums.txt); the per-architecture one is installed.
ARG L80_VERSION=0.4.0
ARG TARGETARCH
ADD --checksum=sha256:cde6b67dfb67b0ffddd56dfd384b8b24610573199287c59597359145310d9d23 \
https://github.com/launch80/L80-Skills/releases/download/v${L80_VERSION}/L80_linux_amd64.tar.gz /downloads/l80/amd64.tar.gz
ADD --checksum=sha256:bbd7c6cf35bcba2bf9a651f348581b691b36d5f7cdca9c8a11e8a1ac2fc3f5bc \
https://github.com/launch80/L80-Skills/releases/download/v${L80_VERSION}/L80_linux_arm64.tar.gz /downloads/l80/arm64.tar.gz
RUN mkdir -p /opt/l80 \
&& tar -xzf "/downloads/l80/${TARGETARCH:-amd64}.tar.gz" -C /opt/l80 L80 \
&& chmod 0755 /opt/l80/L80
# --- runtime -----------------------------------------------------------------
# Python base (provides the official `hf` CLI) plus the Node binary. The Python image already
# has CA certificates and libstdc++, so no apt.
FROM python:3.13-slim-trixie AS runtime
COPY --from=node /usr/local/bin/node /usr/local/bin/node
COPY --from=downloads /opt/l80/L80 /opt/l80/L80
# Pinned: the worker relies on the CLI's on-disk layout (see src/worker/hf-layout.ts);
# re-verify that before bumping.
ARG HF_HUB_VERSION=2.1.1
# BetterBench (Apache-2.0), the benchmark run against endpoints. Not on PyPI: the release
# archive is pinned by checksum; flags used by src/worker/betterbench.ts are verified per version.
ARG BETTERBENCH_VERSION=0.6.1
ADD --checksum=sha256:f0a9d7fcc411c809ff87a0a22e2d76f6662b426431d2ae9fa273bc2644464db7 \
https://codeload.github.com/GGZ14/BetterBench/tar.gz/refs/tags/v${BETTERBENCH_VERSION} /tmp/betterbench.tar.gz
# L80 CLI (launch80.com): publishes a BetterBench run as a shareable page. Release archives pinned
# by checksum (from the release's checksums.txt); the per-architecture one is installed.
ARG L80_VERSION=0.4.0
ARG TARGETARCH
ADD --checksum=sha256:cde6b67dfb67b0ffddd56dfd384b8b24610573199287c59597359145310d9d23 \
https://github.com/launch80/L80-Skills/releases/download/v${L80_VERSION}/L80_linux_amd64.tar.gz /tmp/l80/amd64.tar.gz
ADD --checksum=sha256:bbd7c6cf35bcba2bf9a651f348581b691b36d5f7cdca9c8a11e8a1ac2fc3f5bc \
https://github.com/launch80/L80-Skills/releases/download/v${L80_VERSION}/L80_linux_arm64.tar.gz /tmp/l80/arm64.tar.gz
RUN mkdir -p /opt/l80 \
&& tar -xzf "/tmp/l80/${TARGETARCH:-amd64}.tar.gz" -C /opt/l80 L80 \
&& chmod 0755 /opt/l80/L80 \
&& rm -rf /tmp/l80
RUN python -m venv /opt/hf \
RUN --mount=type=bind,from=downloads,source=/downloads/betterbench.tar.gz,target=/tmp/betterbench.tar.gz \
python -m venv /opt/hf \
&& /opt/hf/bin/pip install --no-cache-dir "huggingface_hub[hf_xet]==${HF_HUB_VERSION}" \
&& python -m venv /opt/betterbench \
&& /opt/betterbench/bin/pip install --no-cache-dir /tmp/betterbench.tar.gz \
&& rm -rf /root/.cache /tmp/betterbench.tar.gz \
&& rm -rf /root/.cache \
&& useradd --uid 1000 --create-home --shell /usr/sbin/nologin app \
&& mkdir -p /data /models /sandbox \
&& chown app:app /data /models \
@@ -65,9 +74,9 @@ ENV PATH=/opt/hf/bin:$PATH \
L80_BIN=/opt/l80/L80
WORKDIR /app
COPY --from=build --chown=app:app /app/package.json /app/next.config.ts ./
COPY --from=build --chown=app:app /app/node_modules ./node_modules
COPY --from=build --chown=app:app /app/.next ./.next
# server.js, package.json, the traced node_modules (also what dist/ needs: @libsql/client) and .next.
COPY --from=build --chown=app:app /app/.next/standalone ./
COPY --from=build --chown=app:app /app/.next/static ./.next/static
COPY --from=build --chown=app:app /app/dist ./dist
COPY --from=build --chown=app:app /app/drizzle ./drizzle
COPY --chmod=755 docker-entrypoint.sh docker-healthcheck.sh /usr/local/bin/
+133 -13
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="docs/banner.png" alt="Kaname: self-hosted model manager for Hugging Face" width="100%" />
<img src="docs/banner-0.16.png" alt="Kaname: download models from Hugging Face and benchmark the servers that run them" width="100%" />
</p>
**Kaname** (要, "the pivot") is a self-hosted web app for downloading local LLMs from Hugging Face
@@ -17,31 +17,144 @@ 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.
## Install
You need a Linux server with Docker and Compose, and an OIDC provider for the login (e.g.
You need a Linux server with Docker and Compose, and optionally an OIDC provider for the login (e.g.
[Pocket ID](https://pocket-id.org), Authelia, Authentik, Keycloak).
**1. Get the compose file and the config template**
**1. Create a folder with two files**
```bash
mkdir kaname && cd kaname
```
`compose.yaml` (same as [`deploy/compose.yaml`](deploy/compose.yaml)):
```yaml
# Kaname: put this file and a filled-in .env (from .env.example) in one folder, then
# docker compose up -d
name: kaname
services:
web:
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
env_file: .env
ports:
- "3000:3000"
volumes:
- ./data:/data
restart: unless-stopped
worker:
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
command: worker
env_file: .env
environment:
SANDBOX_DIR: /sandbox
volumes:
- ./data:/data
- ./models:/models # where models are downloaded to, e.g. /mnt/models
- sandbox:/sandbox
restart: unless-stopped
# Runs the coding answers of the quality eval (Python written by the model under test), locked
# down: no network, no secrets, read-only. Optional: without it the eval skips the coding part.
sandbox:
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
command: sandbox
user: "65534:65534"
network_mode: none
read_only: true
tmpfs:
- /tmp:size=64m,mode=1777
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
mem_limit: 512m
pids_limit: 64
cpus: 1
volumes:
- sandbox:/sandbox
depends_on: [worker]
restart: unless-stopped
volumes:
sandbox:
```
The database goes to `./data` and models to `./models` next to this file. To keep models somewhere
else (e.g. a NAS share mounted on the host), change the worker's `./models:/models` line, e.g. to
`/mnt/models:/models`. To use another port, change the left side of `"3000:3000"`.
`.env` (same as [`.env.example`](.env.example)):
```env
# Kaname settings: copy to .env next to compose.yaml and fill in.
# All options: https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Configuration
# Read-only Hugging Face token (needed for gated repos, higher rate limits)
HF_TOKEN=
MAX_CONCURRENT_DOWNLOADS=1
UPDATE_CHECK_INTERVAL_HOURS=12
# Login. AUTH_URL is the address you open Kaname at; register
# <AUTH_URL>/api/auth/callback/pocket-id as redirect URI with your OIDC provider.
# AUTH_SECRET: any random string (openssl rand -base64 32); empty = generated on first start.
AUTH_SECRET=
AUTH_URL=http://localhost:3000
OIDC_ISSUER=https://auth.example.com
OIDC_CLIENT_ID=
OIDC_CLIENT_SECRET=
# Optional, comma-separated: only these groups may log in
OIDC_ALLOWED_GROUPS=
# Optional: pin an image version (default: latest)
# KANAME_VERSION=0.23.0
# Optional: user/group Kaname runs as (default 1000); set to the owner of your models folder
# PUID=1000
# PGID=1000
# Optional: launch80.com publish token, to publish benchmark runs
# L80_TOKEN=
```
Or download both instead of copying:
```bash
curl -fsSLo compose.yaml https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/branch/main/deploy/compose.yaml
curl -fsSLo .env https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/branch/main/.env.example
```
**2. Create an OIDC client** in your identity provider with the redirect URI
**2. Create an OIDC client** (optional) in your identity provider with the redirect URI
`<AUTH_URL>/api/auth/callback/pocket-id`, e.g. `http://192.168.1.10:3000/api/auth/callback/pocket-id`
(the path says `pocket-id` whatever provider you use). Request the `groups` scope if you want to
restrict access by group.
Without OIDC, skip this step and leave the `OIDC_*` lines empty: Kaname then runs without any
login, and anyone who can reach it can use it. Only do that on a trusted network (or behind a proxy
that does the login). Setting only some of the `OIDC_*` values is an error, so a typo never turns
the login off.
**3. Fill in `.env`:** `AUTH_URL` (the address you open in the browser), `OIDC_ISSUER`,
`OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, and ideally a read-only `HF_TOKEN`. Everything else has
defaults. Models go to `./models` and the database to `./data` next to the compose file; point
`KANAME_MODELS_DIR` at another folder (e.g. a NAS share mounted on the host) if you like.
`OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, and ideally a read-only `HF_TOKEN`. Everything else can
stay as it is. A filled-in example:
```env
HF_TOKEN=hf_...
MAX_CONCURRENT_DOWNLOADS=1
UPDATE_CHECK_INTERVAL_HOURS=12
AUTH_SECRET=
AUTH_URL=http://192.168.1.10:3000
OIDC_ISSUER=https://auth.example.com
OIDC_CLIENT_ID=...
OIDC_CLIENT_SECRET=...
OIDC_ALLOWED_GROUPS=admin
```
**4. Start**
@@ -53,11 +166,11 @@ Open your `AUTH_URL`, sign in, click **Add model**. That's it.
Kaname creates and takes over `./data` itself, and an empty models folder too. It runs as uid/gid
1000 by default; if your models folder already holds files that belong to another user (common for
NAS shares), set `PUID`/`PGID` in `.env` to that owner (`ls -ln /path/to/models`). Kaname never
NAS shares), add `PUID`/`PGID` to `.env` for that owner (`ls -ln /path/to/models`). Kaname never
changes the ownership of a models folder that has files in it.
**Updating:** `docker compose pull && docker compose up -d`. To stay on a version, set e.g.
`KANAME_VERSION=0.16.0` in `.env`. The running version is shown next to the app name. Read the
`KANAME_VERSION=0.23.0` in `.env`. The running version is shown next to the app name. Read the
[changelog](CHANGELOG.md) before jumping minor versions: it says when the compose file changed.
### The image
@@ -67,8 +180,8 @@ changes the ownership of a models folder that has files in it.
| Tag | What it is |
| --- | --- |
| `latest` | the newest release |
| `0.16` | the newest 0.16.x release |
| `0.16.0` | exactly that release |
| `0.23` | the newest 0.23.x release |
| `0.23.0` | exactly that release |
It is built for x86-64 (`linux/amd64`). One image serves all three services (`web`, `worker`,
`sandbox`); the compose file picks the role. To build it yourself (e.g. for ARM) from this
@@ -79,7 +192,7 @@ git clone https://git.linxweiler.xyz/pascallinxweiler/Kaname.git && cd Kaname
docker build -t kaname:mine --build-arg APP_VERSION=$(git describe --tags) .
```
and set `KANAME_IMAGE=kaname` and `KANAME_VERSION=mine` in `.env`.
and change the three `image:` lines in `compose.yaml` to `kaname:mine`.
## Configuration
@@ -133,6 +246,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 &lt;token&gt;** 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
@@ -143,7 +262,8 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
Three containers from the same image; web and worker share one SQLite database:
- **web:** Next.js UI and API, OIDC login (Auth.js); live updates via Server-Sent Events.
- **web:** Next.js UI and API, OIDC login (Auth.js); live updates by polling once a second from
the visible tab (paused in background tabs, so any number of tabs can stay open).
- **worker:** runs the download queue, spawns `hf download --revision <sha> --include <files>`, and
measures progress from bytes on disk; runs benchmarks against endpoints (BetterBench, the quality
eval). Only one worker runs at a time.
+26 -25
View File
@@ -1,50 +1,51 @@
# Builds the image from this checkout. For the server use deploy/compose.yaml (released image).
name: kaname
x-app: &app
image: kaname:local
build: .
env_file: .env
# Container paths win over local-dev paths in .env.
environment:
DATABASE_URL: file:/data/app.db
MODELS_DIR: /models
HF_HOME: /data/hf-home
restart: unless-stopped
services:
web:
build: .
image: kaname:local
env_file: .env
environment:
DATABASE_URL: file:/data/app.db # container paths win over local-dev paths in .env
MODELS_DIR: /models
ports:
- "3000:3000"
volumes:
- data:/data
restart: unless-stopped
worker:
<<: *app
image: kaname:local
command: worker
env_file: .env
environment:
DATABASE_URL: file:/data/app.db
MODELS_DIR: /models
HF_HOME: /data/hf-home
SANDBOX_DIR: /sandbox
volumes: [data:/data, models:/models, sandbox:/sandbox]
volumes:
- data:/data
- models:/models
- sandbox:/sandbox
depends_on: [web]
restart: unless-stopped
web:
<<: *app
ports: ["${WEB_PORT:-3000}:3000"]
volumes: [data:/data]
# Runs the quality eval's coding answers (Python written by the model under test) with no
# network, a read-only root, no capabilities, small limits and an unprivileged user. It shares only
# the exchange folder with the worker. Optional: without it the quality eval skips coding.
sandbox:
image: kaname:local
command: sandbox
user: "65534:65534"
depends_on: [worker]
network_mode: none
read_only: true
tmpfs: ["/tmp:size=64m,mode=1777"]
tmpfs:
- /tmp:size=64m,mode=1777
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
mem_limit: 512m
pids_limit: 64
cpus: 1
volumes: [sandbox:/sandbox]
volumes:
- sandbox:/sandbox
depends_on: [worker]
restart: unless-stopped
volumes:
+19 -20
View File
@@ -1,49 +1,48 @@
# Kaname: put this file and a filled-in .env (from .env.example) in one folder, then
# docker compose up -d
# The data and models folders are created next to this file unless .env points elsewhere.
name: kaname
x-kaname: &kaname
# Public image, no login needed. Pin a version with KANAME_VERSION=0.15.2 in .env.
image: ${KANAME_IMAGE:-git.linxweiler.xyz/pascallinxweiler/kaname}:${KANAME_VERSION:-latest}
restart: unless-stopped
services:
web:
<<: *kaname
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
env_file: .env
ports: ["${WEB_PORT:-3000}:3000"]
ports:
- "3000:3000"
volumes:
- ${KANAME_DATA_DIR:-./data}:/data # SQLite database and results, shared with the worker (local disk, not NFS)
- ./data:/data
restart: unless-stopped
worker:
<<: *kaname
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
command: worker
env_file: .env
environment:
SANDBOX_DIR: /sandbox
volumes:
- ${KANAME_DATA_DIR:-./data}:/data
- ${KANAME_MODELS_DIR:-./models}:/models # downloaded models (a NAS share mounted on the host works)
- sandbox:/sandbox # exchange folder with the code sandbox
- ./data:/data
- ./models:/models # where models are downloaded to, e.g. /mnt/models
- sandbox:/sandbox
restart: unless-stopped
# Runs the quality eval's coding answers (Python written by the model under test): no network, a
# read-only root, no capabilities, small limits, an unprivileged user, and only the exchange
# folder shared with the worker. No .env (no secrets). Optional: without it the eval skips coding.
# Runs the coding answers of the quality eval (Python written by the model under test), locked
# down: no network, no secrets, read-only. Optional: without it the eval skips the coding part.
sandbox:
<<: *kaname
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
command: sandbox
user: "65534:65534"
depends_on: [worker]
network_mode: none
read_only: true
tmpfs: ["/tmp:size=64m,mode=1777"]
tmpfs:
- /tmp:size=64m,mode=1777
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
mem_limit: 512m
pids_limit: 64
cpus: 1
volumes: [sandbox:/sandbox]
volumes:
- sandbox:/sandbox
depends_on: [worker]
restart: unless-stopped
volumes:
sandbox:
+1 -1
View File
@@ -55,7 +55,7 @@ case "$role" in
esac
case "$role" in
web) exec node_modules/.bin/next start ;;
web) exec node server.js ;; # Next.js standalone server (see Dockerfile)
worker) exec node dist/worker.mjs ;;
sandbox)
# It runs code written by the model under test: never as root (compose gives it `user:`).
+253
View File
@@ -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/<modelId>"
```
`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":"<sha from the lookup>","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/<jobId>?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/<modelId>/verify" # presence and size, takes seconds
kaname -X POST "$KANAME_URL/api/v1/models/<modelId>/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/<modelId>/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/<modelId>/tags" -d '{"name":"coding"}' # add (creates the tag if it's new)
kaname -X DELETE "$KANAME_URL/api/v1/models/<modelId>/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/<jobId>/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/<jobId>?wait=900"`, then
report that it's done, or the progress and ETA.
+3
View File
@@ -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" "$@"
+330
View File
@@ -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 (or is open, if you run Kaname without 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.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 705 KiB

+2
View File
@@ -0,0 +1,2 @@
CREATE INDEX `benchmark_runs_state_idx` ON `benchmark_runs` (`state`,`created_at`);--> statement-breakpoint
CREATE INDEX `jobs_finished_idx` ON `jobs` (`finished_at`);
+1
View File
@@ -0,0 +1 @@
ALTER TABLE `models` ADD `source` text DEFAULT 'hub' NOT NULL;
+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE `local_folders` ADD `readme` text;--> statement-breakpoint
ALTER TABLE `models` ADD `local_readme` text;
+31
View File
@@ -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;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+28
View File
@@ -169,6 +169,34 @@
"when": 1793115558680,
"tag": "0023_scan_schedule",
"breakpoints": true
},
{
"idx": 24,
"version": "6",
"when": 1793567055573,
"tag": "0024_polling_indexes",
"breakpoints": true
},
{
"idx": 25,
"version": "6",
"when": 1794093022425,
"tag": "0025_local_models",
"breakpoints": true
},
{
"idx": 26,
"version": "6",
"when": 1794093954553,
"tag": "0026_local_readme",
"breakpoints": true
},
{
"idx": 27,
"version": "6",
"when": 1794429640033,
"tag": "0027_api_tokens",
"breakpoints": true
}
]
}
+21
View File
@@ -15,6 +15,27 @@ const eslintConfig = defineConfig([
// Bundled worker output
"dist/**",
]),
// A value import from the schema in a client component puts drizzle-orm and every table
// definition into the browser bundle. Enums are in @/lib/db/enums; types are fine. Pages, layouts
// and route handlers run on the server only.
{
files: ["src/components/**/*.{ts,tsx}", "src/hooks/**/*.{ts,tsx}", "src/app/**/*.{ts,tsx}"],
ignores: ["src/app/**/page.tsx", "src/app/**/layout.tsx", "src/app/**/route.ts"],
rules: {
"@typescript-eslint/no-restricted-imports": [
"error",
{
paths: [
{
name: "@/lib/db/schema",
allowTypeImports: true,
message: "In client code this bundles drizzle-orm and every table. Import enums from @/lib/db/enums.",
},
],
},
],
},
},
]);
export default eslintConfig;
+8
View File
@@ -3,6 +3,14 @@ import type { NextConfig } from "next";
const nextConfig: NextConfig = {
// Native SQLite driver: load from node_modules at runtime instead of bundling.
serverExternalPackages: ["@libsql/client", "libsql"],
// The Docker image runs the standalone server: only the files the server needs instead of all of
// node_modules (see Dockerfile). Local `next build` / `next start` stay as they are.
output: process.env.NEXT_OUTPUT === "standalone" ? "standalone" : undefined,
// Nothing uses next/image (model cards show the Hub's images as they are). With the optimizer off
// (/_next/image answers 404), sharp and its native libvips (28 MB) stay out of the standalone
// output; "next-server" is the key Next applies to its own server's trace.
images: { unoptimized: true },
outputFileTracingExcludes: { "next-server": ["**/node_modules/sharp/**/*", "**/node_modules/@img/**/*"] },
};
export default nextConfig;
+389 -5
View File
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "kaname",
"version": "0.16.0",
"version": "0.23.0",
"private": true,
"scripts": {
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
@@ -14,7 +14,7 @@
"db:generate": "drizzle-kit generate",
"db:migrate": "dotenv -e .env -- tsx src/lib/db/migrate-cli.ts",
"test": "tsx --conditions=react-server --test \"src/**/*.test.ts\"",
"build:worker": "esbuild src/worker/index.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/worker.mjs && esbuild src/lib/db/migrate-cli.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/migrate.mjs && esbuild src/sandbox/index.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/sandbox.mjs"
"build:worker": "esbuild src/worker/index.ts --bundle --platform=node --target=node24 --format=esm --external:@libsql/client --external:libsql --outfile=dist/worker.mjs && esbuild src/lib/db/migrate-cli.ts --bundle --platform=node --target=node24 --format=esm --external:@libsql/client --external:libsql --outfile=dist/migrate.mjs && esbuild src/sandbox/index.ts --bundle --platform=node --target=node24 --format=esm --external:@libsql/client --external:libsql --outfile=dist/sandbox.mjs"
},
"dependencies": {
"@base-ui/react": "^1.8.0",
@@ -33,9 +33,7 @@
"rehype-sanitize": "^6.0.0",
"remark-gfm": "^4.0.1",
"server-only": "^0.0.1",
"shadcn": "^4.21.1",
"sonner": "^2.0.8",
"tw-animate-css": "^1.4.0",
"ulid": "^3.0.2",
"zod": "^4.6.5"
},
@@ -51,8 +49,10 @@
"esbuild": "^0.25.12",
"eslint": "^9",
"eslint-config-next": "16.3.8",
"shadcn": "^4.21.1",
"tailwindcss": "^4",
"tsx": "^4.23.15",
"tw-animate-css": "^1.4.0",
"typescript": "^5"
}
}
+29 -16
View File
@@ -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";
@@ -22,17 +24,22 @@ export function DownloadCard({
modelId,
status,
hubMissing,
local = false,
}: {
modelId: string;
status: ModelStatus;
/** The repo or pinned commit is gone from the Hub; no new downloads. */
hubMissing: boolean;
/** A local model (no Hub repo): nothing to download or repair, no hashes to deep-verify against. */
local?: boolean;
}) {
const { snapshot } = useLive({ model: modelId });
const [busy, setBusy] = useState(false);
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");
@@ -58,15 +65,17 @@ export function DownloadCard({
: latest?.state === "failed" && latest.kind === "download"
? "Retry"
: "Download missing";
const canDownload = !open && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
const canVerify = !open && !neverRan && status !== "deleting" && !!snapshot;
const needsRepair = !open && !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 = "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.";
let hint = local ? "A local folder: Kaname keeps its files as they are." : "Downloads the selected files at the pinned commit.";
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.";
else if (local && (verifyProblems > 0 || status === "incomplete")) hint = "Some files are missing or changed. A local model can't be repaired from the Hub.";
else if (status === "ready") hint = "All selected files are present.";
const showProgress =
@@ -77,13 +86,15 @@ export function DownloadCard({
<div className="flex items-center justify-between gap-2">
<h3 className="flex items-center gap-1.5 text-sm font-semibold">
<DownloadIcon className="size-4 text-muted-foreground" />
{open ? jobLabel(open) : "Download"}
{open ? jobLabel(open) : local ? "Files" : "Download"}
</h3>
{latest && <JobStateBadge job={latest} />}
</div>
<p className="text-xs text-muted-foreground">{hint}</p>
{showProgress && <JobProgress job={latest} compact />}
{pending && <ApprovalBar job={pending} onRemoved={() => router.push("/")} />}
{showProgress && !pending && <JobProgress job={latest} compact />}
{latest?.state === "failed" && latest.errorMessage && (
<pre className="max-h-40 overflow-auto rounded-md bg-destructive/10 px-2.5 py-2 text-xs whitespace-pre-wrap text-destructive">
@@ -145,15 +156,17 @@ export function DownloadCard({
<ShieldCheckIcon />
Verify
</Button>
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => run(() => startVerify(modelId, true))}
title="Hash every file and compare with the Hub (slow: reads every byte)"
>
Deep verify
</Button>
{!local && (
<Button
size="sm"
variant="ghost"
disabled={busy}
onClick={() => run(() => startVerify(modelId, true))}
title="Hash every file and compare with the Hub (slow: reads every byte)"
>
Deep verify
</Button>
)}
</>
)}
</>
+7 -2
View File
@@ -13,6 +13,7 @@ import { useRecommended } from "@/hooks/use-recommended";
import { groupSplitFiles } from "@/lib/file-groups";
import { formatBytes, percent, shortSha } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { ReloadButton } from "./reload-button";
type Candidate = { path: string; size: number };
@@ -32,6 +33,7 @@ export function FilesHeader({
freeBytes,
busy,
hubMissing,
local = false,
}: {
modelId: string;
sha: string;
@@ -47,6 +49,8 @@ export function FilesHeader({
busy: boolean;
/** The repo or pinned commit is gone from the Hub; nothing more can be downloaded. */
hubMissing: boolean;
/** A local model: "Reload" reads the folder again instead of "Download more". */
local?: boolean;
}) {
const router = useRouter();
const [open, setOpen] = useState(false);
@@ -121,14 +125,15 @@ export function FilesHeader({
</span>
<span className="text-muted-foreground">
{" "}
· {formatBytes(totalBytes)} · commit {shortSha(sha)}
· {formatBytes(totalBytes)} · {sha ? `commit ${shortSha(sha)}` : "local folder"}
</span>
</span>
<div className="flex items-center gap-3">
<span className="text-muted-foreground">
{localCount} of {selectedCount} on disk · {formatBytes(localBytes)}
</span>
{candidates.length > 0 && !hubMissing && (
{local && <ReloadButton />}
{!local && candidates.length > 0 && !hubMissing && (
<Button
size="sm"
variant={open ? "outline" : "default"}
+8 -3
View File
@@ -68,7 +68,7 @@ function entryState(e: Entry): { state: ModelFileState; label: string } {
const isLocal = (e: Entry) => e.parts.every((p) => p.state === "present" || p.state === "verified");
function Row({ entry, href, muted, showState, action }: { entry: Entry; href: string; muted?: boolean; showState: boolean; action?: React.ReactNode }) {
function Row({ entry, href, muted, showState, action }: { entry: Entry; href?: string; muted?: boolean; showState: boolean; action?: React.ReactNode }) {
const { state: stateKey, label } = entryState(entry);
const state = STATE[stateKey];
const split = entry.totalParts > 1;
@@ -76,8 +76,8 @@ function Row({ entry, href, muted, showState, action }: { entry: Entry; href: st
<li className="flex items-center pr-3">
<a
href={href}
target="_blank"
rel="noreferrer"
target={href ? "_blank" : undefined}
rel={href ? "noreferrer" : undefined}
title={split ? entry.parts.map((p) => p.path).join("\n") : undefined}
className={cn(
// Fixed status column so sizes line up between selected and unselected rows.
@@ -125,6 +125,7 @@ export function FilesTab({
freeBytes,
busy,
hubMissing,
local = false,
}: {
modelId: string;
repoId: string;
@@ -134,10 +135,13 @@ export function FilesTab({
freeBytes: number | null;
busy: boolean;
hubMissing: boolean;
/** A local model (no Hub repo): files don't link anywhere. */
local?: boolean;
}) {
const hub = `https://huggingface.co/${repoId}`;
// Split files link to their folder (all parts), single files to the file itself.
const href = (e: Entry) => {
if (local) return undefined;
const dir = e.path.includes("/") ? e.path.slice(0, e.path.lastIndexOf("/")) : null;
return e.totalParts > 1 && dir ? `${hub}/tree/${sha}/${dir}` : `${hub}/blob/${sha}/${e.parts[0].path}`;
};
@@ -161,6 +165,7 @@ export function FilesTab({
freeBytes={freeBytes}
busy={busy}
hubMissing={hubMissing}
local={local}
/>
<ul className="divide-y">
+84 -3
View File
@@ -1,7 +1,12 @@
import "server-only";
import { ExternalLinkIcon } from "lucide-react";
import ReactMarkdown, { defaultUrlTransform } from "react-markdown";
import rehypeRaw from "rehype-raw";
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
import remarkGfm from "remark-gfm";
import { Skeleton } from "@/components/ui/skeleton";
import { shortSha } from "@/lib/format";
import { fetchModelCard } from "@/lib/hub/client";
// Model cards mix Markdown and raw HTML. Parse the HTML (rehype-raw), then sanitize it: no scripts,
// styles or event handlers, only the tags/attributes GitHub-style READMEs normally use.
@@ -17,9 +22,84 @@ const schema = {
},
};
/** Renders a repo's README like the Hub: relative links/images point at the pinned commit. */
export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId: string; sha: string }) {
const base = `https://huggingface.co/${repoId}`;
/**
* The Model card tab: the README at the pinned commit, fetched from the Hub (cached per commit).
* Rendered inside a Suspense boundary, so the rest of the page doesn't wait for the Hub.
*/
export async function ModelCardSection({ repoId, sha }: { repoId: string; sha: string }) {
const hub = `https://huggingface.co/${repoId}`;
const card = await fetchModelCard(repoId, sha).catch(() => undefined);
if (!card) {
return (
<p className="text-sm text-muted-foreground">
{card === null ? "This repository has no model card." : "The model card could not be loaded."}{" "}
<a href={hub} target="_blank" rel="noreferrer" className="underline">
Open on Hugging Face
</a>
</p>
);
}
return (
<>
<ModelCard markdown={card} repoId={repoId} sha={sha} />
<div className="mt-6 flex justify-end">
<a
href={`${hub}/blob/${sha}/README.md`}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
>
README.md @ {shortSha(sha)}
<ExternalLinkIcon className="size-3" />
</a>
</div>
</>
);
}
/**
* The Model card tab of a local model: the folder's README.md, as the worker last read it. Relative
* images and links are dropped: the web app can't serve files from the models folder.
*/
export function LocalModelCardSection({ markdown, localPath }: { markdown: string | null; localPath: string }) {
if (!markdown) {
return (
<p className="text-sm text-muted-foreground">
This folder has no README.md. Add one to <code className="font-mono">{localPath}</code> and it shows up here after the
next scan of the models folder, or right away with Reload on the Files tab.
</p>
);
}
return (
<>
<ModelCard markdown={markdown} />
<p className="mt-6 text-right text-xs text-muted-foreground">
README.md in <code className="font-mono">{localPath}</code>, as of the last scan
</p>
</>
);
}
export function ModelCardSkeleton() {
return (
<div className="flex flex-col gap-3" aria-busy="true" aria-label="Loading the model card">
<Skeleton className="h-7 w-2/5" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-11/12" />
<Skeleton className="h-4 w-4/5" />
<Skeleton className="mt-3 h-5 w-1/4" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
</div>
);
}
/**
* Renders a repo's README like the Hub: relative links/images point at the pinned commit. Without a
* repo (a local model's README) they are dropped.
*/
export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId?: string; sha?: string }) {
const base = repoId ? `https://huggingface.co/${repoId}` : null;
return (
<article className="prose prose-sm max-w-none dark:prose-invert prose-headings:scroll-mt-20 prose-img:inline-block prose-img:my-1 prose-pre:bg-muted prose-pre:text-foreground prose-table:text-xs">
<ReactMarkdown
@@ -29,6 +109,7 @@ export function ModelCard({ markdown, repoId, sha }: { markdown: string; repoId:
const safe = defaultUrlTransform(url);
if (!safe || safe.startsWith("#") || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(safe)) return safe;
// Relative path inside the repo: images from /resolve, links to /blob, both at the pinned SHA.
if (!base) return null;
const path = safe.replace(/^\.?\//, "");
return key === "src" ? `${base}/resolve/${sha}/${path}` : `${base}/blob/${sha}/${path}`;
}}
+45 -32
View File
@@ -2,7 +2,6 @@ import {
ArrowDownIcon,
BoxIcon,
CpuIcon,
ExternalLinkIcon,
FileTextIcon,
FolderIcon,
HistoryIcon,
@@ -17,6 +16,7 @@ import {
import type { Metadata } from "next";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { Suspense } from "react";
import { CopyButton } from "@/components/copy-button";
import { BenchmarkStateBadge } from "@/components/benchmark-state";
import { PageHero } from "@/components/hero/page-hero";
@@ -26,8 +26,7 @@ import { ModelStatusBadge } from "@/components/model-status-badge";
import { cn } from "@/lib/utils";
import { formatBytes, shortSha } from "@/lib/format";
import { listBenchmarks } from "@/lib/benchmarks";
import { headline, targetName } from "@/lib/benchmark-view";
import { fetchModelCard } from "@/lib/hub/client";
import { targetName } from "@/lib/benchmark-view";
import { modelFamilies } from "@/lib/hub/metadata";
import { listModelJobs } from "@/lib/jobs";
import { getModelByRepo, relatedModels } from "@/lib/library";
@@ -39,9 +38,10 @@ import { DownloadCard } from "./download-card";
import { FilesTab } from "./files-tab";
import { HubCheckButton } from "./hub-check";
import { JobsTab } from "./jobs-tab";
import { ModelCard } from "./model-card";
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";
@@ -94,6 +94,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
const { model, files } = data;
if (model.repoId !== `${org}/${repo}`) redirect(`/${model.repoId}`); // canonical spelling
// A local model has no Hub repo: no commit, Hub checks or model tree; its README is the model card.
const local = model.source === "local";
const tab: TabId = TABS.some((t) => t.id === sp.tab) ? (sp.tab as TabId) : "files";
const [author, name] = model.repoId.split("/");
const hub = `https://huggingface.co/${model.repoId}`;
@@ -101,13 +103,13 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
const hubTags = model.hubTags ?? [];
const hubMissing = model.hubState === "repo_missing" || model.hubState === "commit_missing";
const [tags, related, card, worker, recentJobs, runs] = await Promise.all([
// The model card (a Hub request) isn't awaited here: it streams in behind its Suspense boundary.
const [tags, related, worker, recentJobs, runs] = await Promise.all([
modelTagList(model.id),
relatedModels(model.id, baseModels),
tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined),
getWorkerStatus(),
listModelJobs(model.id, 1),
listBenchmarks({ modelId: model.id }),
listBenchmarks({ modelId: model.id }, { limit: 5 }), // the sidebar shows 5 and links to all
]);
const update =
!hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha
@@ -139,7 +141,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
</Link>
<span className="font-normal text-muted-foreground">/</span>
<span className="break-all">{name}</span>
<CopyButton value={model.repoId} label="Copy repo ID" />
<CopyButton value={model.repoId} label={local ? "Copy name" : "Copy repo ID"} />
{!local && (
<a
href={hub}
target="_blank"
@@ -150,7 +153,17 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
>
🤗
</a>
)}
<ModelStatusBadge status={model.status} />
<RequestedByBadge name={model.requestedBy} />
{local && (
<span
title="A folder in the models folder without a Hugging Face repo"
className="inline-flex h-5 items-center rounded-4xl border border-foreground/15 bg-background/80 px-2 text-xs font-medium text-muted-foreground"
>
local
</span>
)}
<HubStateBadge state={model.hubState} />
{update && (
<span className="inline-flex h-5 items-center rounded-4xl border border-sky-500/30 bg-sky-500/10 px-2 text-xs font-medium text-sky-700 dark:text-sky-300">
@@ -253,28 +266,12 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
{tab === "card" && (
<div className="p-5 sm:p-6">
{card ? (
<>
<ModelCard markdown={card} repoId={model.repoId} sha={model.pinnedSha} />
<div className="mt-6 flex justify-end">
<a
href={`${hub}/blob/${model.pinnedSha}/README.md`}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
>
README.md @ {shortSha(model.pinnedSha)}
<ExternalLinkIcon className="size-3" />
</a>
</div>
</>
{local ? (
<LocalModelCardSection markdown={model.localReadme} localPath={model.localPath} />
) : (
<p className="text-sm text-muted-foreground">
{card === null ? "This repository has no model card." : "The model card could not be loaded."}{" "}
<a href={hub} target="_blank" rel="noreferrer" className="underline">
Open on Hugging Face
</a>
</p>
<Suspense fallback={<ModelCardSkeleton />}>
<ModelCardSection repoId={model.repoId} sha={model.pinnedSha} />
</Suspense>
)}
</div>
)}
@@ -288,6 +285,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
freeBytes={worker.online ? worker.modelsDirFreeBytes : null}
busy={model.status === "downloading"}
hubMissing={hubMissing}
local={local}
/>
)}
{tab === "jobs" && (
@@ -299,20 +297,20 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
<aside className="flex flex-col gap-4">
<SideCard>
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} />
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} local={local} />
</SideCard>
{runs.length > 0 && (
<SideCard title="Benchmarks" icon={GaugeIcon}>
<div className="flex flex-col gap-1">
{runs.slice(0, 5).map((r) => {
const h = headline(r.summary);
const h = r.headline;
return (
<Link key={r.id} href={`/benchmarks/${r.id}`} className="flex items-center justify-between gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted">
<span className="flex min-w-0 flex-col">
<span className="truncate font-medium">{r.label ?? targetName(r.snapshot)}</span>
<span className="truncate text-xs text-muted-foreground">
{r.kind === "eval" ? (r.quality?.score != null ? `quality ${r.quality.score}%` : "quality eval") : h.decode != null ? `${h.decode.toFixed(1)} t/s decode` : r.kind === "ab" ? "A/B" : "run"}
{r.kind === "eval" ? (r.qualityScore != null ? `quality ${r.qualityScore}%` : "quality eval") : h.decode != null ? `${h.decode.toFixed(1)} t/s decode` : r.kind === "ab" ? "A/B" : "run"}
</span>
</span>
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
@@ -332,6 +330,13 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
<dd>{quants.length > 0 ? quants.join(", ") : `${selected.length} file${selected.length === 1 ? "" : "s"}`}</dd>
<dt className="text-muted-foreground">Size</dt>
<dd className="tabular-nums">{formatBytes(selectedBytes)}</dd>
{local ? (
<>
<dt className="text-muted-foreground">Source</dt>
<dd>Local folder, no Hugging Face repo</dd>
</>
) : (
<>
<dt className="text-muted-foreground">Commit</dt>
<dd className="flex items-center gap-1">
<a href={`${hub}/commit/${model.pinnedSha}`} target="_blank" rel="noreferrer" className="font-mono hover:underline" title={model.pinnedSha}>
@@ -344,6 +349,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
<dd>
<LocalTime value={model.downloadedAt} />
</dd>
</>
)}
<dt className="text-muted-foreground">Path</dt>
<dd className="flex min-w-0 items-center gap-1">
<span className="truncate font-mono text-xs" title={`$MODELS_DIR/${model.localPath}`}>
@@ -363,6 +370,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
<dd className="flex flex-col font-mono text-xs">{model.excludePatterns.map((p) => <span key={p} className="break-all">{p}</span>)}</dd>
</>
)}
{!local && (
<>
<dt className="text-muted-foreground">On the Hub</dt>
<dd className="flex flex-col items-start gap-0.5">
<span className={cn(hubMissing && "text-amber-700 dark:text-amber-300", update && "text-sky-700 dark:text-sky-300")}>
@@ -384,6 +393,8 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
{model.lastCheckError && <span className="text-xs text-amber-700 dark:text-amber-300">{model.lastCheckError}</span>}
<HubCheckButton modelId={model.id} />
</dd>
</>
)}
<dt className="text-muted-foreground">Added</dt>
<dd>
<LocalTime value={model.createdAt} />
@@ -391,6 +402,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
</dl>
</SideCard>
{!local && (
<SideCard title="Model tree" icon={SparklesIcon}>
<ModelTree
repoId={model.repoId}
@@ -410,6 +422,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
</div>
)}
</SideCard>
)}
</aside>
</div>
</PageHero>
@@ -0,0 +1,54 @@
"use client";
import { RefreshCwIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
/** The worker picks a scan request up with its next heartbeat (every 5 s); a big models folder takes longer. */
const TIMEOUT_MS = 90_000;
const POLL_MS = 1_500;
/**
* Local models: read the folder again (files and README). Asks the worker for a scan of the models
* folder and waits until it has finished, then reloads the page.
*/
export function ReloadButton() {
const router = useRouter();
const [busy, setBusy] = useState(false);
async function reload() {
setBusy(true);
try {
const res = await fetch("/api/local-folders/scan", { method: "POST" });
const body = await res.json().catch(() => ({}));
if (!res.ok || typeof body.requestedAt !== "number") {
toast.error(body.error?.message ?? `Could not start a scan (${res.status})`);
return;
}
const deadline = Date.now() + TIMEOUT_MS;
while (Date.now() < deadline) {
await new Promise((r) => setTimeout(r, POLL_MS));
const state = await fetch("/api/local-folders/scan", { cache: "no-store" })
.then((r) => (r.ok ? r.json() : null))
.catch(() => null);
if (state?.lastScanAt != null && state.lastScanAt >= body.requestedAt) {
router.refresh();
return;
}
}
toast.error("The worker hasn't scanned the folder yet. Is it running?");
} finally {
setBusy(false);
}
}
return (
<Button size="sm" variant="outline" onClick={() => void reload()} disabled={busy} title="Read the folder again: files and README.md">
<RefreshCwIcon className={cn(busy && "animate-spin")} />
{busy ? "Reloading…" : "Reload"}
</Button>
);
}
+27
View File
@@ -175,6 +175,21 @@ export function AddModelForm({
});
}
/** Import without a Hub repo: every file in the folder, kept as it is. */
async function addAsLocal() {
if (!importFolder) return;
setSubmitting(true);
try {
const { id } = await postJson<{ id: string }>("/api/models", { source: "local", localPath: importFolder.path });
toast.success(`${importFolder.path} added as a local model`);
onAdded(id);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
} finally {
setSubmitting(false);
}
}
async function addToLibrary() {
if (!result) return;
setSubmitting(true);
@@ -241,6 +256,18 @@ export function AddModelForm({
{error}
</p>
)}
{importFolder && (
<div className="mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t pt-4">
<p className="min-w-0 flex-1 text-sm text-muted-foreground">
<span className="font-medium text-foreground">Not on Hugging Face?</span> Add the folder as a local model: all{" "}
{importFolder.fileCount} file{importFolder.fileCount === 1 ? "" : "s"} as they are, without Hub checks, updates or
downloads.
</p>
<Button type="button" variant="outline" onClick={addAsLocal} disabled={submitting || loading}>
{submitting ? "Adding…" : "Add as local model"}
</Button>
</div>
)}
</CardContent>
</Card>
+25 -12
View File
@@ -10,7 +10,8 @@ import { formatBytes, shortSha } from "@/lib/format";
import { cn } from "@/lib/utils";
import { AddModelForm, type ImportFolder } from "./add-model-form";
type Folder = ImportFolder & { totalBytes: number };
/** A folder found by the scan, without its file list (fetched when you click Import). */
type Folder = { path: string; commit: string | null; fileCount: number; totalBytes: number };
/** The "Add model" / "Close" toggle (shown in the library hero). */
export function AddModelToggle({ open, onToggle }: { open: boolean; onToggle: () => void }) {
@@ -37,7 +38,9 @@ export function AddModelPanel({
setOpen: (open: boolean) => void;
}) {
const router = useRouter();
const [importing, setImporting] = useState<Folder | null>(null);
const [importing, setImporting] = useState<ImportFolder | null>(null);
// The folder whose file list is being fetched for Import.
const [fetching, setFetching] = useState<string | null>(null);
// Closed from outside (the toggle in the hero): forget the folder being imported.
const [wasOpen, setWasOpen] = useState(open);
if (open !== wasOpen) {
@@ -51,6 +54,22 @@ export function AddModelPanel({
setImporting(null);
}
async function startImport(folder: Folder) {
setFetching(folder.path);
try {
const res = await fetch(`/api/local-folders?path=${encodeURIComponent(folder.path)}`, { cache: "no-store" });
const body = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(body.error?.message ?? `Could not load the folder (${res.status})`);
return;
}
setImporting(body as ImportFolder);
setOpen(true);
} finally {
setFetching(null);
}
}
async function rescan() {
setScanning(true);
try {
@@ -89,7 +108,8 @@ export function AddModelPanel({
</CardTitle>
<CardDescription>
{folders.length} folder{folders.length === 1 ? " isn't" : "s aren't"} in the library yet. Import matches
{folders.length === 1 ? " it" : " them"} with the Hub repo and verifies the files instead of downloading them again.
{folders.length === 1 ? " it" : " them"} with the Hub repo and verifies the files instead of downloading them again,
or adds {folders.length === 1 ? "it" : "them"} as a local model if there is no Hub repo.
</CardDescription>
<CardAction>
<Button variant="ghost" size="sm" onClick={rescan} disabled={scanning}>
@@ -109,15 +129,8 @@ export function AddModelPanel({
{f.fileCount} file{f.fileCount === 1 ? "" : "s"} · {formatBytes(f.totalBytes)}
{f.commit && <> · hf commit {shortSha(f.commit)}</>}
</span>
<Button
size="sm"
variant="outline"
onClick={() => {
setImporting(f);
setOpen(true);
}}
>
Import
<Button size="sm" variant="outline" disabled={fetching != null} onClick={() => void startImport(f)}>
{fetching === f.path ? "Loading…" : "Import"}
</Button>
</li>
))}
+2 -2
View File
@@ -3,7 +3,7 @@ import { abCaveats, abHeadline, abMethod, abSummaryText, halfWidth } from "@/lib
import { CONFIG_ROWS, targetName } from "@/lib/benchmark-view";
import type { PairedResult } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
import type { ListRow } from "../benchmark-list";
import type { RunRow } from "../benchmark-list";
const sign = (v: number) => `${v > 0 ? "+" : ""}${v.toFixed(2)}%`;
@@ -56,7 +56,7 @@ function Side({ label, name, value, unit }: { label: string; name: string; value
);
}
export function AbReport({ run }: { run: ListRow }) {
export function AbReport({ run }: { run: RunRow }) {
const ab = run.ab;
const a = run.snapshot;
const b = run.snapshotB;
@@ -39,7 +39,7 @@ import {
modelName,
targetName,
} from "@/lib/benchmark-view";
import type { ListRow } from "../benchmark-list";
import type { RunRow } from "../benchmark-list";
import { PageHero } from "@/components/hero/page-hero";
import { RunMetaCard } from "@/components/run-meta";
import {
@@ -68,7 +68,7 @@ function duration(a: string | null, b: string | null, now: number) {
: `${Math.round(s)} s`;
}
export function BenchmarkDetail({ initial }: { initial: ListRow }) {
export function BenchmarkDetail({ initial }: { initial: RunRow }) {
const router = useRouter();
const [r, setR] = useState(initial);
const [now, setNow] = useState(() => Date.now());
@@ -7,7 +7,7 @@ import { f0, f1, isBatched, reportCaveats, reportMethod, reportSubtitle, reportS
import { configChips, engineName, modelName } from "@/lib/benchmark-view";
import type { BenchmarkSummary } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
import type { ListRow } from "../benchmark-list";
import type { RunRow } from "../benchmark-list";
function Tile({ label, value, unit, note }: { label: string; value: string; unit: string; note: string }) {
return (
@@ -54,7 +54,7 @@ const date = (iso: string | null | undefined) =>
: "";
/** The run's report, after launch80's bench.betterbench.v1 page; every figure is one BetterBench reported. */
export function BenchmarkReport({ run }: { run: ListRow }) {
export function BenchmarkReport({ run }: { run: RunRow }) {
const sum = run.summary;
if (!sum) return null;
const s = run.snapshot;
+11 -8
View File
@@ -17,20 +17,23 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table";
import type { BenchmarkRow } from "@/lib/benchmarks";
import { configChips, describeSettings, engineName, headline, modelName, targetName } from "@/lib/benchmark-view";
import type { BenchmarkListRow, BenchmarkRow } from "@/lib/benchmarks";
import { configChips, describeSettings, engineName, modelName, targetName } from "@/lib/benchmark-view";
import { cn } from "@/lib/utils";
export type ListRow = Omit<
BenchmarkRow,
"createdAt" | "startedAt" | "finishedAt" | "cancelRequestedAt"
> & {
/** A row as it arrives in the browser (dates as ISO strings). */
type Serialized<T> = Omit<T, "createdAt" | "startedAt" | "finishedAt" | "cancelRequestedAt"> & {
createdAt: string;
startedAt: string | null;
finishedAt: string | null;
cancelRequestedAt: string | null;
};
/** A run in a list: headline numbers only. */
export type ListRow = Serialized<BenchmarkListRow>;
/** A run with everything (detail page). */
export type RunRow = Serialized<BenchmarkRow>;
const MAX_COMPARE = 16;
const fmt = (v: number | null | undefined, digits = 1) =>
v == null ? "–" : v.toFixed(digits);
@@ -165,7 +168,7 @@ export function BenchmarkList({
</TableHeader>
<TableBody>
{shown.map((r) => {
const h = headline(r.summary);
const h = r.headline;
const s = r.snapshot;
return (
<TableRow
@@ -214,7 +217,7 @@ export function BenchmarkList({
</TableCell>
<TableCell className="text-right font-medium tabular-nums">
{r.kind === "eval" ? (
<span title="Quality eval score">{r.quality?.score != null ? `${r.quality.score}% quality` : "–"}</span>
<span title="Quality eval score">{r.qualityScore != null ? `${r.qualityScore}% quality` : "–"}</span>
) : (
fmt(h.decode)
)}
@@ -9,7 +9,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { NativeSelect } from "@/components/ui/native-select";
import { type BenchmarkPhase, QUALITY_SECTIONS, type QualitySection } from "@/lib/db/schema";
import { type BenchmarkPhase, QUALITY_SECTIONS, type QualitySection } from "@/lib/db/enums";
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
import { cn } from "@/lib/utils";
+2 -1
View File
@@ -10,7 +10,8 @@ import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { NativeSelect } from "@/components/ui/native-select";
import { ENGINE_LABEL } from "@/lib/benchmark-meta";
import { ENDPOINT_ENGINES, type EndpointHardware, type EndpointProbe } from "@/lib/db/schema";
import { ENDPOINT_ENGINES } from "@/lib/db/enums";
import type { EndpointHardware, EndpointProbe } from "@/lib/db/schema";
import type { EndpointView } from "@/lib/endpoints";
type Field = { key: keyof EndpointHardware; label: string; placeholder?: string; kind?: "number" | "int"; hint?: string };
+2 -3
View File
@@ -5,7 +5,6 @@ import { buttonVariants } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ENGINE_LABEL } from "@/lib/benchmark-meta";
import { headline } from "@/lib/benchmark-view";
import { listBenchmarks } from "@/lib/benchmarks";
import { listEndpoints } from "@/lib/endpoints";
import { PageHero } from "@/components/hero/page-hero";
@@ -21,8 +20,8 @@ export default async function EndpointsPage() {
for (const r of runs) {
if (!r.endpointId || r.state !== "completed") continue;
const cur = latest.get(r.endpointId) ?? { decode: null, quality: null };
if (r.kind === "run" && cur.decode == null) cur.decode = headline(r.summary).decode;
if (r.kind === "eval" && cur.quality == null) cur.quality = r.quality?.score ?? null;
if (r.kind === "run" && cur.decode == null) cur.decode = r.headline.decode;
if (r.kind === "eval" && cur.quality == null) cur.quality = r.qualityScore;
latest.set(r.endpointId, cur);
}
+14 -1
View File
@@ -1,11 +1,14 @@
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { ApprovalBar } from "@/components/approval-bar";
import { cancelJob } from "@/components/job-actions";
import { JobFilesTable } from "@/components/job-files-table";
import { JobProgress } from "@/components/job-progress";
import { PageHero } from "@/components/hero/page-hero";
import { RequestedByBadge } from "@/components/requested-by-badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useLive } from "@/hooks/use-live";
@@ -22,6 +25,7 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
const files = snapshot?.files ?? [];
const open = OPEN.includes(job.state);
const [busy, setBusy] = useState(false);
const router = useRouter();
const logRef = useRef<HTMLDivElement>(null);
const [follow, setFollow] = useState(true);
@@ -45,7 +49,8 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
{jobLabel(job)} ·{" "}
<Link href={`/${job.repoId}`} className="hover:underline">
{job.repoId}
</Link>
</Link>{" "}
<RequestedByBadge name={job.requestedBy} className="align-middle" />
</>
}
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" && <ApprovalBar job={job} onRemoved={() => router.push("/")} />}
<Card>
<CardContent className="flex flex-col gap-3">
<JobProgress job={job} />
@@ -82,6 +89,12 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
<dd><LocalTime value={job.finishedAt} /></dd>
<dt className="text-muted-foreground">Duration</dt>
<dd>{formatDuration(duration)}</dd>
{job.requestedBy && (
<>
<dt className="text-muted-foreground">Requested by</dt>
<dd>{job.requestedBy} (API token)</dd>
</>
)}
{job.exitCode != null && (
<>
<dt className="text-muted-foreground">Exit code</dt>
+19 -10
View File
@@ -1,22 +1,25 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { auth, signOut } from "@/auth";
import { currentSession, signOut } from "@/auth";
import { AppNav } from "@/components/app-nav";
import { CommandPalette, CommandPaletteButton } from "@/components/command-palette";
import { BackdropProvider } from "@/components/hero/dot-painting";
import { LabelSettingsProvider } from "@/components/labels";
import { UserMenu } from "@/components/user-menu";
import { WorkerIndicator } from "@/components/worker-indicator";
import { getFileRoleStyles, getRecommendedRoles } from "@/lib/settings";
import { authEnabled } from "@/lib/server-env";
import { getBackdrop, getFileRoleStyles, getRecommendedRoles } from "@/lib/settings";
import { getWorkerStatus } from "@/lib/worker-status";
export default async function AppLayout({ children }: LayoutProps<"/">) {
const session = await auth();
if (!session?.user) redirect("/login");
const session = await currentSession();
if (!session) redirect("/login");
const [worker, fileRoles, recommendedRoles] = await Promise.all([
const [worker, fileRoles, recommendedRoles, backdrop] = await Promise.all([
getWorkerStatus(),
getFileRoleStyles(),
getRecommendedRoles(),
getBackdrop(),
]);
return (
@@ -36,17 +39,23 @@ export default async function AppLayout({ children }: LayoutProps<"/">) {
<WorkerIndicator initial={worker} />
<UserMenu
user={{ name: session.user.name ?? null, email: session.user.email ?? null, image: session.user.image ?? null }}
signOutAction={async () => {
"use server";
await signOut({ redirectTo: "/login" });
}}
signOutAction={
authEnabled()
? async () => {
"use server";
await signOut({ redirectTo: "/login" });
}
: undefined
}
/>
</div>
</div>
</header>
<CommandPalette />
<main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6">
<LabelSettingsProvider fileRoles={fileRoles} recommendedRoles={recommendedRoles}>{children}</LabelSettingsProvider>
<BackdropProvider backdrop={backdrop}>
<LabelSettingsProvider fileRoles={fileRoles} recommendedRoles={recommendedRoles}>{children}</LabelSettingsProvider>
</BackdropProvider>
</main>
</div>
);
+34 -9
View File
@@ -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,11 +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<Facet, string> = {
@@ -40,12 +44,13 @@ const FACET_LABEL: Record<Facet, string> = {
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 {
return {
const m: SearchableModel = {
repoId: r.repoId,
author: r.author,
families: r.families,
@@ -63,7 +68,10 @@ function toSearchable(r: LibraryRow): SearchableModel {
: r.updateAvailable
? "update available"
: null,
requestedBy: r.requestedBy,
pendingApproval: r.pendingApproval,
};
return { ...m, text: searchText(m) };
}
/** Search + facet filters (kept in the URL) over the library table. */
@@ -106,9 +114,19 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
sync("", EMPTY_FILTERS);
};
// Search text and counts are computed once per change of rows, query or filters, not on every
// render (live job progress re-renders this table while downloads run).
const searchable = useMemo(() => rows.map(toSearchable), [rows]);
const tagColors = useMemo(() => new Map(rows.flatMap((r) => r.tags.map((t) => [t.name, t.color] as const))), [rows]);
const visible = rows.filter((_, i) => matchesQuery(searchable[i], query) && matchesFilters(searchable[i], filters));
const terms = useMemo(() => queryTerms(query), [query]);
const visible = useMemo(
() => rows.filter((_, i) => matchesQuery(searchable[i], terms) && matchesFilters(searchable[i], filters)),
[rows, searchable, terms, filters],
);
const facetOptions = useMemo(
() => Object.fromEntries(FACETS.map((facet) => [facet, facetCounts(searchable, facet, terms, filters)])) as Record<Facet, [string, number][]>,
[searchable, terms, filters],
);
const anyActive = query.trim() !== "" || FACETS.some((f) => filters[f].length > 0);
const pages = Math.max(1, Math.ceil(visible.length / pageSize));
const current = Math.min(page, pages - 1);
@@ -147,7 +165,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
<FacetFilter
key={facet}
label={FACET_LABEL[facet]}
values={facetCounts(searchable, facet, query, filters)}
values={facetOptions[facet]}
selected={filters[facet]}
onChange={(v) => updateFilter(facet, v)}
format={facet === "status" ? statusLabel : undefined}
@@ -195,6 +213,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
{base && base !== r.repoId && <span>base {base}</span>}
{r.architecture && <span>{r.architecture}</span>}
<RequestedByBadge name={r.requestedBy} className="h-4 text-[10px]" />
{r.tags.map((t) => (
<button
key={t.id}
@@ -223,9 +242,15 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(r.totalBytes)}</TableCell>
<TableCell className="hidden lg:table-cell">
<code className="font-mono text-xs text-muted-foreground" title={r.pinnedSha}>
{r.trackedRevision}@{shortSha(r.pinnedSha)}
</code>
{r.source === "local" ? (
<span className="text-xs text-muted-foreground" title="A folder without a Hugging Face repo">
local
</span>
) : (
<code className="font-mono text-xs text-muted-foreground" title={r.pinnedSha}>
{r.trackedRevision}@{shortSha(r.pinnedSha)}
</code>
)}
</TableCell>
<TableCell className="hidden text-sm text-muted-foreground md:table-cell">
<LocalTime value={r.downloadedAt} />
@@ -234,7 +259,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
{job ? (
<Link href={`/jobs/${job.id}`} className="flex flex-col gap-1">
<JobStateBadge job={job} />
{job.state !== "queued" && <JobProgress job={job} compact />}
{job.state !== "queued" && job.state !== "pending_approval" && <JobProgress job={job} compact />}
</Link>
) : (
<span className="flex flex-wrap gap-1">
+3 -6
View File
@@ -1,4 +1,4 @@
import { auth } from "@/auth";
import { currentSession } from "@/auth";
import { listLibrary } from "@/lib/library";
import { listLocalFolders } from "@/lib/local-folders";
import { getWorkerStatus } from "@/lib/worker-status";
@@ -8,7 +8,7 @@ import { LibraryView } from "./library-view";
export const dynamic = "force-dynamic";
export default async function LibraryPage({ searchParams }: PageProps<"/">) {
const [rows, worker, folders, session] = await Promise.all([listLibrary(), getWorkerStatus(), listLocalFolders(), auth()]);
const [rows, worker, folders, session] = await Promise.all([listLibrary(), getWorkerStatus(), listLocalFolders(), currentSession()]);
return (
<div className="flex flex-col gap-4">
@@ -24,10 +24,7 @@ export default async function LibraryPage({ searchParams }: PageProps<"/">) {
updates: rows.filter((r) => r.updateAvailable && (r.hubState === "available" || !r.hubState)).length,
goneFromHub: rows.filter((r) => r.hubState === "repo_missing" || r.hubState === "commit_missing").length,
}}
panel={{
freeBytes: worker.online ? worker.modelsDirFreeBytes : null,
folders: folders.map((f) => ({ path: f.path, commit: f.commit, files: f.files, fileCount: f.fileCount, totalBytes: f.totalBytes })),
}}
panel={{ freeBytes: worker.online ? worker.modelsDirFreeBytes : null, folders }}
/>
{rows.length > 0 && <LibraryView rows={rows} />}
</div>
@@ -0,0 +1,111 @@
"use client";
import { ShieldCheckIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import { type ApprovalMode, type Guardrails, parseAuthorList } from "@/lib/agent-guardrails";
const GB = 1_000_000_000;
const toGb = (b: number) => String(Math.round((b / GB) * 1000) / 1000);
/** Limits for downloads requested through the API. Saved together with one button. */
export function GuardrailSettings({ initial }: { initial: Guardrails }) {
const router = useRouter();
const [mode, setMode] = useState<ApprovalMode>(initial.approvalMode);
const [maxGb, setMaxGb] = useState(toGb(initial.maxRequestBytes));
const [minFreeGb, setMinFreeGb] = useState(toGb(initial.minFreeBytes));
const [maxJobs, setMaxJobs] = useState(String(initial.maxOpenJobs));
const [authors, setAuthors] = useState(initial.allowedAuthors.join(", "));
const [busy, setBusy] = useState(false);
let authorError: string | null = null;
let authorList: string[] = [];
try {
authorList = parseAuthorList(authors);
} catch (err) {
authorError = err instanceof Error ? err.message : String(err);
}
const num = (s: string) => Number(s.replace(",", "."));
async function save(e: React.FormEvent) {
e.preventDefault();
if (authorError) return;
setBusy(true);
try {
const res = await fetch("/api/settings/agent", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
approvalMode: mode,
maxRequestBytes: Math.round(num(maxGb) * GB),
minFreeBytes: Math.round(num(minFreeGb) * GB),
maxOpenJobs: Math.round(num(maxJobs)),
allowedAuthors: authorList,
}),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(json.error?.message ?? `Could not save (${res.status})`);
toast.success("Guardrails saved");
router.refresh();
} finally {
setBusy(false);
}
}
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-1.5">
<ShieldCheckIcon className="size-4 text-muted-foreground" />
Guardrails for API downloads
</CardTitle>
<CardDescription>Apply to every download and repair requested with a token, across all tokens. Downloads you start in the UI are not affected. Verify and tags never need approval.</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={save} className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-mode">Approval</Label>
<NativeSelect id="g-mode" value={mode} onChange={(e) => setMode(e.target.value as ApprovalMode)} className="max-w-md">
<option value="approve">Ask me: requests wait as &ldquo;pending approval&rdquo;</option>
<option value="auto">Automatic: downloads start right away</option>
</NativeSelect>
</div>
<div className="grid gap-4 sm:grid-cols-3">
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-max">Max size per request (GB)</Label>
<Input id="g-max" value={maxGb} onChange={(e) => setMaxGb(e.target.value.replace(/[^\d.,]/g, ""))} inputMode="decimal" />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-free">Keep free on the models folder (GB)</Label>
<Input id="g-free" value={minFreeGb} onChange={(e) => setMinFreeGb(e.target.value.replace(/[^\d.,]/g, ""))} inputMode="decimal" />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-jobs">Agent jobs at once</Label>
<Input id="g-jobs" value={maxJobs} onChange={(e) => setMaxJobs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" />
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-authors">Allowed authors</Label>
<Input id="g-authors" value={authors} onChange={(e) => setAuthors(e.target.value)} placeholder="Empty: any author. e.g. unsloth, ggml-org, Qwen" aria-invalid={!!authorError} />
<p className="text-xs text-muted-foreground">
{authorError ?? "Hugging Face users or organizations (the part before the slash), comma-separated. Applies to new downloads, not to repairs of models already in the library."}
</p>
</div>
<p className="text-xs text-muted-foreground">
&ldquo;Agent jobs at once&rdquo; counts downloads and repairs that are pending approval, queued or downloading. The free-space check also subtracts what other open
downloads still need.
</p>
<Button type="submit" className="self-start" disabled={busy || !!authorError}>
Save guardrails
</Button>
</form>
</CardContent>
</Card>
);
}
@@ -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 (
<div className="flex flex-col gap-4">
<TokenSettings tokens={tokens} activity={activity} />
<GuardrailSettings initial={guardrails} />
</div>
);
}
@@ -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<string, ActivityItem[]>;
}) {
const [created, setCreated] = useState<{
name: string;
token: string;
} | null>(null);
return (
<Card>
<CardHeader>
<CardTitle>API tokens</CardTitle>
<CardDescription>
For programs and agents calling Kaname&apos;s API at{" "}
<code className="font-mono text-xs">/api/v1</code> with{" "}
<code className="font-mono text-xs">
Authorization: Bearer &lt;token&gt;
</code>
. No token can delete models or files, change settings, or manage
tokens. The guide for agents is in{" "}
<code className="font-mono text-xs">docs/agent/SKILL.md</code>.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<NewTokenForm onCreated={setCreated} />
{created && (
<div className="flex flex-col gap-1.5 rounded-lg border border-primary/40 bg-primary/5 px-4 py-3">
<p className="text-sm font-medium">
Token &ldquo;{created.name}&rdquo; created. Copy it now: it is not
shown again.
</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 rounded-md bg-muted px-2 py-1 font-mono text-xs break-all">
{created.token}
</code>
<CopyButton value={created.token} label="Copy token" />
</div>
</div>
)}
{tokens.length === 0 ? (
<p className="text-sm text-muted-foreground">No tokens yet.</p>
) : (
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{tokens.map((t) => (
<TokenRow key={t.id} token={t} activity={activity[t.id] ?? []} />
))}
</div>
)}
</CardContent>
</Card>
);
}
function NewTokenForm({
onCreated,
}: {
onCreated: (t: { name: string; token: string }) => void;
}) {
const router = useRouter();
const [name, setName] = useState("");
const [scopes, setScopes] = useState<TokenScope[]>(["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 (
<form
onSubmit={create}
className="flex flex-col gap-3 rounded-lg border border-dashed px-4 py-3"
>
<div className="flex items-center gap-2">
<Input
value={name}
maxLength={40}
disabled={busy}
onChange={(e) =>
setName(e.target.value.toLowerCase().replace(/[^a-z0-9._-]/g, ""))
}
placeholder="Name, e.g. hermes"
aria-label="Token name"
className="max-w-56"
/>
<Button
type="submit"
size="sm"
disabled={busy || !name || scopes.length === 0}
>
<PlusIcon />
Create token
</Button>
</div>
<div className="flex flex-col gap-1.5">
{TOKEN_SCOPES.map((s) => (
<label
key={s}
className="flex cursor-pointer items-start gap-2 text-sm"
>
<Checkbox
checked={scopes.includes(s)}
onCheckedChange={(v) =>
setScopes((cur) =>
v ? [...cur, s] : cur.filter((x) => x !== s),
)
}
className="mt-0.5"
/>
<span className="flex flex-col">
<code className="font-mono text-xs">{s}</code>
<span className="text-xs text-muted-foreground">
{SCOPE_LABEL[s]}
</span>
</span>
</label>
))}
</div>
<p className="text-xs text-muted-foreground">
The name is shown as &ldquo;requested by&rdquo; on everything the token
asks for.
</p>
</form>
);
}
function TokenRow({
token,
activity,
}: {
token: ApiTokenRow;
activity: ActivityItem[];
}) {
const router = useRouter();
const revoked = !!token.revokedAt;
const [editing, setEditing] = useState(false);
const [scopes, setScopes] = useState<TokenScope[]>(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 (
<div className="flex flex-col gap-2 px-4 py-2.5">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<BotIcon className="size-4 shrink-0 text-muted-foreground" />
<span className="text-sm font-medium">{token.name}</span>
<code className="font-mono text-xs text-muted-foreground">
{token.prefix}…
</code>
<span className="flex flex-wrap gap-1">
{token.scopes.map((s) => (
<Badge key={s} variant="outline" className="font-mono text-[10px]">
{s}
</Badge>
))}
</span>
{revoked && <Badge variant="destructive">revoked</Badge>}
<span className="ml-auto text-xs text-muted-foreground">
{token.lastUsedAt ? (
<>
used <LocalTime value={token.lastUsedAt} />
</>
) : (
"never used"
)}
</span>
{activity.length > 0 && (
<Button
variant="ghost"
size="sm"
onClick={() => setShowActivity((v) => !v)}
>
Activity ({activity.length})
</Button>
)}
{!revoked && (
<Button
variant="ghost"
size="sm"
onClick={() => setEditing((v) => !v)}
>
Scopes
</Button>
)}
<AlertDialog>
<AlertDialogTrigger render={<Button variant="ghost" size="sm" />}>
{revoked ? <Trash2Icon /> : "Revoke"}
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{revoked ? "Delete" : "Revoke"} token &ldquo;{token.name}
&rdquo;?
</AlertDialogTitle>
<AlertDialogDescription>
{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."}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={() => act(revoked ? "DELETE" : "POST")}
>
{revoked ? "Delete" : "Revoke"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
{editing && (
<div className="flex flex-col gap-2 rounded-lg border p-3">
{TOKEN_SCOPES.map((s) => (
<label
key={s}
className="flex cursor-pointer items-start gap-2 text-sm"
>
<Checkbox
checked={scopes.includes(s)}
onCheckedChange={(v) =>
setScopes((cur) =>
v ? [...cur, s] : cur.filter((x) => x !== s),
)
}
className="mt-0.5"
/>
<span className="flex flex-col">
<span className="font-mono text-xs">{s}</span>
<span className="text-xs text-muted-foreground">
{SCOPE_LABEL[s]}
</span>
</span>
</label>
))}
<Button
size="sm"
className="self-start"
disabled={scopes.length === 0}
onClick={saveScopes}
>
Save scopes
</Button>
</div>
)}
{showActivity && <ActivityList items={activity} />}
</div>
);
}
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, (id: string) => 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 (
<ul className="flex max-h-80 flex-col gap-1 overflow-y-auto rounded-lg border p-2 text-xs">
{items.map((a) => (
<li key={a.id} className="flex flex-wrap items-baseline gap-x-2">
<span className="text-muted-foreground tabular-nums">
<LocalTime value={a.createdAt} />
</span>
<span className="font-mono">{a.action}</span>
<span
className={
a.outcome === "refused"
? "text-destructive"
: a.outcome === "pending_approval"
? "text-amber-700 dark:text-amber-300"
: "text-emerald-700 dark:text-emerald-300"
}
>
{a.outcome === "refused"
? `refused: ${a.code}`
: a.outcome === "pending_approval"
? "awaiting approval"
: "ok"}
</span>
{a.targetType && a.targetId && TARGET_HREF[a.targetType] && (
<Link
href={TARGET_HREF[a.targetType](a.targetId)}
className="underline"
>
{a.targetType}
</Link>
)}
{a.message && (
<span className="w-full text-muted-foreground">{a.message}</span>
)}
</li>
))}
</ul>
);
}
@@ -0,0 +1,158 @@
"use client";
import { ImageIcon, ImageUpIcon, Loader2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useRef, useState } from "react";
import { toast } from "sonner";
import { DotPainting } from "@/components/hero/dot-painting";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { type Backdrop, BACKDROP_MAX_CELLS } from "@/lib/backdrop";
/**
* Turns an image into a brightness grid like the built-in painting: at most BACKDROP_MAX_CELLS on
* the long side, transparency on white, contrast-stretched (2nd–98th percentile) to levels 0–f.
*/
async function toBackdrop(file: File): Promise<Backdrop> {
let img: ImageBitmap | HTMLCanvasElement = await createImageBitmap(file);
const s = Math.min(1, BACKDROP_MAX_CELLS / Math.max(img.width, img.height));
const w = Math.max(8, Math.round(img.width * s));
const h = Math.max(8, Math.round(img.height * s));
// Halve in steps first: one big downscale skips most pixels and looks noisy.
while (img.width > w * 2 && img.height > h * 2) {
const half = document.createElement("canvas");
half.width = Math.round(img.width / 2);
half.height = Math.round(img.height / 2);
half.getContext("2d")!.drawImage(img, 0, 0, half.width, half.height);
img = half;
}
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
const g = canvas.getContext("2d", { willReadFrequently: true })!;
g.fillStyle = "#fff";
g.fillRect(0, 0, w, h);
g.imageSmoothingQuality = "high";
g.drawImage(img, 0, 0, w, h);
const px = g.getImageData(0, 0, w, h).data;
const lum = new Float32Array(w * h);
for (let i = 0; i < lum.length; i++) lum[i] = 0.2126 * px[i * 4] + 0.7152 * px[i * 4 + 1] + 0.0722 * px[i * 4 + 2];
const sorted = Float32Array.from(lum).sort();
const lo = sorted[Math.floor(sorted.length * 0.02)];
const hi = sorted[Math.ceil(sorted.length * 0.98) - 1];
const range = Math.max(1, hi - lo);
let dots = "";
for (const l of lum) dots += Math.round(Math.min(1, Math.max(0, (l - lo) / range)) * 15).toString(16);
return { w, h, dots, focus: [0.5, 0.5] };
}
/** Upload a picture for the dot painting behind the page headers, pick its focus point, or go back to the built-in one. */
export function BackdropSettings({ initial }: { initial: Backdrop | null }) {
const router = useRouter();
const [saved, setSaved] = useState(initial);
// The picture being edited: the saved one, a new upload, or null (built-in painting).
const [draft, setDraft] = useState(initial);
const [reading, setReading] = useState(false);
const [busy, setBusy] = useState(false);
const input = useRef<HTMLInputElement>(null);
const dirty = draft?.dots !== saved?.dots || draft?.focus[0] !== saved?.focus[0] || draft?.focus[1] !== saved?.focus[1];
async function pick(file: File | undefined) {
if (!file) return;
setReading(true);
try {
setDraft(await toBackdrop(file));
} catch {
toast.error(`"${file.name}" couldn't be read as an image.`);
} finally {
setReading(false);
if (input.current) input.current.value = "";
}
}
async function save(next: Backdrop | null) {
setBusy(true);
try {
const res = await fetch("/api/settings/appearance", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ backdrop: next }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(body.error?.message ?? `Could not save (${res.status})`);
setSaved(body.backdrop);
setDraft(body.backdrop);
toast.success(body.backdrop ? "Background picture saved" : "Back to The Creation of Adam");
router.refresh(); // the headers get the picture from the layout
} finally {
setBusy(false);
}
}
return (
<Card>
<CardHeader>
<CardTitle>Background picture</CardTitle>
<CardDescription>
The dot matrix behind every page header. Upload your own picture and it is drawn in dots the same way, in the theme&apos;s colors. Only the dots are
saved, not the image, and they apply for everyone using this Kaname.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3 text-sm">
{draft ? (
<div className="flex flex-col gap-1.5">
<button
type="button"
className="relative w-full max-w-xl cursor-crosshair overflow-hidden rounded-lg bg-background ring-1 ring-foreground/10"
style={{ aspectRatio: `${draft.w} / ${draft.h}` }}
onClick={(e) => {
const r = e.currentTarget.getBoundingClientRect();
const f = (v: number) => Math.round(Math.min(1, Math.max(0, v)) * 1000) / 1000;
setDraft({ ...draft, focus: [f((e.clientX - r.left) / r.width), f((e.clientY - r.top) / r.height)] });
}}
aria-label="Set the focus point"
>
<DotPainting source={draft} anchor={draft.focus} className="absolute inset-0 size-full text-foreground/75" />
<span
className="absolute size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-primary bg-primary/30 shadow"
style={{ left: `${draft.focus[0] * 100}%`, top: `${draft.focus[1] * 100}%` }}
aria-hidden
/>
</button>
<p className="text-xs text-muted-foreground">Click the part that should stay in view when a header crops the picture.</p>
</div>
) : (
<p className="flex items-center gap-2 text-muted-foreground">
<ImageIcon className="size-4" />
<span>
Showing the built-in painting, Michelangelo&apos;s <i>The Creation of Adam</i>.
</span>
</p>
)}
<div className="flex flex-wrap items-center gap-2">
<input ref={input} type="file" accept="image/*" className="hidden" onChange={(e) => void pick(e.target.files?.[0])} />
<Button variant="outline" disabled={reading || busy} onClick={() => input.current?.click()}>
{reading ? <Loader2Icon className="animate-spin" /> : <ImageUpIcon />}
{draft ? "Choose another picture" : "Upload a picture"}
</Button>
{dirty && (
<>
<Button disabled={busy || reading} onClick={() => void save(draft)}>
Save
</Button>
<Button variant="ghost" disabled={busy} onClick={() => setDraft(saved)}>
Cancel
</Button>
</>
)}
{saved && !dirty && (
<Button variant="ghost" disabled={busy} onClick={() => void save(null)}>
Use the built-in painting
</Button>
)}
</div>
</CardContent>
</Card>
);
}
@@ -0,0 +1,10 @@
import type { Metadata } from "next";
import { getBackdrop } from "@/lib/settings";
import { BackdropSettings } from "./backdrop-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Appearance · Settings" };
export default async function AppearanceSettingsPage() {
return <BackdropSettings initial={await getBackdrop()} />;
}
+4 -2
View File
@@ -1,4 +1,4 @@
import { DownloadIcon, 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";
@@ -6,13 +6,15 @@ const SECTIONS = [
{ href: "/settings/labels", label: "File labels", icon: <TagIcon className="size-4" /> },
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
{ href: "/settings/appearance", label: "Appearance", icon: <PaletteIcon className="size-4" /> },
{ href: "/settings/api-tokens", label: "API tokens", icon: <BotIcon className="size-4" /> },
];
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
return (
<PageHero
title="Settings"
description="File labels, tags, and how Kaname downloads and scans models."
description="File labels, tags, how Kaname downloads and scans models, the background picture, and API tokens for agents."
painting={{ view: 0.4, focus: [0.5, 0.43], anchor: [0.7, 0.4] }}
>
<div className="grid items-start gap-4 md:grid-cols-[200px_minmax(0,1fr)]">
+40
View File
@@ -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<RouteContext<"/api/api-tokens/[id]">>(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<RouteContext<"/api/api-tokens/[id]">>(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<RouteContext<"/api/api-tokens/[id]">>(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;
}
});
+23
View File
@@ -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);
}
});
+17
View File
@@ -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<RouteContext<"/api/jobs/[id]/approve">>(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;
}
});
+16
View File
@@ -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<RouteContext<"/api/jobs/[id]/reject">>(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;
}
});
+43
View File
@@ -0,0 +1,43 @@
import { createHash } from "node:crypto";
import { withAuth } from "@/lib/api-auth";
import { getJob, listJobFiles, listJobLogs, listLiveJobs, listModelJobs } from "@/lib/jobs";
import { liveBody, type LiveSnapshot } from "@/lib/live-protocol";
import { getWorkerStatus } from "@/lib/worker-status";
export const dynamic = "force-dynamic";
/**
* Live job state, polled by the browser about once per second while the tab is visible (one poller
* per query and tab, see src/lib/live-store.ts). Short requests instead of a stream per component:
* over HTTP/1.1 a browser allows 6 connections per host, and open streams used them up.
* ?model=<id> jobs of one model (+ files of its newest job)
* ?job=<id> one job with per-file progress; with &logAfter=<id> also the log lines after
* that id (0: the last 1000)
* (none) open and recently finished jobs (library view)
* &v=<version> the snapshot version the client has; an unchanged snapshot is left out
*/
export const GET = withAuth(async (req) => {
const sp = new URL(req.url).searchParams;
const modelId = sp.get("model");
const jobId = sp.get("job");
const json = JSON.stringify(await buildSnapshot(modelId, jobId));
const version = createHash("sha1").update(json).digest("base64url").slice(0, 16);
const logs = jobId && sp.has("logAfter") ? await listJobLogs(jobId, Number(sp.get("logAfter")) || 0) : undefined;
return new Response(liveBody(json, version, sp.get("v"), logs), {
headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" },
});
});
async function buildSnapshot(modelId: string | null, jobId: string | null): Promise<LiveSnapshot> {
const worker = await getWorkerStatus();
if (jobId) {
const job = await getJob(jobId);
return { worker, jobs: job ? [job] : [], files: job ? await listJobFiles(jobId) : [] };
}
if (modelId) {
const jobs = await listModelJobs(modelId);
const files = jobs[0] ? await listJobFiles(jobs[0].id) : [];
return { worker, jobs, files };
}
return { worker, jobs: await listLiveJobs(), files: [] };
}
+20
View File
@@ -0,0 +1,20 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { getLocalFolder } from "@/lib/local-folders";
export const dynamic = "force-dynamic";
/** One folder the scan found, with its files (`?path=<org>/<name>`): what the Import form needs. */
export const GET = withAuth(async (req) => {
const path = new URL(req.url).searchParams.get("path");
const folder = path ? await getLocalFolder(path) : undefined;
if (!folder) return apiError(404, "not_found", "This folder is no longer in the models folder. Rescan and try again.");
return NextResponse.json({
path: folder.path,
commit: folder.commit,
files: folder.files,
fileCount: folder.fileCount,
totalBytes: folder.totalBytes,
});
});
+11 -4
View File
@@ -1,9 +1,16 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { requestFolderScan } from "@/lib/local-folders";
import { getScanState, requestFolderScan } from "@/lib/local-folders";
/** Ask the worker to rescan the models folder for importable folders. */
export const dynamic = "force-dynamic";
/** Ask the worker to rescan the models folder (importable folders, and local models' files). */
export const POST = withAuth(async () => {
await requestFolderScan();
return new NextResponse(null, { status: 202 });
const requestedAt = await requestFolderScan();
return NextResponse.json({ requestedAt: requestedAt.getTime() }, { status: 202 });
});
/** When the worker last finished a scan, so a client can wait for the one it asked for. */
export const GET = withAuth(async () => {
return NextResponse.json(await getScanState());
});
@@ -8,5 +8,6 @@ export const POST = withAuth<RouteContext<"/api/models/[id]/hub-check">>(async (
const { id } = await params;
const model = await getCheckedModel(id);
if (!model) return apiError(404, "not_found", "Model not found.");
if (model.source === "local") return apiError(409, "local_model", "This is a local model without a Hugging Face repo.");
return NextResponse.json(await checkHub(model));
});
+21 -3
View File
@@ -4,7 +4,7 @@ import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client";
import { queueDownload } from "@/lib/jobs";
import { addModel, ModelError } from "@/lib/models";
import { addLocalModel, addModel, ModelError } from "@/lib/models";
import { addTag, normalizeTagName, TagError } from "@/lib/tags";
const Body = z.object({
@@ -19,10 +19,28 @@ const Body = z.object({
localPath: z.string().min(1).max(512).optional(),
});
/** Add a model to the library, pinned to the SHA the user reviewed, and queue its download. */
/** A folder from the models folder without a Hub repo, added as it is. */
const LocalBody = z.object({
source: z.literal("local"),
localPath: z.string().min(1).max(512),
tags: z.array(z.string()).max(50).default([]),
});
/**
* Add a model to the library, pinned to the SHA the user reviewed, and queue its download. With
* `source: "local"`, add a folder from the models folder that has no Hub repo instead (nothing queued).
*/
export const POST = withAuth(async (req) => {
try {
const body = Body.parse(await req.json());
const json = await req.json();
if (json?.source === "local") {
const body = LocalBody.parse(json);
body.tags.forEach(normalizeTagName);
const { id } = await addLocalModel({ localPath: body.localPath });
for (const tag of body.tags) await addTag(id, tag);
return NextResponse.json({ id, jobId: null }, { status: 201 });
}
const body = Body.parse(json);
body.tags.forEach(normalizeTagName); // validate before anything is written
const { id } = await addModel({
repoId: body.repoId,
+2 -2
View File
@@ -10,11 +10,11 @@ export const dynamic = "force-dynamic";
/** Everything the ⌘K palette can jump to, compact (it filters in the browser). */
export const GET = withAuth(async () => {
const [models, endpoints, runs, tags] = await Promise.all([listLibrary(), listEndpoints(), listBenchmarks(), listTags()]);
const [models, endpoints, runs, tags] = await Promise.all([listLibrary(), listEndpoints(), listBenchmarks({}, { limit: 300 }), listTags()]);
return NextResponse.json({
models: models.map((m) => ({ id: m.id, repoId: m.repoId, quants: m.quants, status: m.status, tags: m.tags.map((t) => t.name) })),
endpoints: endpoints.map((e) => ({ id: e.id, name: e.name, model: e.model, engine: e.engine ?? e.probe?.engine ?? null })),
benchmarks: runs.slice(0, 300).map((r) => ({
benchmarks: runs.map((r) => ({
id: r.id,
label: r.label,
kind: r.kind,
+30
View File
@@ -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);
}
});
+22
View File
@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { getBackdrop, saveBackdrop, SettingsError } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Appearance: the custom picture behind the page headers (null for the built-in painting). */
export const GET = withAuth(async () => NextResponse.json({ backdrop: await getBackdrop() }));
const Body = z.object({ backdrop: z.unknown() });
export const PUT = withAuth(async (req) => {
try {
const body = Body.parse(await req.json());
return NextResponse.json({ backdrop: await saveBackdrop(body.backdrop ?? null) });
} catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
-97
View File
@@ -1,97 +0,0 @@
import { withAuth } from "@/lib/api-auth";
import { getJob, listJobFiles, listJobLogs, listLiveJobs, listModelJobs } from "@/lib/jobs";
import { getWorkerStatus } from "@/lib/worker-status";
export const dynamic = "force-dynamic";
const INTERVAL_MS = 1_000;
const KEEPALIVE_MS = 15_000;
/**
* Server-Sent Events with live job state, polled from the DB once per second.
* ?model=<id> jobs of one model (+ files of its newest job)
* ?job=<id> one job with per-file progress and incremental log lines
* (none) open and recently finished jobs (library view)
* Events: "snapshot" (only when something changed) and "logs" (new lines).
*/
export const GET = withAuth(async (req) => {
const url = new URL(req.url);
const modelId = url.searchParams.get("model");
const jobId = url.searchParams.get("job");
let logCursor = Number(url.searchParams.get("logAfter") ?? 0) || 0;
const encoder = new TextEncoder();
const signal = req.signal;
const stream = new ReadableStream({
async start(controller) {
let last = "";
let lastWrite = Date.now();
const write = (chunk: string) => {
controller.enqueue(encoder.encode(chunk));
lastWrite = Date.now();
};
const send = (event: string, data: unknown) => write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
try {
write("retry: 3000\n\n");
while (!signal.aborted) {
const snapshot = await buildSnapshot(modelId, jobId);
const serialized = JSON.stringify(snapshot);
if (serialized !== last) {
send("snapshot", snapshot);
last = serialized;
}
if (jobId) {
const lines = await listJobLogs(jobId, logCursor);
if (lines.length > 0) {
logCursor = lines[lines.length - 1].id;
send("logs", lines);
}
}
if (Date.now() - lastWrite > KEEPALIVE_MS) write(": keepalive\n\n");
await sleep(INTERVAL_MS, signal);
}
} catch {
// client went away or the stream was closed
} finally {
try {
controller.close();
} catch {}
}
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
},
});
});
async function buildSnapshot(modelId: string | null, jobId: string | null) {
const worker = await getWorkerStatus();
if (jobId) {
const job = await getJob(jobId);
return { worker, jobs: job ? [job] : [], files: job ? await listJobFiles(jobId) : [] };
}
if (modelId) {
const jobs = await listModelJobs(modelId);
const files = jobs[0] ? await listJobFiles(jobs[0].id) : [];
return { worker, jobs, files };
}
return { worker, jobs: await listLiveJobs(), files: [] };
}
function sleep(ms: number, signal: AbortSignal) {
return new Promise<void>((resolve) => {
const t = setTimeout(resolve, ms);
signal.addEventListener("abort", () => {
clearTimeout(t);
resolve();
});
});
}
+34
View File
@@ -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);
}
});
+49
View File
@@ -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);
}
});
+47
View File
@@ -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);
}
});
+17
View File
@@ -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<RouteContext<"/api/v1/jobs/[id]/cancel">>(["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);
}
});
+83
View File
@@ -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<string, string> = {
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<Awaited<ReturnType<typeof getJob>>>) {
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=<s> (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<RouteContext<"/api/v1/jobs/[id]">>("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);
}
});
@@ -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<RouteContext<"/api/v1/models/[id]/repair">>("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);
}
});
+40
View File
@@ -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<RouteContext<"/api/v1/models/[id]">>("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);
}
});
@@ -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<RouteContext<"/api/v1/models/[id]/tags/[name]">>("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);
}
});
+21
View File
@@ -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<RouteContext<"/api/v1/models/[id]/tags">>("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);
}
});
@@ -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<RouteContext<"/api/v1/models/[id]/verify">>("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);
}
});
+62
View File
@@ -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);
}
});
+36
View File
@@ -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",
],
});
});
+15
View File
@@ -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);
}
});
+3 -2
View File
@@ -1,5 +1,5 @@
import { redirect } from "next/navigation";
import { auth, OIDC_PROVIDER_ID, signIn } from "@/auth";
import { currentSession, OIDC_PROVIDER_ID, signIn } from "@/auth";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
@@ -19,7 +19,8 @@ export default async function LoginPage({ searchParams }: PageProps<"/login">) {
const params = await searchParams;
const callbackUrl = safeCallback(params.callbackUrl);
if ((await auth())?.user) redirect(callbackUrl);
// Also covers login off: currentSession() is never null then.
if (await currentSession()) redirect(callbackUrl);
const errorKey = typeof params.error === "string" ? params.error : undefined;
const error = errorKey ? (ERRORS[errorKey] ?? "Login failed. Please try again.") : undefined;
+17 -2
View File
@@ -1,5 +1,5 @@
import NextAuth, { type NextAuthConfig } from "next-auth";
import { authEnv } from "@/lib/server-env";
import NextAuth, { type NextAuthConfig, type Session } from "next-auth";
import { authEnabled, authEnv } from "@/lib/server-env";
declare module "next-auth" {
interface Session {
@@ -24,6 +24,8 @@ function groupsFromProfile(profile: unknown): string[] {
// Config is built lazily (per request) so `next build` doesn't need OIDC env vars.
export const { handlers, auth, signIn, signOut } = NextAuth((): NextAuthConfig => {
const env = authEnv();
// Login off: no provider. Nothing calls signIn then (see currentSession, proxy.ts, /login).
if (!env) return { trustHost: true, session: { strategy: "jwt" }, providers: [] };
const restrictGroups = env.OIDC_ALLOWED_GROUPS.length > 0;
return {
@@ -62,3 +64,16 @@ export const { handlers, auth, signIn, signOut } = NextAuth((): NextAuthConfig =
},
};
});
/** Stand-in user while login is off (no OIDC_* configured). */
const NO_LOGIN_SESSION: Session = { user: { name: null, email: null, image: null, groups: [] }, expires: "" };
/**
* The signed-in user's session, or null. With login off (see authEnabled), everyone counts as
* signed in. Use this instead of auth() everywhere outside proxy.ts.
*/
export async function currentSession(): Promise<Session | null> {
if (!authEnabled()) return NO_LOGIN_SESSION;
const session = await auth();
return session?.user ? session : null;
}
+62
View File
@@ -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<string, string> = {
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<unknown>) {
setBusy(true);
try {
await fn();
router.refresh();
} finally {
setBusy(false);
}
}
return (
<div className="flex flex-col gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2.5 text-sm">
<p className="flex items-center gap-1.5">
<BotIcon className="size-4 shrink-0 text-amber-700 dark:text-amber-300" />
<span>
<strong>{job.requestedBy ?? "An API token"}</strong> asks to download {job.purpose === "repair" ? "up to " : ""}
{formatBytes(job.totalBytes)}
{WHAT[job.purpose ?? ""] ?? ""}. It starts once you approve it.
</span>
</p>
<div className="flex gap-2">
<Button size="sm" disabled={busy} onClick={() => run(() => approveJob(job.id))}>
<CheckIcon />
Approve
</Button>
<Button
size="sm"
variant="outline"
disabled={busy}
onClick={() =>
run(async () => {
const r = await rejectJob(job.id);
if (r?.removedModel) onRemoved?.();
})
}
>
<XIcon />
Reject
</Button>
</div>
</div>
);
}
+231
View File
@@ -0,0 +1,231 @@
"use client";
import { Dialog } from "@base-ui/react/dialog";
import {
BotIcon,
BoxIcon,
CornerDownLeftIcon,
DownloadIcon,
GaugeIcon,
LibraryIcon,
MonitorIcon,
MoonIcon,
PaletteIcon,
PlusIcon,
ScanSearchIcon,
SearchIcon,
ServerIcon,
SunIcon,
TagIcon,
TagsIcon,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useTheme } from "next-themes";
import { useEffect, useMemo, useRef, useState } from "react";
import { cn } from "@/lib/utils";
type Index = {
models: { id: string; repoId: string; quants: string[]; status: string; tags: string[] }[];
endpoints: { id: string; name: string; model: string | null; engine: string | null }[];
benchmarks: { id: string; label: string | null; kind: string; state: string; target: string; model: string; createdAt: number }[];
tags: string[];
};
type Item = {
id: string;
group: string;
title: string;
hint?: string;
icon: React.ComponentType<{ className?: string }>;
/** Extra words that match (not shown). */
keywords?: string;
run: () => void;
};
const KIND_LABEL: Record<string, string> = { run: "speed run", ab: "A/B", eval: "quality eval" };
/** Every whitespace-separated term must appear (case-insensitive); earlier and title matches rank higher. */
function score(item: Item, terms: string[]): number {
if (terms.length === 0) return 1;
const title = item.title.toLowerCase();
const all = `${title} ${item.hint ?? ""} ${item.keywords ?? ""} ${item.group}`.toLowerCase();
let s = 0;
for (const t of terms) {
const i = all.indexOf(t);
if (i < 0) return 0;
s += title.startsWith(t) ? 4 : title.includes(t) ? 2 : 1;
}
return s;
}
/** The palette itself: loaded on first use (see command-palette.tsx), then kept mounted. */
export function CommandPaletteDialog({ open, setOpen }: { open: boolean; setOpen: (open: boolean) => void }) {
const router = useRouter();
const { setTheme } = useTheme();
const [query, setQuery] = useState("");
const [index, setIndex] = useState<Index | null>(null);
const [active, setActive] = useState(0);
const list = useRef<HTMLDivElement>(null);
// Fresh data every time it opens (the library changes while you use it).
useEffect(() => {
if (!open) return;
let stop = false;
void fetch("/api/search-index", { cache: "no-store" })
.then((r) => (r.ok ? r.json() : null))
.then((d: Index | null) => !stop && d && setIndex(d));
return () => {
stop = true;
};
}, [open]);
const go = (href: string) => () => {
setOpen(false);
router.push(href);
};
const items = useMemo<Item[]>(() => {
const out: Item[] = [
{ id: "p:library", group: "Pages", title: "Library", icon: LibraryIcon, keywords: "models home", run: go("/") },
{ id: "p:endpoints", group: "Pages", title: "Endpoints", icon: ServerIcon, keywords: "servers", run: go("/endpoints") },
{ id: "p:benchmarks", group: "Pages", title: "Benchmarks", icon: GaugeIcon, keywords: "runs compare", run: go("/benchmarks") },
{ id: "a:add-model", group: "Actions", title: "Add model", icon: PlusIcon, keywords: "download new hugging face repo", run: go("/?add=1") },
{ id: "a:new-endpoint", group: "Actions", title: "Add endpoint", icon: PlusIcon, keywords: "new server", run: go("/endpoints/new") },
{ id: "a:scan", group: "Actions", title: "Scan the models folder", icon: ScanSearchIcon, keywords: "rescan import", run: go("/settings/downloads#scan") },
{ id: "a:theme-light", group: "Actions", title: "Light theme", icon: SunIcon, keywords: "appearance", run: () => (setTheme("light"), setOpen(false)) },
{ id: "a:theme-dark", group: "Actions", title: "Dark theme", icon: MoonIcon, keywords: "appearance", run: () => (setTheme("dark"), setOpen(false)) },
{ id: "a:theme-system", group: "Actions", title: "System theme", icon: MonitorIcon, keywords: "appearance", run: () => (setTheme("system"), setOpen(false)) },
{ id: "s:labels", group: "Settings", title: "File labels", icon: TagIcon, keywords: "colors roles", run: go("/settings/labels") },
{ id: "s:tags", group: "Settings", title: "Tags", icon: TagsIcon, keywords: "rename colors", run: go("/settings/tags") },
{ 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 ?? []) {
out.push({ id: `m:${m.id}`, group: "Models", title: m.repoId, hint: m.quants.join(", ") || m.status, icon: BoxIcon, keywords: `${m.status} ${m.tags.join(" ")}`, run: go(`/${m.repoId}`) });
}
for (const e of index?.endpoints ?? []) {
out.push({ id: `e:${e.id}`, group: "Endpoints", title: e.name, hint: [e.engine, e.model].filter(Boolean).join(" · "), icon: ServerIcon, run: go(`/endpoints/${e.id}`) });
}
for (const b of index?.benchmarks ?? []) {
out.push({
id: `b:${b.id}`,
group: "Benchmarks",
title: b.label ?? `${b.target} · ${b.model}`,
hint: `${KIND_LABEL[b.kind] ?? b.kind} · ${b.state} · ${new Date(b.createdAt).toLocaleDateString()}`,
icon: GaugeIcon,
keywords: `${b.target} ${b.model}`,
run: go(`/benchmarks/${b.id}`),
});
}
for (const t of index?.tags ?? []) {
out.push({ id: `t:${t}`, group: "Tags", title: t, hint: "models with this tag", icon: TagIcon, run: go(`/?tag=${encodeURIComponent(t)}`) });
}
return out;
// `go` only closes over router and setOpen (the shell's state setter), which are stable.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [index, setTheme]);
const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
const groups = useMemo(() => {
const scored = items.map((it) => ({ it, s: score(it, terms) })).filter((x) => x.s > 0);
const order = ["Pages", "Actions", "Models", "Endpoints", "Benchmarks", "Settings", "Tags"];
// Without a query: pages, actions and settings, plus the newest few of the rest.
const per = terms.length ? 8 : 4;
return order
.map((g) => ({ g, rows: scored.filter((x) => x.it.group === g).sort((a, b) => b.s - a.s).slice(0, per).map((x) => x.it) }))
.filter((x) => x.rows.length && (terms.length || ["Pages", "Actions", "Models", "Benchmarks"].includes(x.g)));
// terms is derived from query
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [items, query]);
const flat = groups.flatMap((g) => g.rows);
const current = Math.min(active, Math.max(0, flat.length - 1));
useEffect(() => {
list.current?.querySelector(`[data-index="${current}"]`)?.scrollIntoView({ block: "nearest" });
}, [current]);
function onKeyDown(e: React.KeyboardEvent) {
if (e.key === "ArrowDown") {
e.preventDefault();
setActive((current + 1) % Math.max(1, flat.length));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive((current - 1 + flat.length) % Math.max(1, flat.length));
} else if (e.key === "Enter") {
e.preventDefault();
flat[current]?.run();
}
}
let n = -1;
return (
<Dialog.Root
open={open}
onOpenChange={(o) => {
setOpen(o);
if (!o) {
setQuery("");
setActive(0);
}
}}
>
<Dialog.Portal>
<Dialog.Backdrop className="fixed inset-0 z-50 bg-black/50 backdrop-blur-[2px] data-ending-style:opacity-0 data-starting-style:opacity-0" />
<Dialog.Popup className="fixed top-[15vh] left-1/2 z-50 flex max-h-[70vh] w-[min(40rem,calc(100vw-2rem))] -translate-x-1/2 flex-col overflow-hidden rounded-2xl bg-popover/85 text-popover-foreground shadow-2xl ring-1 ring-foreground/10 backdrop-blur-xl outline-none data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0">
<Dialog.Title className="sr-only">Search</Dialog.Title>
<div className="flex items-center gap-2 border-b px-4">
<SearchIcon className="size-4 shrink-0 text-muted-foreground" />
<input
autoFocus
value={query}
onChange={(e) => {
setQuery(e.target.value);
setActive(0);
}}
onKeyDown={onKeyDown}
placeholder="Search models, endpoints, benchmarks, settings…"
className="h-12 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
aria-label="Search"
/>
<kbd className="rounded-full border px-2 text-[10px] leading-4 text-muted-foreground">Esc</kbd>
</div>
<div ref={list} className="min-h-0 flex-1 overflow-y-auto p-2" role="listbox">
{flat.length === 0 ? (
<p className="px-3 py-8 text-center text-sm text-muted-foreground">{index ? `Nothing matches "${query}".` : "Loading…"}</p>
) : (
groups.map(({ g, rows }) => (
<div key={g} className="mb-1">
<div className="px-2 pt-2 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{g}</div>
{rows.map((it) => {
n++;
const i = n;
return (
<button
key={it.id}
type="button"
role="option"
aria-selected={i === current}
data-index={i}
onMouseMove={() => setActive(i)}
onClick={it.run}
className={cn("flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-left text-sm", i === current && "bg-muted")}
>
<it.icon className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate">{it.title}</span>
{it.hint && <span className="max-w-[45%] shrink-0 truncate text-xs text-muted-foreground">{it.hint}</span>}
{i === current && <CornerDownLeftIcon className="size-3.5 shrink-0 text-muted-foreground" />}
</button>
);
})}
</div>
))
)}
</div>
</Dialog.Popup>
</Dialog.Portal>
</Dialog.Root>
);
}
+40 -237
View File
@@ -1,258 +1,61 @@
"use client";
import { Dialog } from "@base-ui/react/dialog";
import {
BoxIcon,
CornerDownLeftIcon,
DownloadIcon,
GaugeIcon,
LibraryIcon,
MonitorIcon,
MoonIcon,
PlusIcon,
ScanSearchIcon,
SearchIcon,
ServerIcon,
SunIcon,
TagIcon,
TagsIcon,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useTheme } from "next-themes";
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { SearchIcon } from "lucide-react";
import dynamic from "next/dynamic";
import { useEffect, useState, useSyncExternalStore } from "react";
import { cn } from "@/lib/utils";
type Index = {
models: { id: string; repoId: string; quants: string[]; status: string; tags: string[] }[];
endpoints: { id: string; name: string; model: string | null; engine: string | null }[];
benchmarks: { id: string; label: string | null; kind: string; state: string; target: string; model: string; createdAt: number }[];
tags: string[];
};
// The dialog (base-ui Dialog, all items and icons) is its own chunk, kept out of every page's first
// load: most page views never open it. It starts loading when you reach for it (hovering or focusing
// the Search button, pressing ⌘ or Ctrl) and renders on the first open.
const loadDialog = () => import("./command-palette-dialog");
const CommandPaletteDialog = dynamic(() => loadDialog().then((m) => m.CommandPaletteDialog), { ssr: false });
const preload = () => void loadDialog();
type Item = {
id: string;
group: string;
title: string;
hint?: string;
icon: React.ComponentType<{ className?: string }>;
/** Extra words that match (not shown). */
keywords?: string;
run: () => void;
};
const OPEN_EVENT = "kaname:command-palette";
const KIND_LABEL: Record<string, string> = { run: "speed run", ab: "A/B", eval: "quality eval" };
/** ⌘K / Ctrl+K: jump to any model, endpoint, benchmark run, settings page or action. */
export function CommandPalette() {
const [open, setOpen] = useState(false);
// Mounted from the first open on, so it keeps its state like before.
const [used, setUsed] = useState(false);
/** Every whitespace-separated term must appear (case-insensitive); earlier and title matches rank higher. */
function score(item: Item, terms: string[]): number {
if (terms.length === 0) return 1;
const title = item.title.toLowerCase();
const all = `${title} ${item.hint ?? ""} ${item.keywords ?? ""} ${item.group}`.toLowerCase();
let s = 0;
for (const t of terms) {
const i = all.indexOf(t);
if (i < 0) return 0;
s += title.startsWith(t) ? 4 : title.includes(t) ? 2 : 1;
}
return s;
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Meta" || e.key === "Control") preload();
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
e.preventDefault();
setUsed(true);
setOpen((o) => !o);
}
};
const onOpen = () => {
setUsed(true);
setOpen(true);
};
window.addEventListener("keydown", onKey);
window.addEventListener(OPEN_EVENT, onOpen);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener(OPEN_EVENT, onOpen);
};
}, []);
return used ? <CommandPaletteDialog open={open} setOpen={setOpen} /> : null;
}
const isMac = () => /mac|iphone|ipad/i.test(navigator.platform || navigator.userAgent);
const noSubscribe = () => () => {};
/** ⌘K / Ctrl+K: jump to any model, endpoint, benchmark run, settings page or action. */
export function CommandPalette() {
const router = useRouter();
const { setTheme } = useTheme();
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const [index, setIndex] = useState<Index | null>(null);
const [active, setActive] = useState(0);
const list = useRef<HTMLDivElement>(null);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
e.preventDefault();
setOpen((o) => !o);
}
};
const onOpen = () => setOpen(true);
window.addEventListener("keydown", onKey);
window.addEventListener("kaname:command-palette", onOpen);
return () => {
window.removeEventListener("keydown", onKey);
window.removeEventListener("kaname:command-palette", onOpen);
};
}, []);
// Fresh data every time it opens (the library changes while you use it).
useEffect(() => {
if (!open) return;
let stop = false;
void fetch("/api/search-index", { cache: "no-store" })
.then((r) => (r.ok ? r.json() : null))
.then((d: Index | null) => !stop && d && setIndex(d));
return () => {
stop = true;
};
}, [open]);
const go = (href: string) => () => {
setOpen(false);
router.push(href);
};
const items = useMemo<Item[]>(() => {
const out: Item[] = [
{ id: "p:library", group: "Pages", title: "Library", icon: LibraryIcon, keywords: "models home", run: go("/") },
{ id: "p:endpoints", group: "Pages", title: "Endpoints", icon: ServerIcon, keywords: "servers", run: go("/endpoints") },
{ id: "p:benchmarks", group: "Pages", title: "Benchmarks", icon: GaugeIcon, keywords: "runs compare", run: go("/benchmarks") },
{ id: "a:add-model", group: "Actions", title: "Add model", icon: PlusIcon, keywords: "download new hugging face repo", run: go("/?add=1") },
{ id: "a:new-endpoint", group: "Actions", title: "Add endpoint", icon: PlusIcon, keywords: "new server", run: go("/endpoints/new") },
{ id: "a:scan", group: "Actions", title: "Scan the models folder", icon: ScanSearchIcon, keywords: "rescan import", run: go("/settings/downloads#scan") },
{ id: "a:theme-light", group: "Actions", title: "Light theme", icon: SunIcon, keywords: "appearance", run: () => (setTheme("light"), setOpen(false)) },
{ id: "a:theme-dark", group: "Actions", title: "Dark theme", icon: MoonIcon, keywords: "appearance", run: () => (setTheme("dark"), setOpen(false)) },
{ id: "a:theme-system", group: "Actions", title: "System theme", icon: MonitorIcon, keywords: "appearance", run: () => (setTheme("system"), setOpen(false)) },
{ id: "s:labels", group: "Settings", title: "File labels", icon: TagIcon, keywords: "colors roles", run: go("/settings/labels") },
{ id: "s:tags", group: "Settings", title: "Tags", icon: TagsIcon, keywords: "rename colors", run: go("/settings/tags") },
{ 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") },
];
for (const m of index?.models ?? []) {
out.push({ id: `m:${m.id}`, group: "Models", title: m.repoId, hint: m.quants.join(", ") || m.status, icon: BoxIcon, keywords: `${m.status} ${m.tags.join(" ")}`, run: go(`/${m.repoId}`) });
}
for (const e of index?.endpoints ?? []) {
out.push({ id: `e:${e.id}`, group: "Endpoints", title: e.name, hint: [e.engine, e.model].filter(Boolean).join(" · "), icon: ServerIcon, run: go(`/endpoints/${e.id}`) });
}
for (const b of index?.benchmarks ?? []) {
out.push({
id: `b:${b.id}`,
group: "Benchmarks",
title: b.label ?? `${b.target} · ${b.model}`,
hint: `${KIND_LABEL[b.kind] ?? b.kind} · ${b.state} · ${new Date(b.createdAt).toLocaleDateString()}`,
icon: GaugeIcon,
keywords: `${b.target} ${b.model}`,
run: go(`/benchmarks/${b.id}`),
});
}
for (const t of index?.tags ?? []) {
out.push({ id: `t:${t}`, group: "Tags", title: t, hint: "models with this tag", icon: TagIcon, run: go(`/?tag=${encodeURIComponent(t)}`) });
}
return out;
// `go` only closes over router and setOpen, which are stable.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [index, setTheme]);
const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
const groups = useMemo(() => {
const scored = items.map((it) => ({ it, s: score(it, terms) })).filter((x) => x.s > 0);
const order = ["Pages", "Actions", "Models", "Endpoints", "Benchmarks", "Settings", "Tags"];
// Without a query: pages, actions and settings, plus the newest few of the rest.
const per = terms.length ? 8 : 4;
return order
.map((g) => ({ g, rows: scored.filter((x) => x.it.group === g).sort((a, b) => b.s - a.s).slice(0, per).map((x) => x.it) }))
.filter((x) => x.rows.length && (terms.length || ["Pages", "Actions", "Models", "Benchmarks"].includes(x.g)));
// terms is derived from query
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [items, query]);
const flat = groups.flatMap((g) => g.rows);
const current = Math.min(active, Math.max(0, flat.length - 1));
useEffect(() => {
list.current?.querySelector(`[data-index="${current}"]`)?.scrollIntoView({ block: "nearest" });
}, [current]);
function onKeyDown(e: React.KeyboardEvent) {
if (e.key === "ArrowDown") {
e.preventDefault();
setActive((current + 1) % Math.max(1, flat.length));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive((current - 1 + flat.length) % Math.max(1, flat.length));
} else if (e.key === "Enter") {
e.preventDefault();
flat[current]?.run();
}
}
let n = -1;
return (
<Dialog.Root
open={open}
onOpenChange={(o) => {
setOpen(o);
if (!o) {
setQuery("");
setActive(0);
}
}}
>
<Dialog.Portal>
<Dialog.Backdrop className="fixed inset-0 z-50 bg-black/50 backdrop-blur-[2px] data-ending-style:opacity-0 data-starting-style:opacity-0" />
<Dialog.Popup className="fixed top-[15vh] left-1/2 z-50 flex max-h-[70vh] w-[min(40rem,calc(100vw-2rem))] -translate-x-1/2 flex-col overflow-hidden rounded-2xl bg-popover/85 text-popover-foreground shadow-2xl ring-1 ring-foreground/10 backdrop-blur-xl outline-none data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0">
<Dialog.Title className="sr-only">Search</Dialog.Title>
<div className="flex items-center gap-2 border-b px-4">
<SearchIcon className="size-4 shrink-0 text-muted-foreground" />
<input
autoFocus
value={query}
onChange={(e) => {
setQuery(e.target.value);
setActive(0);
}}
onKeyDown={onKeyDown}
placeholder="Search models, endpoints, benchmarks, settings…"
className="h-12 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
aria-label="Search"
/>
<kbd className="rounded-full border px-2 text-[10px] leading-4 text-muted-foreground">Esc</kbd>
</div>
<div ref={list} className="min-h-0 flex-1 overflow-y-auto p-2" role="listbox">
{flat.length === 0 ? (
<p className="px-3 py-8 text-center text-sm text-muted-foreground">{index ? `Nothing matches "${query}".` : "Loading…"}</p>
) : (
groups.map(({ g, rows }) => (
<div key={g} className="mb-1">
<div className="px-2 pt-2 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{g}</div>
{rows.map((it) => {
n++;
const i = n;
return (
<button
key={it.id}
type="button"
role="option"
aria-selected={i === current}
data-index={i}
onMouseMove={() => setActive(i)}
onClick={it.run}
className={cn("flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-left text-sm", i === current && "bg-muted")}
>
<it.icon className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate">{it.title}</span>
{it.hint && <span className="max-w-[45%] shrink-0 truncate text-xs text-muted-foreground">{it.hint}</span>}
{i === current && <CornerDownLeftIcon className="size-3.5 shrink-0 text-muted-foreground" />}
</button>
);
})}
</div>
))
)}
</div>
</Dialog.Popup>
</Dialog.Portal>
</Dialog.Root>
);
}
/** The menu button that opens the palette, showing its shortcut. */
export function CommandPaletteButton({ className }: { className?: string }) {
const mac = useSyncExternalStore(noSubscribe, isMac, () => false);
return (
<button
type="button"
onClick={() => window.dispatchEvent(new Event("kaname:command-palette"))}
onClick={() => window.dispatchEvent(new Event(OPEN_EVENT))}
onPointerEnter={preload}
onFocus={preload}
className={cn("flex h-8 items-center gap-2 rounded-lg px-2 text-sm text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground", className)}
aria-label="Search"
>
+73 -19
View File
@@ -1,60 +1,102 @@
"use client";
import { useEffect, useRef } from "react";
import { ADAM_DOTS, ADAM_H, ADAM_W } from "./adam-dots";
import { createContext, useContext, useEffect, useMemo, useRef } from "react";
import type { Backdrop } from "@/lib/backdrop";
const SPACING = 6; // CSS px between dot centres
const levels = Uint8Array.from(ADAM_DOTS, (c) => parseInt(c, 16));
type Grid = { w: number; h: number; levels: Uint8Array };
const parse = (dots: string) => Uint8Array.from(dots, (c) => parseInt(c, 16));
// The brightness grid (26 KB of text) is its own chunk, shared by every page and parsed once per
// tab. Imported statically, it was copied into each page's chunk.
let grid: Promise<Grid> | null = null;
const loadGrid = () =>
(grid ??= import("./adam-dots").then(({ ADAM_DOTS, ADAM_H, ADAM_W }) => ({
w: ADAM_W,
h: ADAM_H,
levels: parse(ADAM_DOTS),
})));
const BackdropContext = createContext<Backdrop | null>(null);
/** Provides the custom picture from Settings → Appearance (null for the built-in painting). */
export function BackdropProvider({ backdrop, children }: { backdrop: Backdrop | null; children: React.ReactNode }) {
return <BackdropContext.Provider value={backdrop}>{children}</BackdropContext.Provider>;
}
/**
* The Creation of Adam as a dot matrix. `view` is the horizontal slice of the painting (0–1) that
* fills the box (at least covering it), placed so `focus` (the hands) lands at `anchor` (x, y as
* fractions of the box) as far as the painting's edges allow. Dots use the element's text color; bright parts of the painting get big dots in
* dark mode, dark parts in light mode, so it reads as the painting either way.
*
* With a custom picture (Settings → Appearance, or `source`), that picture covers the box instead,
* with its own focus point at `anchor`; `view` and `focus` only apply to the built-in painting.
*/
export function DotPainting({
className,
view = 0.7,
focus = [0.48, 0.42],
anchor = [0.68, 0.5],
source,
}: {
className?: string;
view?: number;
focus?: [number, number];
anchor?: [number, number];
/** Draw this picture instead of the one from the settings (the Appearance preview). */
source?: Backdrop | null;
}) {
const ref = useRef<HTMLCanvasElement>(null);
const fromSettings = useContext(BackdropContext);
const custom = source !== undefined ? source : fromSettings;
const customGrid = useMemo(() => (custom ? { w: custom.w, h: custom.h, levels: parse(custom.dots) } : null), [custom]);
const [fx, fy] = focus;
const [fx, fy] = custom ? custom.focus : focus;
const [ax, ay] = anchor;
const v = custom ? 1 : view;
useEffect(() => {
const canvas = ref.current;
if (!canvas) return;
let data: Grid | null = customGrid;
let cancelled = false;
let frame = 0;
// What the canvas shows (size, pixel ratio, theme, color): a drawing takes tens of ms, so skip it
// when nothing changed, e.g. for the ResizeObserver's first callback or another class on <html>.
let drawn = "";
const draw = () => {
frame = 0;
if (!data) return;
const { width, height } = canvas.getBoundingClientRect();
if (!width || !height) return;
const dpr = window.devicePixelRatio || 1;
const color = getComputedStyle(canvas).color;
const dark = document.documentElement.classList.contains("dark");
const key = `${width}x${height}@${dpr} ${dark} ${color}`;
if (key === drawn) return;
drawn = key;
const { w, h, levels } = data;
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
const g = canvas.getContext("2d")!;
g.setTransform(dpr, 0, 0, dpr, 0, 0);
g.clearRect(0, 0, width, height);
g.fillStyle = getComputedStyle(canvas).color;
const dark = document.documentElement.classList.contains("dark");
g.fillStyle = color;
// CSS px per grid cell: `view` of the painting's width fills the box (at least covering it).
const scale = Math.max(width / (view * ADAM_W), height / ADAM_H);
const offX = ax * width - fx * ADAM_W * scale;
const offY = ay * height - fy * ADAM_H * scale;
const scale = Math.max(width / (v * w), height / h);
const offX = ax * width - fx * w * scale;
const offY = ay * height - fy * h * scale;
const clampOff = (o: number, box: number, size: number) => Math.min(0, Math.max(box - size, o));
const ox = clampOff(offX, width, ADAM_W * scale);
const oy = clampOff(offY, height, ADAM_H * scale);
const ox = clampOff(offX, width, w * scale);
const oy = clampOff(offY, height, h * scale);
const maxR = SPACING * 0.48;
for (let y = SPACING / 2; y < height; y += SPACING) {
const iy = Math.min(ADAM_H - 1, Math.max(0, Math.floor((y - oy) / scale)));
const iy = Math.min(h - 1, Math.max(0, Math.floor((y - oy) / scale)));
for (let x = SPACING / 2; x < width; x += SPACING) {
const ix = Math.min(ADAM_W - 1, Math.max(0, Math.floor((x - ox) / scale)));
const v = levels[iy * ADAM_W + ix] / 15;
const r = maxR * (dark ? v : 1 - v);
const ix = Math.min(w - 1, Math.max(0, Math.floor((x - ox) / scale)));
const level = levels[iy * w + ix] / 15;
const r = maxR * (dark ? level : 1 - level);
if (r < 0.35) continue;
g.beginPath();
g.arc(x, y, r, 0, Math.PI * 2);
@@ -62,17 +104,29 @@ export function DotPainting({
}
}
};
draw();
const resize = new ResizeObserver(draw);
// While a window is resized, observations arrive every frame: draw at most once per frame.
const schedule = () => {
if (!frame) frame = requestAnimationFrame(draw);
};
if (data) draw();
else
void loadGrid().then((g) => {
if (cancelled) return;
data = g;
draw();
});
const resize = new ResizeObserver(schedule);
resize.observe(canvas);
// next-themes switches the class on <html>.
const theme = new MutationObserver(draw);
const theme = new MutationObserver(schedule);
theme.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
return () => {
cancelled = true;
cancelAnimationFrame(frame);
resize.disconnect();
theme.disconnect();
};
}, [view, fx, fy, ax, ay]);
}, [customGrid, v, fx, fy, ax, ay]);
return <canvas ref={ref} aria-hidden className={className} />;
}
+7 -1
View File
@@ -1,10 +1,14 @@
"use client";
import { toast } from "sonner";
import { pokeLive } from "@/lib/live-store";
async function post(url: string): Promise<boolean> {
const res = await fetch(url, { method: "POST" });
if (res.ok) return true;
if (res.ok) {
pokeLive(); // show the new job state now instead of on the next poll
return true;
}
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Request failed (${res.status})`);
return false;
@@ -32,6 +36,7 @@ export async function startUpdate(modelId: string): Promise<boolean> {
return ok;
}
/** Let a download requested through the API start. */
export async function approveJob(jobId: string): Promise<boolean> {
const ok = await post(`/api/jobs/${jobId}/approve`);
if (ok) toast.success("Approved; the download is queued");
@@ -46,6 +51,7 @@ export async function rejectJob(jobId: string): Promise<{ removedModel: boolean
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;
}
+14
View File
@@ -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 (
<Badge variant="outline" className={cn("gap-1 font-normal", className)} title={`Requested through the API with the token "${name}"`}>
<BotIcon className="size-3" />
{name}
</Badge>
);
}
+29 -14
View File
@@ -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";
@@ -34,8 +34,11 @@ function UserAvatar({ user, size }: { user: MenuUser; size?: "sm" | "default" |
);
}
/** Avatar from the OIDC profile; opens a menu with account info, settings, theme and sign out. */
export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutAction: () => Promise<void> }) {
/**
* Avatar from the OIDC profile; opens a menu with account info, settings, theme and sign out.
* Without signOutAction (login off) there's no account to show or sign out of.
*/
export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutAction?: () => Promise<void> }) {
const { theme, setTheme } = useTheme();
const [signingOut, startSignOut] = useTransition();
@@ -49,13 +52,17 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
<UserAvatar user={user} />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
<div className="flex items-center gap-3 px-1.5 py-2">
<UserAvatar user={user} size="lg" />
<div className="flex min-w-0 flex-col">
<span className="truncate text-sm font-medium">{user.name ?? "Signed in"}</span>
{user.email && <span className="truncate text-xs text-muted-foreground">{user.email}</span>}
{signOutAction ? (
<div className="flex items-center gap-3 px-1.5 py-2">
<UserAvatar user={user} size="lg" />
<div className="flex min-w-0 flex-col">
<span className="truncate text-sm font-medium">{user.name ?? "Signed in"}</span>
{user.email && <span className="truncate text-xs text-muted-foreground">{user.email}</span>}
</div>
</div>
</div>
) : (
<p className="px-1.5 py-2 text-xs text-muted-foreground">Login is off: anyone who can reach Kaname can use it.</p>
)}
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuLabel>Settings</DropdownMenuLabel>
@@ -71,6 +78,10 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
<DownloadIcon />
Downloads
</DropdownMenuItem>
<DropdownMenuItem render={<Link href="/settings/api-tokens" />}>
<BotIcon />
API tokens
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
@@ -90,11 +101,15 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
</DropdownMenuRadioItem>
</DropdownMenuRadioGroup>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" disabled={signingOut} onClick={() => startSignOut(() => signOutAction())}>
<LogOutIcon />
{signingOut ? "Signing out…" : "Sign out"}
</DropdownMenuItem>
{signOutAction && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" disabled={signingOut} onClick={() => startSignOut(() => signOutAction())}>
<LogOutIcon />
{signingOut ? "Signing out…" : "Sign out"}
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
);
+3 -16
View File
@@ -1,25 +1,12 @@
"use client";
import { useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { useWorkerStatus } from "@/hooks/use-live";
import type { WorkerStatus } from "@/lib/worker-status";
/** Polls /api/status and shows whether the background worker is alive. */
/** Shows whether the background worker is alive (from the page's live poll, or /api/status). */
export function WorkerIndicator({ initial }: { initial: WorkerStatus }) {
const [status, setStatus] = useState(initial);
useEffect(() => {
const tick = async () => {
try {
const res = await fetch("/api/status", { cache: "no-store" });
if (res.ok) setStatus((await res.json()).worker);
} catch {
// keep last known state
}
};
const id = setInterval(tick, 10_000);
return () => clearInterval(id);
}, []);
const status = useWorkerStatus(initial);
// Online: just a green dot (details on hover); offline stays spelled out.
if (status.online) {
+22 -47
View File
@@ -1,58 +1,33 @@
"use client";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import type { JobFileSnapshot, JobSnapshot, LogLine } from "@/lib/jobs";
import { useCallback, useSyncExternalStore } from "react";
import type { LiveQuery } from "@/lib/live-protocol";
import { EMPTY_LIVE, type LiveState, liveStore } from "@/lib/live-store";
import type { WorkerStatus } from "@/lib/worker-status";
export type LiveSnapshot = { worker: WorkerStatus; jobs: JobSnapshot[]; files: JobFileSnapshot[] };
export const TERMINAL_STATES = ["completed", "failed", "cancelled", "interrupted"];
const MAX_LOG_LINES = 5000;
/**
* Subscribe to /api/stream. Re-renders on every snapshot; refreshes server components
* (model status, library) when a job reaches a terminal state.
* Live job state for a query (see src/lib/live-store.ts). Components showing the same query share
* one poller. When a job reaches a terminal state, server components are refreshed (model status,
* library).
*/
export function useLive(query: { model?: string; job?: string } = {}, withLogs = false) {
export function useLive(query: LiveQuery = {}, withLogs = false): LiveState {
const router = useRouter();
const [snapshot, setSnapshot] = useState<LiveSnapshot | null>(null);
const [logs, setLogs] = useState<LogLine[]>([]);
const [connected, setConnected] = useState(false);
const states = useRef(new Map<string, string>());
const { model, job } = query;
const subscribe = useCallback(
(listener: () => void) => liveStore().subscribe({ model, job }, withLogs, listener, () => router.refresh()),
[model, job, withLogs, router],
);
const getSnapshot = useCallback(() => liveStore().get({ model, job }, withLogs), [model, job, withLogs]);
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}
const params = new URLSearchParams();
if (query.model) params.set("model", query.model);
if (query.job) params.set("job", query.job);
const url = `/api/stream${params.size ? `?${params}` : ""}`;
const getServerSnapshot = () => EMPTY_LIVE;
const subscribeWorker = (listener: () => void) => liveStore().subscribeWorker(listener);
const getWorker = () => liveStore().getWorker();
const noWorker = () => null;
useEffect(() => {
const es = new EventSource(url);
es.onopen = () => setConnected(true);
es.onerror = () => setConnected(false);
es.addEventListener("snapshot", (e) => {
const snap = JSON.parse((e as MessageEvent).data) as LiveSnapshot;
let finished = false;
for (const j of snap.jobs) {
const prev = states.current.get(j.id);
if (prev && prev !== j.state && TERMINAL_STATES.includes(j.state)) finished = true;
states.current.set(j.id, j.state);
}
setSnapshot(snap);
if (finished) router.refresh();
});
if (withLogs) {
es.addEventListener("logs", (e) => {
const lines = JSON.parse((e as MessageEvent).data) as LogLine[];
setLogs((prev) => {
const seen = prev.length ? prev[prev.length - 1].id : 0;
const merged = prev.concat(lines.filter((l) => l.id > seen));
return merged.length > MAX_LOG_LINES ? merged.slice(-MAX_LOG_LINES) : merged;
});
});
}
return () => es.close();
}, [url, withLogs, router]);
return { snapshot, logs, connected };
/** The worker status: from the live poll when one runs, otherwise /api/status every 10 s. */
export function useWorkerStatus(initial: WorkerStatus): WorkerStatus {
return useSyncExternalStore(subscribeWorker, getWorker, noWorker) ?? initial;
}
+66
View File
@@ -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<void> {
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<ActivityRow[]> {
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<T extends object>(token: TokenIdentity, action: string, target: { type: string; id?: string | null }, fn: () => Promise<T>): Promise<T> {
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;
}
}
+267
View File
@@ -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<number> {
const [r] = await db()
.select({ n: sql<number>`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<number> {
const [r] = await db()
.select({ n: sql<number>`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<DownloadOutcome> {
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<void> {
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<number>`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 };
}
+136
View File
@@ -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<string, unknown>;
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(" · ");
}
+62
View File
@@ -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<string, { quant: string; files: number; bytes: number }>();
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>): string[] {
const have = new Set(selected);
return requested.filter((p) => !have.has(p));
}
+192
View File
@@ -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<typeof DEFAULT_GUARDRAILS>, x: Partial<GuardrailInput>, 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"));
});
});
+4 -4
View File
@@ -1,15 +1,15 @@
import "server-only";
import type { Session } from "next-auth";
import { NextResponse } from "next/server";
import { auth } from "@/auth";
import { currentSession } from "@/auth";
type Handler<Ctx> = (req: Request, ctx: Ctx & { session: Session }) => Promise<Response> | Response;
/** Wraps a route handler so it only runs for a logged-in user (defense in depth behind proxy.ts). */
/** Wraps a route handler so it only runs for a logged-in user (anyone while login is off) (defense in depth behind proxy.ts). */
export function withAuth<Ctx = unknown>(handler: Handler<Ctx>) {
return async (req: Request, ctx: Ctx) => {
const session = await auth();
if (!session?.user) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
const session = await currentSession();
if (!session) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
return handler(req, { ...ctx, session });
};
}
+32
View File
@@ -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);
}
+113
View File
@@ -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<typeof apiTokens.$inferSelect, "hash">;
/** lastUsedAt is written at most this often per token, not on every request. */
const TOUCH_MS = 60_000;
export async function listTokens(): Promise<ApiTokenRow[]> {
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<void> {
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<void> {
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<void> {
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<TokenIdentity | null> {
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<Ctx> = (req: Request, ctx: Ctx & { token: TokenIdentity }) => Promise<Response> | Response;
/**
* Wraps a /api/v1 route: requires `Authorization: Bearer <token>` with one of `scopes` (null: any
* valid token). Login sessions don't count here; the rest of the app uses the OIDC login (or none).
*/
export function withToken<Ctx = unknown>(scopes: TokenScope | TokenScope[] | null, handler: Handler<Ctx>) {
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 });
};
}
+26
View File
@@ -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<Facet, string> = {
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 };
}
+294
View File
@@ -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<Response>;
const call = async (handler: Handler, path: string, opts: { token?: string; body?: unknown; method?: string; params?: Record<string, string> } = {}) => {
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<string, any> }; // eslint-disable-line @typescript-eslint/no-explicit-any
};
const post = (handler: Handler, path: string, token: string, params: Record<string, string>, body: unknown = {}) => call(handler, path, { token, body, params });
async function setFiles(modelId: string, states: Record<string, "present" | "missing" | "hash_mismatch">) {
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<string, unknown>) {
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));
});
});
+307
View File
@@ -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<string, { sha: string; files: [string, number][] }> = {
"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<Response>, path: string, opts: { token?: string; body?: unknown; params?: Record<string, string> } = {}) => {
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<string, any> }; // 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);
});
});
+54
View File
@@ -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<Record<HubError["code"], number>> = {
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<unknown> {
const text = await req.text();
return text.trim() ? JSON.parse(text) : {};
}
+19
View File
@@ -0,0 +1,19 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { parseBackdrop } from "./backdrop";
const valid = { w: 10, h: 8, dots: "0123456789abcdef".repeat(5), focus: [0.3, 0.7] };
test("parseBackdrop keeps a valid grid", () => {
assert.deepEqual(parseBackdrop(valid), valid);
});
test("parseBackdrop rejects broken grids", () => {
assert.equal(parseBackdrop(null), null);
assert.equal(parseBackdrop({ ...valid, dots: valid.dots.slice(1) }), null);
assert.equal(parseBackdrop({ ...valid, dots: valid.dots.replace("a", "g") }), null);
assert.equal(parseBackdrop({ ...valid, w: 4, dots: "0".repeat(32) }), null);
assert.equal(parseBackdrop({ ...valid, w: 241, dots: "0".repeat(241 * 8) }), null);
assert.equal(parseBackdrop({ ...valid, focus: [0.5, 1.5] }), null);
assert.equal(parseBackdrop({ ...valid, focus: [0.5] }), null);
});
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff. Show more