Compare commits
10
Commits
v0.9.0
...
backup-0.14.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d2f908b75 | ||
|
|
4f05ee165c | ||
|
|
22a54f731d | ||
|
|
6b67c653b5 | ||
|
|
716bd8f2f0 | ||
|
|
e007a35143 | ||
|
|
ee6c623e2a | ||
|
|
981c4170fc | ||
|
|
93edb198d8 | ||
|
|
7b1c8070b3 |
No files matched your search
+237
-1
@@ -4,7 +4,243 @@ 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.14.3] - 2026-10-22
|
||||
|
||||
### Fixed
|
||||
|
||||
- Downloads over Xet (any download with a file over 50 GB, or all of them with
|
||||
`HF_HUB_DISABLE_XET=false`) showed little or no progress. Xet keeps downloaded data in memory and
|
||||
writes the file in large chunks, sometimes minutes apart, so the bytes on disk don't show what has
|
||||
arrived. For Xet downloads the worker now turns on `hf`'s progress bars and reads its running
|
||||
byte count; the bars stay out of the job log. Ordinary downloads still measure the files on disk.
|
||||
|
||||
## [0.14.2] - 2026-10-22
|
||||
|
||||
### Fixed
|
||||
|
||||
- A running download's progress could jump back and forth between the real value and 0 B while
|
||||
`hf` kept downloading. A single progress reading that missed the partial file (a folder changing
|
||||
while the worker listed it, or a stale size on a network share) counted as nothing downloaded.
|
||||
Folders that vanish mid-listing are now skipped instead of failing the whole listing, and a file's
|
||||
progress no longer goes backwards during a run.
|
||||
|
||||
## [0.14.1] - 2026-10-22
|
||||
|
||||
### Fixed
|
||||
|
||||
- Downloads with a file over 50 GB failed with "The file is too large to be downloaded using the
|
||||
regular download method". `hf` (huggingface_hub 2.1.1) only downloads such files over Xet, which
|
||||
Kaname turns off by default for steady progress; a download that includes one now uses Xet (noted
|
||||
in the job log; its progress grows in bursts).
|
||||
|
||||
## [0.14.0] - 2026-10-21
|
||||
|
||||
A quality eval next to the speed benchmarks: a short, deterministic check of tool calling, coding and
|
||||
long-context retrieval, so a launch option that makes a model faster but worse shows up.
|
||||
|
||||
No changes to `compose.yaml` or `.env`. The new column is added on start.
|
||||
|
||||
### Added
|
||||
|
||||
- **Quality eval** as a run type (deployment page → Benchmark → Quality), run against a deployment
|
||||
with greedy decoding, a fixed seed and thinking turned off:
|
||||
- **tool calling**: 12 requests; one tool call with valid JSON, the right function and arguments;
|
||||
- **coding**: 8 short Python functions, checked by unit tests in a throwaway container from Kaname's
|
||||
own image (no network, read-only, unprivileged user, no capabilities, CPU/memory/process limits);
|
||||
- **long-context retrieval**: a code hidden at 10/50/90 % depth in texts of 25/50/100 % of the
|
||||
context, sized with the server's own tokenizer.
|
||||
The score (0–100) is the mean pass rate of the sections that could run; a server that refuses tool
|
||||
calls doesn't count as 0. The eval set is versioned data in the repo (`src/evals/v1`), and every
|
||||
result records its version (`kaname-eval-1`).
|
||||
- The run page shows the score, each section and every item with the reason it failed. Compare views
|
||||
get a "Quality" group; the benchmark list shows the score; sweeps can run the eval on every variant
|
||||
("Also run the quality eval") and show it as a column.
|
||||
- API: `POST /api/v1/benchmarks` with `kind: "eval"` (optional `sections`), `quality` in run, sweep
|
||||
and compare answers, `"quality": true` for sweeps; the same guardrails as other runs.
|
||||
- The tuning skill checks quality after speed and reports both.
|
||||
|
||||
## [0.13.0] - 2026-10-21
|
||||
|
||||
The agent API can now deploy and benchmark models, so an AI agent can tune launch options for the
|
||||
hardware: within guardrails you set, only on deployments its own token created, and by default only
|
||||
after you approve each start, run and sweep.
|
||||
|
||||
No changes to `compose.yaml` or `.env`. The new columns and table are added on start. Existing
|
||||
tokens keep their scopes; grant the new ones with **Scopes** in Settings → API tokens.
|
||||
|
||||
### Added
|
||||
|
||||
- **Token scopes** `deployments:read`, `deployments:write`, `benchmarks:read`, `benchmarks:run`, and
|
||||
editing an existing token's scopes.
|
||||
- **`/api/v1` for deployments** ([docs/api.md](docs/api.md)):
|
||||
- `GET /api/v1/runtimes`: pulled runtimes, what they serve, whether agents may use them and which
|
||||
extra arguments; the host's GPUs.
|
||||
- `GET /api/v1/deployments`, `GET /api/v1/deployments/{id}`: state, endpoint, options, the engine
|
||||
version and slots, live CPU/RAM; the log with `?log=N`.
|
||||
- `POST /api/v1/deployments` with the same validation, memory/VRAM estimate and `docker run`
|
||||
command as the form (returned in the answer); `dryRun: true` only checks. Unknown fields are
|
||||
refused instead of ignored.
|
||||
- `PATCH`, `POST …/start`, `POST …/stop`, `DELETE` for the token's own deployments.
|
||||
- **`/api/v1` for benchmarks**: `POST /api/v1/benchmarks` (run or A/B, quick or full, phases,
|
||||
description), `GET /api/v1/benchmarks/{id}` with a compact result (headline numbers, the run's
|
||||
hardware/runtime/model setup, GPU and RAM use; the full summary with `?full=1`), cancel, a list,
|
||||
`GET /api/v1/benchmarks/compare?ids=` (what differs, what's the same), and sweeps
|
||||
(`POST /api/v1/sweeps`, `GET /api/v1/sweeps/{id}`, cancel).
|
||||
- **`?wait=<seconds>`** (max 900) on the job, deployment, run and sweep status endpoints: the request
|
||||
returns once the state settles, so agents make one call instead of polling. Things that wait for
|
||||
approval answer right away.
|
||||
- **Guardrails for API deployments and benchmarks** (Settings → API tokens): approval (default: ask
|
||||
me), agent deployments at once (1), one agent run or sweep at a time and no agent start while one
|
||||
runs, time limits per run and sweep (30 min / 3 h, enforced by the worker), max sweep variants (8),
|
||||
a runtime allowlist, an allowlist of extra argument flags per engine (values can't be paths or
|
||||
URLs; the error names the argument), host ports only within a range (none by default), and caps
|
||||
for memory and CPUs (agent deployments always get a memory limit).
|
||||
- **Protected deployments**: the Protect button on a deployment's page. Agents can't edit, stop,
|
||||
delete or benchmark it, nor start anything on the same GPUs that would crowd it out of VRAM
|
||||
(estimated).
|
||||
- **Approval** for agent starts, runs and sweeps on the deployment, run and sweep pages; "awaiting
|
||||
approval" in the lists.
|
||||
- Everything an agent creates shows **requested by <token>**, with a filter in the deployment
|
||||
and benchmark lists; an **activity log** per token (Settings → API tokens) lists every request,
|
||||
including refusals with their error code.
|
||||
- **Agent skill for tuning** ([docs/agent/SKILL-tuning.md](docs/agent/SKILL-tuning.md)): check the
|
||||
limits, pick a runtime, deploy (dry run first), wait until ready, benchmark, change one variable at a
|
||||
time (or sweep), compare, report a compact table, stop the deployment; no polling loops, stop when
|
||||
something needs approval, never work around a guardrail.
|
||||
|
||||
### Changed
|
||||
|
||||
- The download skill and messages use `?wait=` instead of "check again later".
|
||||
|
||||
## [0.12.0] - 2026-10-21
|
||||
|
||||
Intel GPU support (Arc A- and B-series, Arc Pro): telemetry during benchmarks, presets, render group
|
||||
handling and a VRAM estimate for NVIDIA and Intel alike. Host prerequisites are on the wiki page
|
||||
"Intel GPUs".
|
||||
|
||||
No changes to `compose.yaml` or `.env`.
|
||||
|
||||
### Added
|
||||
|
||||
- **GPU telemetry for Intel and AMD** in benchmark runs, A/B and sweeps, with the same fields as
|
||||
NVIDIA (VRAM in use, utilization, power, temperature):
|
||||
- power and temperature from the GPU's hwmon sensors (energy counter or power reading);
|
||||
- AMD: VRAM in use and busy percent from sysfs;
|
||||
- Intel: VRAM in use and utilization summed from every process's DRM fdinfo (the only place the
|
||||
`xe`/`i915` drivers report them), read by a probe container that runs only during the run: host
|
||||
PID namespace, `SYS_PTRACE` and `DAC_READ_SEARCH` only, no network, read-only, removed at the
|
||||
end. Utilization is the busiest engine class, like `intel_gpu_top`.
|
||||
- **Temperature** for every GPU (NVIDIA too), shown in the run's resources and, with GPU power, as
|
||||
sweep table columns.
|
||||
- **VRAM estimate** in the deployment form for NVIDIA and Intel/AMD: weights, KV cache and compute
|
||||
buffers for llama.cpp with all layers on the GPU, the reserved share for vLLM, against the GPUs'
|
||||
VRAM, with a hint when it doesn't fit.
|
||||
- **Render group handling**: the worker reads the group IDs of the host's `/dev/dri` nodes (render,
|
||||
video) and adds them to Intel/AMD runtime containers, so images that don't run as root can use the
|
||||
GPU.
|
||||
- The llama.cpp **Intel SYCL and Vulkan runtimes are added** the first time an Intel GPU is detected.
|
||||
|
||||
### Changed
|
||||
|
||||
- The llama.cpp Intel (SYCL) preset sets `ZES_ENABLE_SYSMAN=1`, so llama.cpp sees free VRAM (needed
|
||||
by `-ngl auto`). Preset descriptions mention the B-series.
|
||||
- GPU figures a source doesn't report are now shown as "—" instead of 0.
|
||||
|
||||
## [0.11.0] - 2026-10-20
|
||||
|
||||
Every benchmark run now records what it ran on: GPUs with their PCIe link and Resizable BAR, the
|
||||
runtime image and the engine version the server reports, model, quant and KV cache type, context and
|
||||
concurrency, plus a system summary and your own description. All of it is shown on the run page, in
|
||||
compare views and sweep tables, and goes to BetterBench and the launch80 preview.
|
||||
|
||||
No changes to `compose.yaml` or `.env`. The new columns are added on start.
|
||||
|
||||
### Added
|
||||
|
||||
- **Run metadata**, recorded when a run starts (single runs, A/B and sweep variants):
|
||||
- GPU count, name and VRAM; PCIe link, current and maximum (e.g. "Gen4 x8 of Gen5 x16"), read
|
||||
from sysfs at the card's upstream port (behind on-card switches like Intel's Arc B-series) or
|
||||
from `nvidia-smi`; peer-to-peer between GPUs (`nvidia-smi topo -p2p`, "n/a" with one GPU);
|
||||
Resizable BAR (on when a BAR covers the VRAM).
|
||||
- GPUs slow their link down when idle, so the current link is sampled during the run and the
|
||||
fastest one seen under load is recorded ("at idle" when it couldn't be sampled).
|
||||
- Runtime image, tag and registry digest, and the engine version the server reports once it's
|
||||
ready (llama.cpp `/props` build, vLLM `/version`, falling back to the startup log). Runtimes have
|
||||
an optional **engine name** for forks (e.g. `vllm-radiance`).
|
||||
- Model, quant and KV cache type (e.g. "Q4_K_M with q8_0 KV cache"), context length and
|
||||
concurrency (llama.cpp slots as reported by the server, vLLM max sequences).
|
||||
- **System summary** per run: CPU model, cores and threads, RAM, the disk holding the models
|
||||
folder, OS and kernel, GPU driver versions, VM or bare metal with GPU passthrough, Kaname version.
|
||||
Only these whitelisted facts; never the hostname, IP addresses, users or paths.
|
||||
- **Description** per run: set it when starting a run or edit it on the run page.
|
||||
- Everything goes to BetterBench as `--note`s (in `results.json` and its report) and into the
|
||||
launch80 dry-run preview as page sections (description, hardware and runtime, system), visible in
|
||||
the preview before anything is sent.
|
||||
- **Settings → Hardware**: what was detected, with manual values for what detection can't see (in a
|
||||
VM the PCIe link is the one the VM sees; new GPUs missing from the PCI ID list). New runs use them.
|
||||
- The run page shows the metadata; compare views get a "Hardware & runtime" section and a prefill
|
||||
row in the headline; sweep tables list the setup shared by all variants and show what differs as
|
||||
columns.
|
||||
- `scripts/intel-probe.sh`: read-only diagnostics for Intel GPU hosts (link, BARs, hwmon, DRM
|
||||
fdinfo, `/dev/dri` groups), for the upcoming Intel GPU support.
|
||||
|
||||
### Changed
|
||||
|
||||
- The image includes the PCI ID database (`pci.ids`) for GPU names.
|
||||
|
||||
### Fixed
|
||||
|
||||
- A run or sweep with both "quick" and an explicit number of passes failed (BetterBench refuses
|
||||
`--quick` with `--passes`); the passes now win.
|
||||
- Agent skill (`docs/agent/SKILL.md`) works with how Hermes Agent runs commands: a `kaname` helper
|
||||
script (`docs/agent/kaname`) instead of a shell function that didn't survive between commands,
|
||||
`KANAME_URL`/`KANAME_TOKEN` declared in the frontmatter, and far less polling (none while a
|
||||
request waits for approval, one check around the ETA while downloading).
|
||||
|
||||
## [0.10.0] - 2026-10-20
|
||||
|
||||
An API for AI agents: a token-authenticated `/api/v1` lets a program look up models, request
|
||||
downloads and follow them, within guardrails you set and, by default, only after you approve each
|
||||
request.
|
||||
|
||||
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 table is created on
|
||||
start.
|
||||
|
||||
### Added
|
||||
|
||||
- **API tokens** (Settings → API tokens): create (shown once; only a SHA-256 hash is stored), name,
|
||||
scopes `models:read` and `downloads:create`, last used, revoke. 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, change settings, or manage runtimes
|
||||
or tokens.
|
||||
- **`/api/v1`**, compact JSON with actionable error messages ([docs/api.md](docs/api.md)):
|
||||
- `GET /api/v1`: the token's name, scopes and the guardrails.
|
||||
- `GET /api/v1/hub/lookup?repo=`: commit SHA, quants and files with sizes (the Add model lookup).
|
||||
- `GET /api/v1/models`: the library with its search and filters (author, family, quant, tag,
|
||||
status, requested by) and the size on disk; `GET /api/v1/models/{id}`.
|
||||
- `POST /api/v1/downloads`: repo + pinned commit + a quant (weights plus the recommended companion
|
||||
files, as in Add model) or include globs, optional tags. Uses the same add-model and queue code
|
||||
as the UI. Repeating a request returns the existing model and job instead of queueing a
|
||||
duplicate; for a model already in the library it adds the missing files.
|
||||
- `GET /api/v1/jobs/{id}`: state, per-file progress, error; the `hf` log only with `?log=N`.
|
||||
- `GET /api/v1/disk`: free, used and reserved space on the models folder.
|
||||
- **Guardrails for API downloads** (Settings → API tokens): approval mode (default: requests wait
|
||||
as *pending approval* until you approve or reject them on the model or job page), max size per
|
||||
request (60 GB), free space that must remain after the download, counting what other open
|
||||
downloads still need (100 GB), API jobs at once (2), and an optional author allowlist. Rejecting a
|
||||
request removes a model it added, or restores the previous file selection.
|
||||
- Everything requested with a token shows **requested by <token name>** in the library, on the
|
||||
model and job pages, with a "Requested by" filter (and "awaiting approval" under Status).
|
||||
- **Agent skill** for Hermes Agent and similar ([docs/agent/SKILL.md](docs/agent/SKILL.md)): how to
|
||||
search, look up, request and monitor a download with `curl`, the guardrails, and to wait for
|
||||
approval instead of retrying.
|
||||
|
||||
### Changed
|
||||
|
||||
- Settings → API keys is now **Runtime API keys** (the keys deployments require), to keep it apart
|
||||
from API tokens.
|
||||
- Tests can now use the database: `npm test` runs with `--conditions=react-server`.
|
||||
|
||||
## [0.9.0] - 2026-10-13
|
||||
|
||||
|
||||
+4
-1
@@ -16,9 +16,12 @@ RUN npm run build \
|
||||
|
||||
# --- runtime -----------------------------------------------------------------
|
||||
# Python base (provides the official `hf` CLI) plus the Node binary. The Python image already
|
||||
# has CA certificates and libstdc++, so no apt is needed.
|
||||
# has CA certificates and libstdc++; apt only adds the PCI ID database (GPU names for benchmarks).
|
||||
FROM python:3.13-slim-trixie AS runtime
|
||||
COPY --from=node /usr/local/bin/node /usr/local/bin/node
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends pci.ids \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Pinned: the worker relies on the CLI's on-disk layout (see src/worker/hf-layout.ts);
|
||||
# re-verify that before bumping.
|
||||
|
||||
@@ -86,6 +86,12 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
|
||||
(groundwork for testing model configs). See the
|
||||
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Runtimes).
|
||||
- **Jobs:** each download has a page with per-file progress and the full `hf` log.
|
||||
- **API for agents:** create a token in Settings → API tokens and let a program or AI agent look up
|
||||
repos, list models and request downloads at `/api/v1`, and deploy and benchmark models to tune
|
||||
their launch options, within guardrails you set (approval, sizes and limits, one GPU job at a time,
|
||||
allowed runtimes and arguments, protected deployments). See [docs/api.md](docs/api.md) (also how to
|
||||
let `/api/v1/` past a forward-auth proxy) and the agent skills [docs/agent/SKILL.md](docs/agent/SKILL.md)
|
||||
and [docs/agent/SKILL-tuning.md](docs/agent/SKILL-tuning.md).
|
||||
|
||||
## How it works
|
||||
|
||||
@@ -100,7 +106,9 @@ Notes on the `hf` CLI (huggingface_hub 2.1.1, pinned in the image):
|
||||
- Interrupted files are **not resumed**: a re-run skips finished files and restarts unfinished ones.
|
||||
Kaname cleans up the leftover partial files.
|
||||
- With Xet transfers the partial file only grows in large bursts, so Kaname disables Xet by default
|
||||
to show accurate progress.
|
||||
to show accurate progress. Files over 50 GB can only be downloaded with Xet, so a download that
|
||||
includes one uses Xet anyway; its progress then comes from `hf`'s own byte counter (the file on
|
||||
disk can sit still for minutes while Xet holds the data in memory).
|
||||
- `hf` exits successfully even if nothing matched, so Kaname checks every file's size and hash
|
||||
metadata after each download.
|
||||
- Files that already exist in the target folder without hf's metadata (copied in by hand) are
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
---
|
||||
name: kaname-tuning
|
||||
description: Deploy local LLMs on the user's Kaname server, benchmark their speed and check their answer quality to find good launch options (context, KV cache type, batch sizes, GPU layers, runtime) for the hardware. Use when the user asks to deploy, test, benchmark, tune or compare a model's settings, or to find the fastest setup for a model.
|
||||
required_environment_variables:
|
||||
- name: KANAME_URL
|
||||
prompt: Kaname base URL (no trailing slash)
|
||||
- name: KANAME_TOKEN
|
||||
prompt: Kaname API token (kn_…) with the deployments and benchmarks scopes
|
||||
---
|
||||
|
||||
# Kaname: deploy and tune models
|
||||
|
||||
Kaname runs models in containers (llama.cpp or vLLM) and measures them with BetterBench. With this
|
||||
skill you deploy a downloaded model, benchmark it, change **one** launch option at a time and report
|
||||
which setup is best. To find or download models, use the `kaname-models` skill (`SKILL.md`).
|
||||
|
||||
You may only change and benchmark deployments your own token created. You **cannot** touch the
|
||||
user's deployments (especially protected ones), change settings, runtimes or tokens, or delete
|
||||
models. Tell the user when something needs one of those.
|
||||
|
||||
Every call needs `KANAME_URL` and `KANAME_TOKEN` (never print the token or put it in a URL), and the
|
||||
`kaname` helper (a `curl` wrapper that adds the token and JSON headers; see `SKILL.md` → Setup). If
|
||||
`kaname` is missing, write out
|
||||
`curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" …` instead.
|
||||
|
||||
Errors are `{"error": {"code", "message"}}`; the message says what to do.
|
||||
|
||||
## Rules
|
||||
|
||||
- **No polling loops.** Status calls take `?wait=S` (max 900): Kaname holds the request until the
|
||||
state settles. Make one call, with `-m` (curl's time limit) a bit above the wait.
|
||||
- **Approval:** by default every start, run and sweep waits for the user (`state:
|
||||
pending_approval`). Then **stop**: tell the user what you asked for and that it awaits their
|
||||
approval in Kaname. Don't retry, don't poll. Continue when the user says it's approved.
|
||||
- **Never work around a guardrail** (another token, splitting a sweep, renaming things). Report the
|
||||
error message and stop.
|
||||
- **One GPU job at a time:** one of your deployments running at once (unless the user raised the
|
||||
limit), one run or sweep at a time. Stop your deployment when you're done.
|
||||
- **Change one variable at a time**, so a difference has one cause.
|
||||
|
||||
## 1. Know your limits
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1"
|
||||
```
|
||||
|
||||
`deploymentGuardrails`: approval mode, how many of your deployments may run, run/sweep time limits,
|
||||
max sweep variants, caps, host ports. Your scopes must include `deployments:write` and
|
||||
`benchmarks:run`; if not, tell the user.
|
||||
|
||||
## 2. Pick a model and a runtime
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/models?status=ready&q=qwen3"
|
||||
kaname "$KANAME_URL/api/v1/models/<modelId>" # its files (pick a .gguf for llama.cpp)
|
||||
kaname "$KANAME_URL/api/v1/runtimes"
|
||||
```
|
||||
|
||||
Runtimes say what they serve (llama.cpp: a GGUF file, vLLM: a safetensors repo), whether you may use
|
||||
them (`"allowed": true`) and which extra argument flags you may pass (`allowedExtraArgs`). `gpus`
|
||||
lists the host's GPUs and their VRAM.
|
||||
|
||||
Previous results for this model, to start from what is known:
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/benchmarks?limit=10"
|
||||
```
|
||||
|
||||
## 3. Deploy
|
||||
|
||||
Check first (nothing is created; you get the exact command and the memory/VRAM estimates):
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/deployments" -d '{
|
||||
"runtimeId": "<runtimeId>", "modelId": "<modelId>", "dryRun": true,
|
||||
"options": { "modelFile": "Qwen3-8B-Q4_K_M.gguf", "contextSize": 16384, "gpuLayers": "auto",
|
||||
"cacheTypeK": "q8_0", "cacheTypeV": "q8_0", "parallel": 1, "extraArgs": [] }
|
||||
}'
|
||||
```
|
||||
|
||||
If `estimates.vramMb` is above `estimates.gpuVramMb`, lower the context, quantize the KV cache or
|
||||
pick a smaller quant. Then the same body without `"dryRun"`:
|
||||
|
||||
- `state: pending_approval` → tell the user and stop (see Rules).
|
||||
- `state: starting` → wait until it is ready:
|
||||
|
||||
```bash
|
||||
kaname -m 660 "$KANAME_URL/api/v1/deployments/<id>?wait=600"
|
||||
```
|
||||
|
||||
`state: running` → go on. `state: failed` → read `error` (and `?log=50`), fix the options
|
||||
(`PATCH`, below) and start again; don't repeat the same failing options.
|
||||
|
||||
## 4. Benchmark
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/benchmarks" -d '{
|
||||
"deploymentId": "<id>", "quick": true, "label": "Q4_K_M ctx16k q8_0 KV",
|
||||
"description": "Baseline for tuning Qwen3-8B on this GPU"
|
||||
}'
|
||||
kaname -m 960 "$KANAME_URL/api/v1/benchmarks/<runId>?wait=900"
|
||||
```
|
||||
|
||||
- `quick: true` (5 passes) to screen options; `quick: false` (20 passes) to confirm the winner.
|
||||
- `phases` (`decode`, `prefill`, `concurrency`) narrows what is measured; leave it out for all.
|
||||
- The result's `headline` has `decodeTps` (generation speed), `prefillTps` (prompt processing at the
|
||||
deepest prompt), `ttftMs` (time to first token) and `peakParallelTps`; `setup` lists GPU, PCIe,
|
||||
engine version, model/quant/KV cache, context and concurrency; `resources` has VRAM, power and
|
||||
temperature. `?full=1` only when you need the per-category details.
|
||||
- If the wait times out, the run is still going: one more call with `?wait=900`, then report.
|
||||
|
||||
Then check that the answers are still right (speed alone can hide a broken setup):
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/benchmarks" -d '{"kind": "eval", "deploymentId": "<id>", "label": "Q4_K_M ctx16k q8_0 KV"}'
|
||||
kaname -m 960 "$KANAME_URL/api/v1/benchmarks/<runId>?wait=900"
|
||||
```
|
||||
|
||||
`quality.score` (0–100) and per section (`tools`, `coding`, `retrieval`). Add `?full=1` to see which
|
||||
items failed. A drop of more than a few points against the baseline means the change hurt quality,
|
||||
however fast it is.
|
||||
|
||||
## 5. Change one variable and compare
|
||||
|
||||
Stop, change one option, start, wait, benchmark again:
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/deployments/<id>/stop"
|
||||
kaname -m 120 "$KANAME_URL/api/v1/deployments/<id>?wait=60"
|
||||
kaname -X PATCH "$KANAME_URL/api/v1/deployments/<id>" -d '{"options": {"cacheTypeK": "f16", "cacheTypeV": "f16"}}'
|
||||
kaname -X POST "$KANAME_URL/api/v1/deployments/<id>/start"
|
||||
```
|
||||
|
||||
Or let Kaname do it: a **sweep** deploys each variant of one or two settings, benchmarks it (with
|
||||
`"quality": true` also runs the quality eval) and removes it again (stop your own deployment first;
|
||||
it counts as one run):
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/sweeps" -d '{
|
||||
"baseDeploymentId": "<id>", "quick": true, "quality": true,
|
||||
"params": [{ "key": "kvCache", "values": ["f16", "q8_0", "q4_0"] }]
|
||||
}'
|
||||
kaname -m 960 "$KANAME_URL/api/v1/sweeps/<sweepId>?wait=900"
|
||||
```
|
||||
|
||||
Keys: `contextSize`, `modelFile`, `kvCache`, `threads`, `parallel`, `batchSize`, `ubatchSize`,
|
||||
`flashAttn`, `cacheRamMb`, `gpuLayers` (llama.cpp); `dtype`, `maxNumSeqs`, `gpuMemoryUtilization`
|
||||
(vLLM); `cpus`. A sweep can take long: after a timed-out wait, report progress instead of waiting
|
||||
again and again.
|
||||
|
||||
Compare runs side by side:
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/benchmarks/compare?ids=<run1>,<run2>,<run3>"
|
||||
```
|
||||
|
||||
Differences under ~2 % between separate runs are noise. For a small difference that matters, run
|
||||
an A/B (two deployments of the same model at once, if the user allows 2 agent deployments):
|
||||
`{"kind": "ab", "deploymentId": "<A>", "deploymentBId": "<B>"}`.
|
||||
|
||||
## 6. Report and clean up
|
||||
|
||||
Report a compact table, one row per setup, the varied option first:
|
||||
|
||||
| KV cache | Decode t/s | Prefill t/s | TTFT ms | Quality | VRAM peak | Notes |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| f16 | 58.1 | 1910 | 88 | 86.1 | 11.2 GB | baseline |
|
||||
| q8_0 | 57.6 | 1880 | 90 | 86.1 | 9.4 GB | −1 % speed, same quality, 1.8 GB less VRAM |
|
||||
|
||||
Name the winner and why: speed and quality together (and what stayed the same: GPU, engine version,
|
||||
quant, context). Then stop
|
||||
your deployment (or delete it if the user doesn't need it):
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/deployments/<id>/stop"
|
||||
```
|
||||
|
||||
## When something is refused
|
||||
|
||||
| `error.code` | What to do |
|
||||
| --- | --- |
|
||||
| `too_many_deployments` | Stop your other deployment first, or tell the user. |
|
||||
| `gpu_busy` | Another agent job is running or a deployment is loading: wait once with `?wait=`, then retry once; otherwise report and stop. |
|
||||
| `vram_protected` | It would crowd the user's protected deployment out of VRAM: smaller quant, context or quantized KV cache, or tell the user. |
|
||||
| `arg_not_allowed` | That flag isn't allowed; use the structured option if there is one (`contextSize`, `gpuLayers`, `cacheTypeK`, …) or drop it. |
|
||||
| `limit_exceeded` | Over the memory/CPU cap: smaller model or context. |
|
||||
| `port_not_allowed` | Leave out `hostPort`. |
|
||||
| `runtime_not_allowed`, `runtime_not_pulled` | Pick another runtime from `GET /api/v1/runtimes`, or tell the user. |
|
||||
| `protected`, `not_owner` | Not your deployment: deploy your own. |
|
||||
| `too_many_variants` | Vary fewer values. |
|
||||
| `busy` | Stop the deployment before changing it. |
|
||||
| `unauthorized`, `forbidden` | Token wrong, revoked or missing a scope: tell the user. |
|
||||
@@ -0,0 +1,133 @@
|
||||
---
|
||||
name: kaname-models
|
||||
description: Find, request and track downloads of local LLMs (Hugging Face models, GGUF quants) on the user's Kaname server. Use when the user asks to get, download, add or check a model, or asks which models are available locally or how much disk space is left.
|
||||
required_environment_variables:
|
||||
- name: KANAME_URL
|
||||
prompt: Kaname base URL (no trailing slash)
|
||||
- name: KANAME_TOKEN
|
||||
prompt: Kaname API token (kn_…)
|
||||
---
|
||||
|
||||
# Kaname: local model downloads
|
||||
|
||||
Kaname manages the user's local LLM library. You can look up Hugging Face repos, see what is
|
||||
already downloaded, request a download and follow it. You **cannot** delete anything, change
|
||||
settings, or start models with this skill: tell the user when they need one of those. To deploy and
|
||||
benchmark models (with a token that has the deployments and benchmarks scopes), see
|
||||
`SKILL-tuning.md`.
|
||||
|
||||
Every call needs two environment variables:
|
||||
|
||||
- `KANAME_URL`: e.g. `https://models.example.com` (no trailing slash)
|
||||
- `KANAME_TOKEN`: the API token (`kn_…`). Never print it or put it in a URL.
|
||||
|
||||
## Setup
|
||||
|
||||
The examples use `kaname`, a small wrapper around `curl` that adds the token and JSON headers. The
|
||||
user installs 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` is not found, write out the full command in each call instead:
|
||||
`curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" …`
|
||||
(every command runs in a fresh shell, so don't define a shell function for it).
|
||||
|
||||
All responses are JSON. Errors are `{"error": {"code", "message"}}`; the message says what to do.
|
||||
|
||||
## 0. Know your limits
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1"
|
||||
```
|
||||
|
||||
Shows your token name, scopes and the guardrails. The defaults:
|
||||
|
||||
- **approvalMode `approve`**: your requests wait until the user approves them. That's normal.
|
||||
- **maxRequestSize** (60 GB): one request may download at most this much.
|
||||
- **minFreeSize** (100 GB): this much must stay free on disk after the download.
|
||||
- **maxOpenAgentJobs** (2): at most this many of your requests pending or running at once.
|
||||
- **allowedAuthors**: if not empty, only repos from these Hugging Face authors.
|
||||
|
||||
## 1. Is it already here?
|
||||
|
||||
```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`, `author`, `family`, `quant`, `tag`, `status`, `requested_by` (comma-separate values).
|
||||
If the model is there with `status: ready`, you're done. Don't request it again.
|
||||
|
||||
## 2. Look up the repo
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/hub/lookup?repo=unsloth/Qwen3-8B-GGUF"
|
||||
```
|
||||
|
||||
Note `sha` (the commit) and pick a quant from `quants` (each has a `size`). Choose one that fits the
|
||||
user's request and the limits: check `size` against `maxRequestSize`, and check space with:
|
||||
|
||||
```bash
|
||||
kaname "$KANAME_URL/api/v1/disk" # availableForRequests = what a request may still use
|
||||
```
|
||||
|
||||
If `gated` is not `false`, the download only works if the user's Hugging Face account has access.
|
||||
|
||||
## 3. Request the download
|
||||
|
||||
```bash
|
||||
kaname -X POST "$KANAME_URL/api/v1/downloads" \
|
||||
-d '{"repoId":"unsloth/Qwen3-8B-GGUF","sha":"<sha from lookup>","quant":"Q4_K_M"}'
|
||||
```
|
||||
|
||||
For repos without GGUF quants (safetensors), use `"include": ["*.safetensors", "*.json"]` instead
|
||||
of `quant`. Optional: `"tags": ["…"]`.
|
||||
|
||||
Answer:
|
||||
|
||||
- `201`, `state: pending_approval`: **waiting for the user.** Tell them what you requested and that
|
||||
it needs their approval in Kaname. **Do not retry or re-request.**
|
||||
- `201`, `state: queued`: it will start on its own.
|
||||
- `200`, `created: false`: you (or someone) already requested exactly this; you get the existing
|
||||
job. Don't request it again.
|
||||
|
||||
## 4. Follow it
|
||||
|
||||
```bash
|
||||
kaname -m 660 "$KANAME_URL/api/v1/jobs/<jobId>?wait=600"
|
||||
```
|
||||
|
||||
`state`: `pending_approval` → `queued` → `downloading` → `verifying` → `completed`. With `?wait=600`
|
||||
Kaname holds the request until the job is finished (or 600 s have passed; then `timedOut` is
|
||||
`true`), so one call replaces a polling loop. Keep `-m` (curl's time limit) a bit above the wait.
|
||||
Every call costs a full round of your context, so call rarely:
|
||||
|
||||
- **`pending_approval`:** do **not** poll. Tell the user what you requested and that it awaits
|
||||
their approval in Kaname, then stop. Check again only when the user says it's approved, or, if
|
||||
the user asks for it, schedule a single one-off check later with your cron/scheduling tool.
|
||||
- **`queued` / `downloading` / `verifying`:** one call with `?wait=600`. If it comes back with
|
||||
`timedOut: true` and the ETA is long, tell the user it is still downloading instead of waiting
|
||||
again and again. Never loop in short intervals.
|
||||
- **`completed`:** tell the user it's ready.
|
||||
- **`cancelled`:** the user rejected or cancelled it. Don't ask again unless the user says so.
|
||||
- **`failed`:** report `error.message` to the user. Don't loop on retries.
|
||||
|
||||
Add `?log=20` only when you need to explain a failure.
|
||||
|
||||
## 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` | Don't wait in a loop: tell the user your earlier downloads are still pending or running, and stop. Request again later when the user asks. |
|
||||
| `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 has a download in progress; tell the user and stop. |
|
||||
| `gated_no_access`, `gated_no_token` | The user must accept the model's terms on Hugging Face. |
|
||||
| `disk_unknown` | Kaname's worker is offline; tell the user and stop. |
|
||||
| `unauthorized`, `forbidden` | Your token is wrong, revoked or lacks a scope: tell the user. |
|
||||
|
||||
Never try to work around a guardrail (e.g. by splitting one big download into several requests).
|
||||
Executable
+2
@@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env bash
|
||||
exec curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" "$@"
|
||||
+419
@@ -0,0 +1,419 @@
|
||||
# Kaname API (`/api/v1`)
|
||||
|
||||
A small JSON API for programs and AI agents: look up Hugging Face repos, list the local library,
|
||||
request downloads, deploy models and benchmark them to tune launch options. Everything an agent can
|
||||
do here is bounded by [guardrails](#guardrails); it can't delete models or files, change settings,
|
||||
manage runtimes or tokens, or touch deployments it didn't create.
|
||||
|
||||
The rest of Kaname (the web UI and its internal `/api/*` routes) stays behind your OIDC login. Only
|
||||
`/api/v1` accepts tokens, and it accepts *only* tokens (a browser session doesn't work there).
|
||||
|
||||
- [Authentication](#authentication)
|
||||
- [Errors](#errors)
|
||||
- [Endpoints](#endpoints): models and downloads, [deployments](#deployments), [benchmarks](#benchmarks)
|
||||
- [Waiting instead of polling](#waiting-instead-of-polling)
|
||||
- [Guardrails](#guardrails)
|
||||
- [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, read jobs (and their log), disk space |
|
||||
| `downloads:create` | `POST /api/v1/downloads`, within the guardrails |
|
||||
| `deployments:read` | List runtimes and deployments, read a deployment's state and log |
|
||||
| `deployments:write` | Create deployments; edit, start, stop and delete **its own** ones, within the guardrails |
|
||||
| `benchmarks:read` | Read runs, sweeps and comparisons |
|
||||
| `benchmarks:run` | Start runs, A/B runs and sweeps on **its own** deployments; cancel its own |
|
||||
|
||||
Tokens created before 0.13 keep the scopes they had; grant new ones with **Scopes** next to the
|
||||
token in Settings → API tokens.
|
||||
|
||||
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; **Revoke** stops it immediately.
|
||||
|
||||
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.
|
||||
|
||||
## 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` (quant or globs match nothing), `invalid_repo_id`, `invalid` |
|
||||
| 401 / 403 | `unauthorized`, `forbidden` (scope), `author_not_allowed`, `gated_no_token`, `gated_no_access`, `runtime_not_allowed`, `arg_not_allowed`, `port_not_allowed`, `protected`, `not_owner` |
|
||||
| 404 | `not_found`, `repo_not_found`, `revision_not_found` |
|
||||
| 409 | `already_exists` (repo is in the library at another commit), `busy` (a model with an open job; a deployment that must be stopped first), `runtime_not_pulled`, `vram_protected`, `invalid` (e.g. benchmarking a stopped deployment) |
|
||||
| 422 | `too_large`, `limit_exceeded`, `too_many_variants` |
|
||||
| 429 | `too_many_jobs`, `too_many_deployments`, `gpu_busy`, `rate_limited` (Hugging Face) |
|
||||
| 503 / 507 | `disk_unknown` (worker offline), `disk_space` |
|
||||
|
||||
Sizes appear as bytes plus a readable `"… GB"` field (decimal GB, like the Hub).
|
||||
|
||||
## Endpoints
|
||||
|
||||
### `GET /api/v1`
|
||||
|
||||
Any valid token. 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]`
|
||||
|
||||
`models:read`. 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`
|
||||
|
||||
`models:read`. 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", "status": "ready", "pendingApproval": false,
|
||||
"pinnedSha": "9e68…", "quants": ["Q4_K_M"], "tags": ["agent"], "selectedFiles": 1, "selectedBytes": 5027783488,
|
||||
"onDiskBytes": 5027783488, "onDisk": "5.0 GB", "updateAvailable": false, "hubState": "available",
|
||||
"requestedBy": "hermes", "createdAt": "…", "downloadedAt": "…" }] }
|
||||
```
|
||||
|
||||
### `GET /api/v1/models/{id}`
|
||||
|
||||
`models:read`. One model with its selected files (path, bytes, state) and latest job.
|
||||
|
||||
### `POST /api/v1/downloads`
|
||||
|
||||
`downloads:create`. Request a download of a repo **at a pinned commit**: take `sha` from the lookup.
|
||||
|
||||
| Field | |
|
||||
| --- | --- |
|
||||
| `repoId` | `"org/name"` |
|
||||
| `sha` | 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"],
|
||||
"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 `approve`) or `queued` (`auto`).
|
||||
- **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 that are
|
||||
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.
|
||||
|
||||
It uses the same code path as the Add model dialog (the file list is fetched again from the Hub at
|
||||
that commit; the client's list isn't trusted).
|
||||
|
||||
### `GET /api/v1/jobs/{id}[?wait=S][&log=N]`
|
||||
|
||||
`models:read`. 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; check again in a minute." }
|
||||
```
|
||||
|
||||
States: `pending_approval`, `queued`, `downloading`, `verifying`, `completed`, `failed`, `cancelled`
|
||||
(also when the user rejected the request), `interrupted`. The `hf` log is only included with
|
||||
`?log=N` (the last N lines, at most 200). `?wait=S` returns once the job is finished (or right away
|
||||
while it waits for approval); see [Waiting instead of polling](#waiting-instead-of-polling).
|
||||
|
||||
### `GET /api/v1/disk`
|
||||
|
||||
`models:read`. 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 hitting the minimum-free guardrail.
|
||||
|
||||
### Deployments
|
||||
|
||||
A deployment is a model served by a runtime container. Agents use the same validation, estimates and
|
||||
`docker run` command as the UI; they can only edit, start, stop, delete and benchmark deployments their
|
||||
own token created, and never [protected](#protected-deployments) ones.
|
||||
|
||||
#### `GET /api/v1/runtimes`
|
||||
|
||||
`deployments:read`. Runtimes with a pulled image: engine (`llama.cpp` or `vllm`), accelerator
|
||||
(`cpu`, `nvidia`, `dri` for Intel/AMD), what they serve, whether agents may use them (`allowed`) and
|
||||
the extra argument flags agents may pass (`allowedExtraArgs`); plus the host's GPUs.
|
||||
|
||||
#### `GET /api/v1/deployments[?mine=1]`, `GET /api/v1/deployments/{id}[?wait=S][&log=N]`
|
||||
|
||||
`deployments:read`. State (`stopped`, `pending_approval`, `starting`, `running`, `stopping`,
|
||||
`failed`), `mine`, `protected`, runtime, model, options, limits, the endpoint inside the Docker
|
||||
network, what the server reported once ready (version, slots, context), live CPU/RAM, error and a
|
||||
`next` hint. `?wait=S` returns once it is running, stopped or failed (or right away while the start
|
||||
waits for approval). `?log=N` adds the last N log lines (max 200).
|
||||
|
||||
#### `POST /api/v1/deployments`
|
||||
|
||||
`deployments:write`.
|
||||
|
||||
| Field | |
|
||||
| --- | --- |
|
||||
| `runtimeId`, `modelId` | From `GET /api/v1/runtimes` and `GET /api/v1/models` |
|
||||
| `options` | The deployment form's launch options: `modelFile` (llama.cpp: the `.gguf`; vLLM: `""`), `contextSize`, `parallel`, `cacheTypeK`/`cacheTypeV`, `flashAttn`, `gpuLayers`, `batchSize`/`ubatchSize`, `maxNumSeqs`, `gpuMemoryUtilization`, … and `extraArgs` (only [allowed flags](#deployments-and-benchmarks)). Unknown fields are refused. |
|
||||
| `cpus`, `memoryMb` | Optional limits within the caps; without `memoryMb` the estimate is used |
|
||||
| `hostPort` | Optional, only inside the configured range (none by default) |
|
||||
| `name` | Optional |
|
||||
| `start` | Default `true`; with approval mode `approve` the start waits for the user |
|
||||
| `dryRun` | `true`: only validate; returns the command and estimates, creates nothing |
|
||||
|
||||
```json
|
||||
{ "created": true, "id": "01M…", "state": "pending_approval",
|
||||
"command": "docker run -v <models>:/models:ro ghcr.io/ggml-org/llama.cpp:server-intel -m /models/… -c 16384 -ctk q8_0 …",
|
||||
"estimates": { "memoryMb": 9800, "vramMb": 7900, "gpuVramMb": 32768 }, "limits": { "memoryMb": 9800, "cpus": null },
|
||||
"message": "Created; the start waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop." }
|
||||
```
|
||||
|
||||
#### `PATCH /api/v1/deployments/{id}`, `POST …/start`, `POST …/stop`, `DELETE …`
|
||||
|
||||
`deployments:write`, own deployments only. `PATCH` takes `options` (merged into the current ones),
|
||||
`cpus`, `memoryMb`, `hostPort`, `name`, and only while the deployment is stopped; it returns the new
|
||||
command and estimates. `start` goes through the same guardrails as creating one (and approval);
|
||||
`stop` and `DELETE` never need approval.
|
||||
|
||||
### Benchmarks
|
||||
|
||||
#### `POST /api/v1/benchmarks`
|
||||
|
||||
`benchmarks:run`. A [BetterBench](https://github.com/GGZ14/BetterBench) run against the token's own
|
||||
**running** deployment.
|
||||
|
||||
| Field | |
|
||||
| --- | --- |
|
||||
| `kind` | `run` (default, BetterBench speed), `ab` (paired A/B with `deploymentBId`, same model; needs 2 agent deployments) or `eval` (the [quality eval](#quality-eval)) |
|
||||
| `deploymentId`, `deploymentBId` | Own, running deployments |
|
||||
| `quick` | `true`: 5 passes, a smoke check; default `false`: 20 passes, comparable |
|
||||
| `passes`, `phases` | Optional: passes per category; phases `decode`, `prefill`, `concurrency` (default all) |
|
||||
| `label`, `description` | Optional; the description goes into the report and the launch80 preview |
|
||||
| `sections` | `eval` only: `tools`, `coding`, `retrieval` (default all) |
|
||||
|
||||
Answers `201` with `state` `pending_approval` (default) or `queued`, and the run's time limit.
|
||||
|
||||
#### `GET /api/v1/benchmarks/{id}[?wait=S][&full=1]`, `GET /api/v1/benchmarks[?deployment=&requested_by=&limit=]`
|
||||
|
||||
`benchmarks:read`. Compact result:
|
||||
|
||||
```json
|
||||
{ "id": "01M…", "kind": "run", "state": "completed", "label": "q8_0 KV", "mine": true,
|
||||
"headline": { "decodeTps": 61.3, "prefillTps": 1840, "prefillDepth": 16000, "ttftMs": 92, "peakParallelTps": 155.2, "peakParallelLevel": 8 },
|
||||
"setup": { "gpus": "1× Intel Arc Pro B65 (32 GiB)", "pcie": "Gen5 x8 of Gen5 x16", "p2p": "n/a", "rebar": "on",
|
||||
"engine": "llama.cpp b11541-f2918cabb", "image": "ghcr.io/ggml-org/llama.cpp:server-intel", "digest": "sha256:…",
|
||||
"model": "Qwen3-8B-GGUF Q4_K_M with q8_0 KV cache", "ctx": "16,384", "concurrency": "4" },
|
||||
"resources": { "cpuAvgCores": 1.1, "ramPeakBytes": 2100000000,
|
||||
"gpus": [{ "name": "Intel Arc Pro B65", "vramPeakMb": 9100, "vramTotalMb": 32768, "utilAvg": 88.5, "powerAvgW": 151.2, "tempPeakC": 71 }] },
|
||||
"error": null, "next": "Done. Compare runs with GET /api/v1/benchmarks/compare?ids=…" }
|
||||
```
|
||||
|
||||
`?full=1` adds BetterBench's complete summary (per category, per prompt depth, per concurrency
|
||||
level). A/B runs add `ab` (pairs, verdict, decode difference with its confidence interval). Eval runs
|
||||
have `quality` instead of `headline`:
|
||||
`{"evalSet": "kaname-eval-1", "score": 83.3, "sections": {"tools": "11/12", "coding": "6/8", "retrieval": "8/9"}}`,
|
||||
and with `?full=1` the `failed` items with the reason.
|
||||
`POST /api/v1/benchmarks/{id}/cancel` cancels an own run.
|
||||
|
||||
#### `GET /api/v1/benchmarks/compare?ids=a,b,…`
|
||||
|
||||
`benchmarks:read`. 2–16 runs: headline numbers side by side, the setup values that differ per run
|
||||
(`differs`) and the ones they share (`same`).
|
||||
|
||||
#### `POST /api/v1/sweeps`, `GET /api/v1/sweeps/{id}[?wait=S]`, `POST /api/v1/sweeps/{id}/cancel`
|
||||
|
||||
`benchmarks:run` / `benchmarks:read`. One or two settings varied from an own base deployment, e.g.
|
||||
`{"baseDeploymentId": "…", "params": [{"key": "kvCache", "values": ["f16", "q8_0"]}], "quick": true}`;
|
||||
`"quality": true` also runs the quality eval on each variant.
|
||||
Keys: `contextSize`, `modelFile`, `kvCache`, `threads`, `parallel`, `batchSize`, `ubatchSize`,
|
||||
`flashAttn`, `cacheRamMb`, `gpuLayers`, `dtype`, `maxNumSeqs`, `kvCacheGb`, `gpuMemoryUtilization`,
|
||||
`cpus` (per engine, as in the UI). Each variant is deployed, benchmarked and removed again. The
|
||||
answer lists every variant with its headline numbers and setup.
|
||||
|
||||
#### Quality eval
|
||||
|
||||
BetterBench measures speed only. `kind: "eval"` checks what a deployment answers, deterministically
|
||||
(greedy decoding, temperature 0, fixed seed, thinking turned off where the chat template supports
|
||||
it), so a quant, KV cache type or build that changes quality shows up next to the speed numbers:
|
||||
|
||||
| Section | Items | Passes when |
|
||||
| --- | --- | --- |
|
||||
| `tools` | 12 requests with 3 tools each | exactly one tool call, valid JSON arguments, the right function and the expected arguments |
|
||||
| `coding` | 8 short Python functions | the answer's code passes its unit tests, run in a throwaway container (no network, read-only, unprivileged) |
|
||||
| `retrieval` | a six-digit code hidden at 10 %, 50 % and 90 % depth in texts of 25 %, 50 % and 100 % of the context | the answer contains the code |
|
||||
|
||||
The score is the mean pass rate of the sections that could run (a server that refuses tool calls,
|
||||
e.g. vLLM without a tool-call parser, doesn't count as 0). The eval set is versioned (`evalSet`);
|
||||
only results of the same version compare.
|
||||
|
||||
## Waiting instead of polling
|
||||
|
||||
Every status call costs an agent a round of its context. The status endpoints (`/jobs/{id}`,
|
||||
`/deployments/{id}`, `/benchmarks/{id}`, `/sweeps/{id}`) take `?wait=S` (seconds, at most 900): the
|
||||
request is held until the state is settled (finished, running, failed, cancelled) or the time is up,
|
||||
then answers with the current state plus `waitedSeconds` and `timedOut`. Something that waits for the
|
||||
user's approval answers right away: there is 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
|
||||
|
||||
### Downloads
|
||||
|
||||
Settings → API tokens → **Guardrails for API downloads**. They apply to every token together;
|
||||
downloads started in the UI aren't affected.
|
||||
|
||||
| Setting | Default | Rejection |
|
||||
| --- | --- | --- |
|
||||
| Approval | **Ask me**: requests wait as *pending approval* until you approve or reject them on the model or job page | (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 (pending approval, queued or running) | `429 too_many_jobs` |
|
||||
| Allowed authors | empty = any; e.g. `unsloth, ggml-org, Qwen` (case-insensitive) | `403 author_not_allowed` |
|
||||
|
||||
Rejecting a request cancels its 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.
|
||||
|
||||
### Deployments and benchmarks
|
||||
|
||||
Settings → API tokens → **Guardrails for API deployments and benchmarks**, for every token together:
|
||||
|
||||
| Setting | Default | Rejection |
|
||||
| --- | --- | --- |
|
||||
| Approval | **Ask me**: starts, runs and sweeps wait as *pending approval* on the deployment, run or sweep page. Creating or editing a stopped deployment, stopping and deleting own ones need none. | (not an error) |
|
||||
| Agent deployments at once | 1 (running, starting or waiting to start); 2 for A/B runs | `429 too_many_deployments` |
|
||||
| One GPU job at a time | No agent start while an agent run or sweep is pending or running, or another agent deployment is still loading; one agent run or sweep at a time; no sweep while an agent deployment runs (the sweep deploys its variants itself) | `429 gpu_busy` |
|
||||
| Max minutes per run / sweep | 30 / 180, then the worker stops it | (`failed` with the reason) |
|
||||
| Max variants per sweep | 8 | `422 too_many_variants` |
|
||||
| Runtimes | Any with a pulled image, or an allowlist | `403 runtime_not_allowed`, `409 runtime_not_pulled` |
|
||||
| Extra arguments | Tuning flags only, per engine (editable list); values can't be paths or URLs | `403 arg_not_allowed`, naming the argument |
|
||||
| Host ports | None (Kaname reaches deployments over the Docker network), or a range | `403 port_not_allowed` |
|
||||
| Memory / CPU caps | The host's size, or what you set; agent deployments always get a memory limit (the estimate if they don't give one) | `422 limit_exceeded` |
|
||||
| Own deployments only | Agents change and benchmark only what their token created | `403 not_owner` |
|
||||
|
||||
Docker options (devices, volumes, privileges, capabilities, network) are never arguments: they belong
|
||||
to the runtime, which tokens can't change.
|
||||
|
||||
### Protected deployments
|
||||
|
||||
The **Protect** button on a deployment's page: agents can't edit, start, stop, delete or benchmark
|
||||
it, and can't start a deployment on the same GPUs if the estimated VRAM of everything running there
|
||||
plus the new one (and 1 GiB to spare) exceeds the GPUs' VRAM (`409 vram_protected`). When the need
|
||||
can't be estimated (only some layers on the GPU), such a start is refused too.
|
||||
|
||||
### Activity
|
||||
|
||||
Settings → API tokens → **Activity** next to each token lists what it did: every request that
|
||||
creates or changes something, waits for approval, or was refused (with the 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
|
||||
```
|
||||
|
||||
The same in a file provider:
|
||||
|
||||
```yaml
|
||||
http:
|
||||
routers:
|
||||
kaname-api:
|
||||
rule: Host(`models.example.com`) && PathPrefix(`/api/v1/`)
|
||||
entryPoints: [websecure]
|
||||
tls: {}
|
||||
priority: 100
|
||||
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.
|
||||
@@ -0,0 +1,17 @@
|
||||
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;
|
||||
@@ -0,0 +1,7 @@
|
||||
ALTER TABLE `benchmark_runs` ADD `meta` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `meta_b` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `system` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `description` text;--> statement-breakpoint
|
||||
ALTER TABLE `deployments` ADD `engine_info` text;--> statement-breakpoint
|
||||
ALTER TABLE `runtimes` ADD `image_digest` text;--> statement-breakpoint
|
||||
ALTER TABLE `runtimes` ADD `engine_name` text;
|
||||
@@ -0,0 +1,25 @@
|
||||
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
|
||||
ALTER TABLE `benchmark_runs` ADD `requested_by_token_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `requested_by` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_runs` ADD `time_limit_s` integer;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_sweeps` ADD `requested_by_token_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_sweeps` ADD `requested_by` text;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_sweeps` ADD `time_limit_s` integer;--> statement-breakpoint
|
||||
ALTER TABLE `benchmark_sweeps` ADD `run_time_limit_s` integer;--> statement-breakpoint
|
||||
ALTER TABLE `deployments` ADD `requested_by_token_id` text;--> statement-breakpoint
|
||||
ALTER TABLE `deployments` ADD `requested_by` text;--> statement-breakpoint
|
||||
ALTER TABLE `deployments` ADD `protected` integer DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE `deployments` ADD `start_requested_at` integer;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `benchmark_runs` ADD `quality` 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
@@ -120,6 +120,34 @@
|
||||
"when": 1791658947930,
|
||||
"tag": "0016_ab_resources_sweeps",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 17,
|
||||
"version": "6",
|
||||
"when": 1792504668583,
|
||||
"tag": "0017_api_tokens",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 18,
|
||||
"version": "6",
|
||||
"when": 1792513935880,
|
||||
"tag": "0018_benchmark_metadata",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 19,
|
||||
"version": "6",
|
||||
"when": 1792587768766,
|
||||
"tag": "0019_agent_tuning",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 20,
|
||||
"version": "6",
|
||||
"when": 1792588720328,
|
||||
"tag": "0020_quality_eval",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "kaname",
|
||||
"version": "0.9.0",
|
||||
"version": "0.14.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "kaname",
|
||||
"version": "0.9.0",
|
||||
"version": "0.14.3",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.8.0",
|
||||
"@libsql/client": "^0.18.0",
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "kaname",
|
||||
"version": "0.9.0",
|
||||
"version": "0.14.3",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
|
||||
@@ -13,7 +13,7 @@
|
||||
"typecheck": "next typegen && tsc --noEmit",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "dotenv -e .env -- tsx src/lib/db/migrate-cli.ts",
|
||||
"test": "tsx --test \"src/**/*.test.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"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
Executable
+86
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env bash
|
||||
# Read-only diagnostics for Intel GPU support (Arc / Arc Pro B-series) on a Kaname host.
|
||||
# Shows which telemetry sources this kernel and driver offer, so Kaname uses ones that exist.
|
||||
# Changes nothing. Run it on the Docker host (or VM) that has the GPU:
|
||||
#
|
||||
# bash scripts/intel-probe.sh # as your user: what an unprivileged container can see
|
||||
# sudo bash scripts/intel-probe.sh # adds lspci's link/ReBAR capability details
|
||||
#
|
||||
# Paste the output back. It contains no hostname, IP addresses or user names.
|
||||
|
||||
set -u
|
||||
section() { printf '\n=== %s ===\n' "$1"; }
|
||||
show() { [ -e "$1" ] && printf '%s: %s\n' "$1" "$(tr '\n' ' ' < "$1" 2>/dev/null || echo '(not readable)')"; }
|
||||
|
||||
section "System"
|
||||
echo "kernel: $(uname -r)"
|
||||
grep -E '^(PRETTY_NAME|VERSION_ID)=' /etc/os-release 2>/dev/null
|
||||
command -v systemd-detect-virt >/dev/null && echo "virt: $(systemd-detect-virt 2>/dev/null)"
|
||||
show /sys/class/dmi/id/sys_vendor
|
||||
show /sys/class/dmi/id/product_name
|
||||
echo "running as uid $(id -u)"
|
||||
|
||||
section "Intel display devices"
|
||||
gpus=()
|
||||
for d in /sys/bus/pci/devices/*; do
|
||||
[ "$(cat "$d/vendor" 2>/dev/null)" = "0x8086" ] || continue
|
||||
case "$(cat "$d/class" 2>/dev/null)" in 0x03*) gpus+=("$(basename "$d")") ;; esac
|
||||
done
|
||||
[ ${#gpus[@]} -eq 0 ] && echo "no Intel GPU found on the PCI bus"
|
||||
|
||||
for a in "${gpus[@]}"; do
|
||||
d=$(readlink -f "/sys/bus/pci/devices/$a")
|
||||
section "GPU $a"
|
||||
echo "sysfs path: $d"
|
||||
show "$d/device"
|
||||
show "$d/subsystem_device"
|
||||
echo "driver: $(basename "$(readlink "$d/driver" 2>/dev/null)" 2>/dev/null)"
|
||||
command -v lspci >/dev/null && lspci -nn -s "$a"
|
||||
echo "-- link per level (GPU up to the root port):"
|
||||
p=$d
|
||||
while [[ $(basename "$p") =~ ^[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$ ]]; do
|
||||
printf '%s vendor=%s cur=%s x%s max=%s x%s\n' "$(basename "$p")" "$(cat "$p/vendor" 2>/dev/null)" \
|
||||
"$(cat "$p/current_link_speed" 2>/dev/null)" "$(cat "$p/current_link_width" 2>/dev/null)" \
|
||||
"$(cat "$p/max_link_speed" 2>/dev/null)" "$(cat "$p/max_link_width" 2>/dev/null)"
|
||||
p=$(dirname "$p")
|
||||
done
|
||||
echo "-- BARs (start end flags):"
|
||||
head -6 "$d/resource" 2>/dev/null
|
||||
echo "-- VRAM / memory files:"
|
||||
find "$d" -maxdepth 3 \( -iname '*vram*' -o -iname '*lmem*' -o -iname '*mem_info*' \) 2>/dev/null | while read -r f; do
|
||||
[ -f "$f" ] && show "$f"
|
||||
done
|
||||
ls "$d/tile0" 2>/dev/null | head -30
|
||||
echo "-- hwmon:"
|
||||
for h in "$d"/hwmon/hwmon*; do
|
||||
[ -d "$h" ] || continue
|
||||
show "$h/name"
|
||||
for f in "$h"/*_input "$h"/*_label "$h"/*_crit "$h"/power*_max; do [ -f "$f" ] && show "$f"; done
|
||||
done
|
||||
if [ "$(id -u)" = 0 ] && command -v lspci >/dev/null; then
|
||||
echo "-- lspci capabilities:"
|
||||
lspci -vvv -s "$a" | grep -E 'LnkCap:|LnkSta:|Resizable BAR|BAR [0-9]: current size|Region'
|
||||
fi
|
||||
done
|
||||
|
||||
section "/dev/dri"
|
||||
ls -ln /dev/dri 2>/dev/null
|
||||
for n in /dev/dri/renderD*; do [ -e "$n" ] && echo "$n gid=$(stat -c %g "$n") group=$(stat -c %G "$n")"; done
|
||||
getent group render video | cut -d: -f1,3
|
||||
|
||||
section "DRM fdinfo (per-process VRAM / engine time)"
|
||||
found=0
|
||||
for f in /proc/[0-9]*/fdinfo/*; do
|
||||
grep -q '^drm-driver:' "$f" 2>/dev/null || continue
|
||||
found=1
|
||||
echo "readable example: $f"
|
||||
grep -E '^drm-(driver|client-id|engine-|cycles-|total-cycles-|memory-|total-|resident-)' "$f" | head -25
|
||||
break
|
||||
done
|
||||
[ $found = 0 ] && echo "no readable DRM fdinfo (no GPU process running, or not permitted for this user)"
|
||||
|
||||
section "Tools"
|
||||
for t in xpu-smi intel_gpu_top clinfo sycl-ls vulkaninfo docker; do
|
||||
printf '%s: %s\n' "$t" "$(command -v "$t" || echo missing)"
|
||||
done
|
||||
command -v docker >/dev/null && docker version --format 'docker server {{.Server.Version}}' 2>/dev/null
|
||||
@@ -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";
|
||||
@@ -33,6 +35,8 @@ export function DownloadCard({
|
||||
const jobs = snapshot?.jobs ?? [];
|
||||
const latest = jobs[0];
|
||||
const open = latest && OPEN.includes(latest.state) ? latest : undefined;
|
||||
const pending = latest?.state === "pending_approval" ? latest : undefined;
|
||||
const router = useRouter();
|
||||
const files = open ? groupJobFiles(snapshot?.files ?? []) : [];
|
||||
// The newest verify, unless a download ran after it (its result would be stale).
|
||||
const lastCheck = jobs.find((j) => VERIFY_KINDS.includes(j.kind) || j.kind === "download");
|
||||
@@ -58,12 +62,13 @@ 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 && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
|
||||
const canVerify = !open && !pending && !neverRan && status !== "deleting" && !!snapshot;
|
||||
const needsRepair = !open && !pending && !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.";
|
||||
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.";
|
||||
@@ -83,7 +88,9 @@ export function DownloadCard({
|
||||
</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">
|
||||
|
||||
@@ -23,6 +23,7 @@ import { DeploymentStateBadge } from "@/components/deployment-state";
|
||||
import { HubStateBadge } from "@/components/hub-state-badge";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import { ModelStatusBadge } from "@/components/model-status-badge";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatBytes, shortSha } from "@/lib/format";
|
||||
@@ -145,6 +146,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
|
||||
<CopyButton value={model.repoId} label="Copy repo ID" />
|
||||
<ModelStatusBadge status={model.status} />
|
||||
<HubStateBadge state={model.hubState} />
|
||||
<RequestedByBadge name={model.requestedBy} />
|
||||
{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">
|
||||
update available
|
||||
|
||||
@@ -33,8 +33,12 @@ import { Input } from "@/components/ui/input";
|
||||
import { reportSummary, weightsLabel } from "@/lib/benchmark-report";
|
||||
import { CONFIG_ROWS, describeSettings } from "@/lib/benchmark-view";
|
||||
import type { ListRow } from "../benchmark-list";
|
||||
import { cancelBenchmark, deleteBenchmark, renameBenchmark } from "../actions";
|
||||
import { AgentApprovalBar } from "@/components/approval-bar";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import { RunMetaCard } from "@/components/run-meta";
|
||||
import { cancelBenchmark, deleteBenchmark, describeBenchmark, renameBenchmark } from "../actions";
|
||||
import { AbReport } from "./ab-report";
|
||||
import { QualityReport } from "./quality-report";
|
||||
import { BenchmarkReport } from "./benchmark-report";
|
||||
import { PublishCard } from "./publish-card";
|
||||
|
||||
@@ -58,7 +62,8 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
const [r, setR] = useState(initial);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
const [label, setLabel] = useState(initial.label ?? "");
|
||||
const active = r.state === "queued" || r.state === "running";
|
||||
const [description, setDescription] = useState(initial.description ?? "");
|
||||
const active = r.state === "pending_approval" || r.state === "queued" || r.state === "running";
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
@@ -80,7 +85,9 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
body: JSON.stringify({
|
||||
deploymentId: r.deploymentId,
|
||||
deploymentBId: r.kind === "ab" ? r.deploymentBId : null,
|
||||
kind: r.kind,
|
||||
label: r.label,
|
||||
description: r.description,
|
||||
...r.settings,
|
||||
}),
|
||||
});
|
||||
@@ -117,6 +124,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
state={r.state}
|
||||
cancelling={!!r.cancelRequestedAt}
|
||||
/>
|
||||
<RequestedByBadge name={r.requestedBy} />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{r.deploymentId ? (
|
||||
@@ -168,7 +176,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
BetterBench ·{" "}
|
||||
{r.kind === "eval" ? "Kaname" : "BetterBench"} ·{" "}
|
||||
{r.kind === "ab"
|
||||
? `paired A/B, target ±${r.settings.mdePct ?? 1}%, up to ${r.settings.maxPairs ?? 200} pairs`
|
||||
: describeSettings(r.settings)}{" "}
|
||||
@@ -262,6 +270,13 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{r.state === "pending_approval" && (
|
||||
<AgentApprovalBar
|
||||
requestedBy={r.requestedBy}
|
||||
what={`run ${r.kind === "ab" ? "an A/B" : r.kind === "eval" ? "the quality eval" : "a benchmark"} on ${s.deploymentName} (${describeSettings(r.settings)}${r.timeLimitS ? `, at most ${Math.round(r.timeLimitS / 60)} min` : ""})`}
|
||||
base={`/api/benchmarks/${r.id}`}
|
||||
/>
|
||||
)}
|
||||
{r.error && (
|
||||
<div className="flex gap-3 rounded-xl border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm">
|
||||
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-destructive" />
|
||||
@@ -281,7 +296,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
|
||||
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_340px]">
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
{r.kind === "ab" ? <AbReport run={r} /> : <BenchmarkReport run={r} />}
|
||||
{r.kind === "ab" ? <AbReport run={r} /> : r.kind === "eval" ? <QualityReport quality={r.quality} running={active} /> : <BenchmarkReport run={r} />}
|
||||
<LiveLog
|
||||
url={`/api/benchmarks/${r.id}/logs`}
|
||||
title="BetterBench output"
|
||||
@@ -318,7 +333,31 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{r.kind === "run" && (
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Description</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-1.5">
|
||||
<textarea
|
||||
value={description}
|
||||
maxLength={4000}
|
||||
rows={3}
|
||||
placeholder="What this run tries out, e.g. q8_0 KV cache to fit 64k context"
|
||||
className="w-full rounded-md border bg-transparent px-2.5 py-1.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
onBlur={async () =>
|
||||
description !== (r.description ?? "") &&
|
||||
(await describeBenchmark(r.id, description || null)) &&
|
||||
setR({ ...r, description: description.trim() || null })
|
||||
}
|
||||
/>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
Passed to BetterBench (when set before the run starts) and to the launch80 preview, together with the system summary.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<RunMetaCard meta={r.meta} metaB={r.metaB} system={r.system} />
|
||||
{r.kind !== "ab" && (
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Settings measured</CardTitle>
|
||||
|
||||
@@ -190,6 +190,12 @@ export function PublishCard({ runId, defaultTitle, defaultSummary }: { runId: st
|
||||
</span>
|
||||
))}
|
||||
</dd>
|
||||
{p.sections.map((s) => (
|
||||
<div key={s.heading} className="contents">
|
||||
<dt className="text-muted-foreground">{s.heading}</dt>
|
||||
<dd className="whitespace-pre-line">{s.body}</dd>
|
||||
</div>
|
||||
))}
|
||||
<dt className="text-muted-foreground">Data</dt>
|
||||
<dd>{p.phases.join(", ")} · every raw sample</dd>
|
||||
<dt className="text-muted-foreground">Removed</dt>
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { CheckIcon, XIcon } from "lucide-react";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import type { QualityResult } from "@/lib/db/schema";
|
||||
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** A quality eval's result: the score, each section's pass rate and every item. */
|
||||
export function QualityReport({ quality, running }: { quality: QualityResult | null; running: boolean }) {
|
||||
if (!quality) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="text-sm text-muted-foreground">{running ? "The quality eval is running; results appear when it's done." : "No result."}</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Quality</CardTitle>
|
||||
<CardDescription>
|
||||
Eval set {quality.evalSet}: greedy decoding (temperature {quality.config.temperature}, seed {quality.config.seed}), thinking{" "}
|
||||
{quality.config.thinking ? "on" : "off"}
|
||||
{quality.config.contextTokens ? `, context ${quality.config.contextTokens.toLocaleString("en-US")} tokens` : ""}. Scores are the share of items that pass;
|
||||
only results of the same eval set compare.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-4xl font-semibold tabular-nums">{quality.score != null ? `${quality.score}%` : "—"}</span>
|
||||
<span className="text-sm text-muted-foreground">overall (mean of the sections)</span>
|
||||
</div>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Section</TableHead>
|
||||
<TableHead className="text-right">Passed</TableHead>
|
||||
<TableHead className="text-right">Score</TableHead>
|
||||
<TableHead className="text-right">Time</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{quality.sections.map((s) => (
|
||||
<TableRow key={s.section}>
|
||||
<TableCell className="whitespace-normal">
|
||||
<div className="font-medium">{SECTION_LABEL[s.section]}</div>
|
||||
<div className="text-xs text-muted-foreground">{s.unsupported ? `Not counted: ${s.unsupported}` : SECTION_HINT[s.section]}</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">{s.unsupported ? "—" : `${s.passed} / ${s.total}`}</TableCell>
|
||||
<TableCell className="text-right font-medium tabular-nums">{s.score != null ? `${s.score}%` : "—"}</TableCell>
|
||||
<TableCell className="text-right text-muted-foreground tabular-nums">{s.seconds} s</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<ul className="flex flex-col gap-1 text-xs">
|
||||
{quality.items.map((i) => (
|
||||
<li key={`${i.section}-${i.id}`} className="flex items-start gap-1.5">
|
||||
{i.pass ? <CheckIcon className="mt-0.5 size-3.5 shrink-0 text-emerald-600" /> : <XIcon className="mt-0.5 size-3.5 shrink-0 text-destructive" />}
|
||||
<span className="font-mono">{i.id}</span>
|
||||
<span className={cn("min-w-0 break-words text-muted-foreground", !i.pass && "text-foreground")}>{i.detail}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -13,3 +13,4 @@ async function call(url: string, method: string, body?: unknown): Promise<boolea
|
||||
export const cancelBenchmark = (id: string) => call(`/api/benchmarks/${id}/cancel`, "POST");
|
||||
export const deleteBenchmark = (id: string) => call(`/api/benchmarks/${id}`, "DELETE");
|
||||
export const renameBenchmark = (id: string, label: string | null) => call(`/api/benchmarks/${id}`, "PATCH", { label });
|
||||
export const describeBenchmark = (id: string, description: string | null) => call(`/api/benchmarks/${id}`, "PATCH", { description });
|
||||
@@ -4,16 +4,28 @@ import { GaugeIcon, GitCompareIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
import { BenchmarkStateBadge } from "@/components/benchmark-state";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import type { BenchmarkRow } from "@/lib/benchmarks";
|
||||
import { configChips, describeSettings, headline } from "@/lib/benchmark-view";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type ListRow = Omit<BenchmarkRow, "createdAt" | "startedAt" | "finishedAt" | "cancelRequestedAt"> & {
|
||||
export type ListRow = Omit<
|
||||
BenchmarkRow,
|
||||
"createdAt" | "startedAt" | "finishedAt" | "cancelRequestedAt"
|
||||
> & {
|
||||
createdAt: string;
|
||||
startedAt: string | null;
|
||||
finishedAt: string | null;
|
||||
@@ -21,18 +33,35 @@ export type ListRow = Omit<BenchmarkRow, "createdAt" | "startedAt" | "finishedAt
|
||||
};
|
||||
|
||||
const MAX_COMPARE = 16;
|
||||
const fmt = (v: number | null | undefined, digits = 1) => (v == null ? "–" : v.toFixed(digits));
|
||||
const fmt = (v: number | null | undefined, digits = 1) =>
|
||||
v == null ? "–" : v.toFixed(digits);
|
||||
|
||||
/** All runs with their headline numbers; polls while something is queued or running. */
|
||||
export function BenchmarkList({ rows: initial, compact }: { rows: ListRow[]; compact?: boolean }) {
|
||||
export function BenchmarkList({
|
||||
rows: initial,
|
||||
compact,
|
||||
}: {
|
||||
rows: ListRow[];
|
||||
compact?: boolean;
|
||||
}) {
|
||||
const [rows, setRows] = useState(initial);
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
// "" = everything, "-" = started in Kaname, else a token name.
|
||||
const [by, setBy] = useState("");
|
||||
const busy = rows.some((r) => r.state === "queued" || r.state === "running");
|
||||
const tokens = [
|
||||
...new Set(rows.map((r) => r.requestedBy).filter((x): x is string => !!x)),
|
||||
].sort();
|
||||
const shown = rows.filter(
|
||||
(r) => !by || (by === "-" ? !r.requestedBy : r.requestedBy === by),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!busy || compact) return;
|
||||
const t = setInterval(async () => {
|
||||
const res = await fetch("/api/benchmarks", { cache: "no-store" }).catch(() => null);
|
||||
const res = await fetch("/api/benchmarks", { cache: "no-store" }).catch(
|
||||
() => null,
|
||||
);
|
||||
if (res?.ok) setRows(await res.json());
|
||||
}, 3_000);
|
||||
return () => clearInterval(t);
|
||||
@@ -53,22 +82,54 @@ export function BenchmarkList({ rows: initial, compact }: { rows: ListRow[]; com
|
||||
);
|
||||
}
|
||||
|
||||
const toggle = (id: string) => setSelected((s) => (s.includes(id) ? s.filter((x) => x !== id) : s.length < MAX_COMPARE ? [...s, id] : s));
|
||||
const toggle = (id: string) =>
|
||||
setSelected((s) =>
|
||||
s.includes(id)
|
||||
? s.filter((x) => x !== id)
|
||||
: s.length < MAX_COMPARE
|
||||
? [...s, id]
|
||||
: s,
|
||||
);
|
||||
const comparable = rows.filter((r) => r.state === "completed");
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
{!compact && comparable.length > 1 && (
|
||||
<div className="flex items-center justify-between gap-2 text-sm">
|
||||
<span className="text-muted-foreground">{selected.length === 0 ? "Select completed runs to compare them." : `${selected.length} selected (up to ${MAX_COMPARE}).`}</span>
|
||||
<Link
|
||||
href={`/benchmarks/compare?ids=${selected.join(",")}`}
|
||||
className={cn(buttonVariants({ size: "sm" }), selected.length < 2 && "pointer-events-none opacity-50")}
|
||||
aria-disabled={selected.length < 2}
|
||||
>
|
||||
<GitCompareIcon />
|
||||
Compare
|
||||
</Link>
|
||||
{!compact && (comparable.length > 1 || tokens.length > 0) && (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-sm">
|
||||
<span className="text-muted-foreground">
|
||||
{selected.length === 0
|
||||
? "Select completed runs to compare them."
|
||||
: `${selected.length} selected (up to ${MAX_COMPARE}).`}
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
{tokens.length > 0 && (
|
||||
<NativeSelect
|
||||
value={by}
|
||||
onChange={(e) => setBy(e.target.value)}
|
||||
className="h-8 text-xs"
|
||||
aria-label="Requested by"
|
||||
>
|
||||
<option value="">Requested by anyone</option>
|
||||
<option value="-">Started in Kaname</option>
|
||||
{tokens.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{t} (API)
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
)}
|
||||
<Link
|
||||
href={`/benchmarks/compare?ids=${selected.join(",")}`}
|
||||
className={cn(
|
||||
buttonVariants({ size: "sm" }),
|
||||
selected.length < 2 && "pointer-events-none opacity-50",
|
||||
)}
|
||||
aria-disabled={selected.length < 2}
|
||||
>
|
||||
<GitCompareIcon />
|
||||
Compare
|
||||
</Link>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<Card className="py-0">
|
||||
@@ -78,27 +139,42 @@ export function BenchmarkList({ rows: initial, compact }: { rows: ListRow[]; com
|
||||
{!compact && <TableHead className="w-8" />}
|
||||
<TableHead>Run</TableHead>
|
||||
<TableHead className="hidden lg:table-cell">Settings</TableHead>
|
||||
<TableHead className="text-right" title="Weighted single-stream decode speed">
|
||||
<TableHead
|
||||
className="text-right"
|
||||
title="Weighted single-stream decode speed"
|
||||
>
|
||||
Decode t/s
|
||||
</TableHead>
|
||||
<TableHead className="text-right" title="Median time to first token">
|
||||
<TableHead
|
||||
className="text-right"
|
||||
title="Median time to first token"
|
||||
>
|
||||
TTFT
|
||||
</TableHead>
|
||||
<TableHead className="hidden text-right md:table-cell" title="Prompt processing at the deepest measured input">
|
||||
<TableHead
|
||||
className="hidden text-right md:table-cell"
|
||||
title="Prompt processing at the deepest measured input"
|
||||
>
|
||||
Prefill t/s
|
||||
</TableHead>
|
||||
<TableHead className="hidden text-right md:table-cell" title="Best aggregate throughput under parallel load">
|
||||
<TableHead
|
||||
className="hidden text-right md:table-cell"
|
||||
title="Best aggregate throughput under parallel load"
|
||||
>
|
||||
Peak t/s
|
||||
</TableHead>
|
||||
<TableHead className="w-28">State</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{rows.map((r) => {
|
||||
{shown.map((r) => {
|
||||
const h = headline(r.summary);
|
||||
const s = r.snapshot;
|
||||
return (
|
||||
<TableRow key={r.id} data-state={selected.includes(r.id) ? "selected" : undefined}>
|
||||
<TableRow
|
||||
key={r.id}
|
||||
data-state={selected.includes(r.id) ? "selected" : undefined}
|
||||
>
|
||||
{!compact && (
|
||||
<TableCell>
|
||||
<Checkbox
|
||||
@@ -110,35 +186,68 @@ export function BenchmarkList({ rows: initial, compact }: { rows: ListRow[]; com
|
||||
</TableCell>
|
||||
)}
|
||||
<TableCell className="whitespace-normal">
|
||||
<Link href={`/benchmarks/${r.id}`} className="font-medium hover:underline">
|
||||
<Link
|
||||
href={`/benchmarks/${r.id}`}
|
||||
className="font-medium hover:underline"
|
||||
>
|
||||
{r.label ?? s.deploymentName}
|
||||
</Link>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<div className="flex flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
|
||||
{r.label && `${s.deploymentName} · `}
|
||||
{s.repoId} · <LocalTime value={r.createdAt} />
|
||||
<RequestedByBadge
|
||||
name={r.requestedBy}
|
||||
className="h-4 text-[10px]"
|
||||
/>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="hidden max-w-md whitespace-normal lg:table-cell">
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<span className="rounded-4xl border border-foreground/15 px-1.5 text-[11px] leading-4">{s.runtimeName}</span>
|
||||
<span className="rounded-4xl border border-foreground/15 px-1.5 text-[11px] leading-4">
|
||||
{s.runtimeName}
|
||||
</span>
|
||||
{configChips(s).map((c) => (
|
||||
<span key={c} className="rounded-4xl bg-muted px-1.5 text-[11px] leading-4 text-muted-foreground">
|
||||
<span
|
||||
key={c}
|
||||
className="rounded-4xl bg-muted px-1.5 text-[11px] leading-4 text-muted-foreground"
|
||||
>
|
||||
{c}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-0.5 text-[11px] text-muted-foreground">{describeSettings(r.settings)}</div>
|
||||
<div className="mt-0.5 text-[11px] text-muted-foreground">
|
||||
{describeSettings(r.settings)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-medium tabular-nums">{fmt(h.decode)}</TableCell>
|
||||
<TableCell className="text-right tabular-nums">{h.ttftMs != null ? `${Math.round(h.ttftMs)} ms` : "–"}</TableCell>
|
||||
<TableCell className="hidden text-right tabular-nums md:table-cell" title={h.prefill ? `at ${h.prefill.depth} tokens` : undefined}>
|
||||
<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>
|
||||
) : (
|
||||
fmt(h.decode)
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">
|
||||
{h.ttftMs != null ? `${Math.round(h.ttftMs)} ms` : "–"}
|
||||
</TableCell>
|
||||
<TableCell
|
||||
className="hidden text-right tabular-nums md:table-cell"
|
||||
title={
|
||||
h.prefill ? `at ${h.prefill.depth} tokens` : undefined
|
||||
}
|
||||
>
|
||||
{fmt(h.prefill?.tps, 0)}
|
||||
</TableCell>
|
||||
<TableCell className="hidden text-right tabular-nums md:table-cell" title={h.peak ? `at ${h.peak.level} parallel` : undefined}>
|
||||
<TableCell
|
||||
className="hidden text-right tabular-nums md:table-cell"
|
||||
title={h.peak ? `at ${h.peak.level} parallel` : undefined}
|
||||
>
|
||||
{fmt(h.peak?.tps)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
|
||||
<BenchmarkStateBadge
|
||||
state={r.state}
|
||||
cancelling={!!r.cancelRequestedAt}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
|
||||
@@ -4,6 +4,8 @@ import { BenchmarkStateBadge } from "@/components/benchmark-state";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { getBenchmarks } from "@/lib/benchmarks";
|
||||
import { metaRows } from "@/lib/benchmark-meta";
|
||||
import { SECTION_LABEL } from "@/lib/quality-view";
|
||||
import { CONFIG_ROWS, deltaPct, describeSettings, headline } from "@/lib/benchmark-view";
|
||||
import type { BenchmarkSummary } from "@/lib/db/schema";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -11,7 +13,7 @@ import { cn } from "@/lib/utils";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Compare benchmarks" };
|
||||
|
||||
type Metric = { label: string; unit: string; higherIsBetter: boolean; digits: number; get: (s: BenchmarkSummary | null) => number | null };
|
||||
type Metric = { label: string; unit: string; higherIsBetter: boolean; digits: number; get: (s: BenchmarkSummary | null, runIndex?: number) => number | null };
|
||||
|
||||
/** Differences smaller than this are shown without color: below what a single run can resolve. */
|
||||
const NOISE_PCT = 2;
|
||||
@@ -62,6 +64,7 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
|
||||
{
|
||||
group: "Headline",
|
||||
rows: [
|
||||
{ label: "Prefill (deepest prompt)", unit: "t/s", higherIsBetter: true, digits: 0, get: (s) => headline(s).prefill?.tps ?? null },
|
||||
{ label: "Decode (weighted)", unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => headline(s).decode },
|
||||
{ label: "Time to first token", unit: "ms", higherIsBetter: false, digits: 0, get: (s) => headline(s).ttftMs },
|
||||
],
|
||||
@@ -85,8 +88,30 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
|
||||
rows: levels.map((l) => ({ label: `${l} parallel`, unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => s?.concurrency.find((c) => c.level === l)?.aggregate_tps ?? null })),
|
||||
},
|
||||
];
|
||||
// Quality evals: the score and each section's pass rate (only when some of the runs are evals).
|
||||
const quality = runs.map((r) => r.quality);
|
||||
if (quality.some(Boolean)) {
|
||||
const sections = [...new Set(quality.flatMap((q) => q?.sections.map((s) => s.section) ?? []))];
|
||||
groups.push({
|
||||
group: `Quality (${[...new Set(quality.filter(Boolean).map((q) => q!.evalSet))].join(", ")})`,
|
||||
rows: [
|
||||
{ label: "Score", unit: "%", higherIsBetter: true, digits: 1, get: (_s, i) => quality[i!]?.score ?? null },
|
||||
...sections.map((sec) => ({
|
||||
label: SECTION_LABEL[sec],
|
||||
unit: "%",
|
||||
higherIsBetter: true,
|
||||
digits: 1,
|
||||
get: (_s: BenchmarkSummary | null, i?: number) => quality[i!]?.sections.find((x) => x.section === sec)?.score ?? null,
|
||||
})),
|
||||
],
|
||||
});
|
||||
}
|
||||
const metrics = groups.filter((g) => g.rows.length > 0);
|
||||
|
||||
// Hardware, runtime version, model/quant/KV, context and concurrency as recorded at the start of each run.
|
||||
const metaByRun = runs.map((r) => (r.meta ? metaRows(r.meta) : null));
|
||||
const metaKeys = [...new Map(metaByRun.flatMap((rows) => rows ?? []).map((x) => [x.key, x.label])).entries()];
|
||||
const metaTable = metaKeys.map(([key, label]) => ({ key, label, values: metaByRun.map((rows) => (rows ? (rows.find((x) => x.key === key)?.value ?? null) : null)) }));
|
||||
const configRows = CONFIG_ROWS.map((row) => ({ row, values: runs.map((r) => row.value(r.snapshot)) })).filter((x) => x.values.some((v) => v != null));
|
||||
const corpora = new Set(sums.map((s) => s?.corpusVersion).filter(Boolean));
|
||||
const anyQuick = runs.some((r) => r.summary?.quick);
|
||||
@@ -122,6 +147,28 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{metaTable.length > 0 && (
|
||||
<>
|
||||
<TableRow className="bg-muted/40 hover:bg-muted/40">
|
||||
<TableCell colSpan={runs.length + 1} className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
|
||||
Hardware & runtime
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{metaTable.map(({ key, label, values }) => {
|
||||
const differs = new Set(values.map((v) => v ?? "")).size > 1;
|
||||
return (
|
||||
<TableRow key={`meta-${key}`} className={cn(differs && "bg-amber-500/5")}>
|
||||
<TableCell className={cn("text-xs", differs ? "font-medium" : "text-muted-foreground")}>{label}</TableCell>
|
||||
{values.map((v, i) => (
|
||||
<TableCell key={i} className={cn("font-mono text-xs break-all whitespace-normal", differs && i > 0 && v !== values[0] && "text-amber-700 dark:text-amber-300")}>
|
||||
{v ?? <span className="text-muted-foreground">not recorded</span>}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
<TableRow className="bg-muted/40 hover:bg-muted/40">
|
||||
<TableCell colSpan={runs.length + 1} className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
|
||||
Settings
|
||||
@@ -159,7 +206,7 @@ function MetricGroup({ group, rows, sums, cols }: { group: string; rows: Metric[
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{rows.map((m) => {
|
||||
const vals = sums.map((s) => m.get(s));
|
||||
const vals = sums.map((s, i) => m.get(s, i));
|
||||
const present = vals.filter((v): v is number => v != null);
|
||||
const best = present.length > 1 ? (m.higherIsBetter ? Math.max(...present) : Math.min(...present)) : null;
|
||||
return (
|
||||
|
||||
@@ -9,19 +9,32 @@ import { BarChart } from "@/components/bar-chart";
|
||||
import { BenchmarkStateBadge } from "@/components/benchmark-state";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { AgentApprovalBar } from "@/components/approval-bar";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import { metaRows } from "@/lib/benchmark-meta";
|
||||
import { describeSettings, headline } from "@/lib/benchmark-view";
|
||||
import type { benchmarkSweeps, BenchmarkSummary, ResourceStats, SweepVariant } from "@/lib/db/schema";
|
||||
import type { benchmarkSweeps, BenchmarkSummary, QualityResult, ResourceStats, RunMeta, SweepVariant } from "@/lib/db/schema";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type Sweep = typeof benchmarkSweeps.$inferSelect;
|
||||
type Run = { id: string; state: string; summary: BenchmarkSummary | null; resources: ResourceStats | null; phase: string | null; error: string | null };
|
||||
type Run = {
|
||||
id: string;
|
||||
state: string;
|
||||
summary: BenchmarkSummary | null;
|
||||
resources: ResourceStats | null;
|
||||
phase: string | null;
|
||||
error: string | null;
|
||||
meta: RunMeta | null;
|
||||
quality: QualityResult | null;
|
||||
};
|
||||
export type SweepData = { sweep: Sweep; runs: Run[] };
|
||||
|
||||
const VARIANT_STATE: Record<SweepVariant["state"], string> = {
|
||||
pending: "Waiting",
|
||||
deploying: "Deploying",
|
||||
benchmarking: "Benchmarking",
|
||||
evaluating: "Quality eval",
|
||||
done: "Done",
|
||||
failed: "Failed",
|
||||
skipped: "Skipped",
|
||||
@@ -37,11 +50,15 @@ type Row = {
|
||||
cpu: number | null;
|
||||
ram: number | null;
|
||||
vram: number | null;
|
||||
power: number | null;
|
||||
temp: number | null;
|
||||
quality: number | null;
|
||||
};
|
||||
|
||||
function rowsOf(data: SweepData): Row[] {
|
||||
return data.sweep.variants.map((v) => {
|
||||
const run = data.runs.find((r) => r.id === v.runId) ?? null;
|
||||
const ev = data.runs.find((r) => r.id === v.evalRunId) ?? null;
|
||||
const h = headline(run?.summary ?? null);
|
||||
const c = run?.resources?.containers.find((x) => x.side === "a");
|
||||
const g = run?.resources?.gpus ?? [];
|
||||
@@ -54,11 +71,28 @@ function rowsOf(data: SweepData): Row[] {
|
||||
peak: h.peak?.tps ?? null,
|
||||
cpu: c?.cpuAvg ?? null,
|
||||
ram: c?.memPeakBytes ?? null,
|
||||
vram: g.length ? g.reduce((s, x) => s + x.vramPeakMb, 0) : null,
|
||||
vram: g.some((x) => x.vramPeakMb != null) ? g.reduce((s, x) => s + (x.vramPeakMb ?? 0), 0) : null,
|
||||
power: g.some((x) => x.powerAvgW != null) ? g.reduce((s, x) => s + (x.powerAvgW ?? 0), 0) : null,
|
||||
temp: g.some((x) => x.tempPeakC != null) ? Math.max(...g.map((x) => x.tempPeakC ?? -Infinity)) : null,
|
||||
quality: ev?.quality?.score ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Recorded setup (GPU, PCIe, engine version, quant, KV cache, context, concurrency): values shared by
|
||||
* every variant go above the table, the ones that differ become columns.
|
||||
*/
|
||||
function setupOf(rows: Row[]) {
|
||||
const per = rows.map((r) => (r.run?.meta ? metaRows(r.run.meta).filter((x) => x.key !== "image" && x.key !== "digest") : null));
|
||||
const keys = [...new Map(per.flatMap((x) => x ?? []).map((x) => [x.key, x.label])).entries()];
|
||||
const recorded = per.filter((x) => x != null);
|
||||
const value = (i: number, key: string) => per[i]?.find((x) => x.key === key)?.value ?? null;
|
||||
const differs = keys.filter(([key]) => new Set(recorded.map((x) => x.find((y) => y.key === key)?.value ?? "")).size > 1);
|
||||
const shared = keys.filter((k) => !differs.includes(k)).map(([key, label]) => ({ label, value: recorded[0]?.find((y) => y.key === key)?.value ?? null }));
|
||||
return { shared: recorded.length ? shared : [], columns: differs.map(([key, label]) => ({ key, label })), value };
|
||||
}
|
||||
|
||||
/** Best value per column (higher or lower is better), to set it in bold. */
|
||||
function best(rows: Row[], key: keyof Row, higher: boolean): number | null {
|
||||
const vals = rows.map((r) => r[key]).filter((x): x is number => typeof x === "number");
|
||||
@@ -71,7 +105,7 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
|
||||
const [data, setData] = useState(initial);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const { sweep } = data;
|
||||
const active = sweep.state === "queued" || sweep.state === "running";
|
||||
const active = sweep.state === "pending_approval" || sweep.state === "queued" || sweep.state === "running";
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
@@ -95,6 +129,7 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
|
||||
}
|
||||
|
||||
const rows = rowsOf(data);
|
||||
const setup = setupOf(rows);
|
||||
const finished = rows.filter((r) => r.decode != null);
|
||||
const runIds = rows.map((r) => r.v.runId).filter((x): x is string => !!x && rows.some((r) => r.run?.id === x && r.run.state === "completed"));
|
||||
const bestOf = {
|
||||
@@ -105,7 +140,11 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
|
||||
cpu: best(rows, "cpu", false),
|
||||
ram: best(rows, "ram", false),
|
||||
vram: best(rows, "vram", false),
|
||||
power: best(rows, "power", false),
|
||||
temp: best(rows, "temp", false),
|
||||
quality: best(rows, "quality", true),
|
||||
};
|
||||
const hasQuality = !!sweep.settings.quality;
|
||||
const cell = (v: number | null, b: number | null, fmt: (x: number) => string) => (
|
||||
<td className={cn("px-3 py-2 text-right tabular-nums", v != null && v === b && "font-semibold")}>{v != null ? fmt(v) : "—"}</td>
|
||||
);
|
||||
@@ -131,6 +170,7 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RequestedByBadge name={sweep.requestedBy} />
|
||||
<BenchmarkStateBadge state={sweep.state} cancelling={!!sweep.cancelRequestedAt && active} />
|
||||
{runIds.length >= 2 && (
|
||||
<Link href={`/benchmarks/compare?ids=${runIds.join(",")}`} className={buttonVariants({ variant: "outline", size: "sm" })}>
|
||||
@@ -157,6 +197,13 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
|
||||
{done} of {rows.length} variants finished. Each variant is deployed, benchmarked and removed again, one after another.
|
||||
</p>
|
||||
)}
|
||||
{sweep.state === "pending_approval" && (
|
||||
<AgentApprovalBar
|
||||
requestedBy={sweep.requestedBy}
|
||||
what={`run a sweep of ${rows.length} variants from ${sweep.base.name} (${sweep.params.map((p) => `${p.key}: ${p.values.join(", ")}`).join("; ")}${sweep.timeLimitS ? `, at most ${Math.round(sweep.timeLimitS / 60)} min` : ""}); each variant is deployed, benchmarked and removed`}
|
||||
base={`/api/sweeps/${sweep.id}`}
|
||||
/>
|
||||
)}
|
||||
{sweep.error && <p className="text-sm text-destructive">{sweep.error}</p>}
|
||||
|
||||
{finished.length > 0 && (
|
||||
@@ -183,6 +230,14 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
|
||||
<CardHeader>
|
||||
<CardTitle>Variants</CardTitle>
|
||||
<CardDescription>Best value per column in bold. Resource figures are averages/peaks over the run.</CardDescription>
|
||||
{setup.shared.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{setup.shared
|
||||
.filter((x) => x.value)
|
||||
.map((x) => `${x.label}: ${x.value}`)
|
||||
.join(" · ")}
|
||||
</p>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent className="overflow-x-auto px-0">
|
||||
<table className="w-full text-sm">
|
||||
@@ -190,17 +245,25 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
|
||||
<tr className="border-b">
|
||||
<th className="px-3 py-2 text-left font-medium">Variant</th>
|
||||
<th className="px-3 py-2 text-left font-medium">State</th>
|
||||
{setup.columns.map((c) => (
|
||||
<th key={c.key} className="px-3 py-2 text-left font-medium">
|
||||
{c.label}
|
||||
</th>
|
||||
))}
|
||||
<th className="px-3 py-2 text-right font-medium">Decode t/s</th>
|
||||
{hasQuality && <th className="px-3 py-2 text-right font-medium">Quality</th>}
|
||||
<th className="px-3 py-2 text-right font-medium">TTFT ms</th>
|
||||
<th className="px-3 py-2 text-right font-medium">Prefill t/s</th>
|
||||
<th className="px-3 py-2 text-right font-medium">Peak t/s</th>
|
||||
<th className="px-3 py-2 text-right font-medium">CPU cores</th>
|
||||
<th className="px-3 py-2 text-right font-medium">Peak RAM</th>
|
||||
<th className="px-3 py-2 text-right font-medium">Peak VRAM</th>
|
||||
<th className="px-3 py-2 text-right font-medium">GPU power</th>
|
||||
<th className="px-3 py-2 text-right font-medium">Peak temp</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r) => (
|
||||
{rows.map((r, i) => (
|
||||
<tr key={r.v.index} className="border-b last:border-0">
|
||||
<td className="px-3 py-2 font-mono text-xs">
|
||||
{r.v.runId ? (
|
||||
@@ -216,13 +279,21 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
|
||||
{r.v.state === "benchmarking" && r.run?.phase ? ` · ${r.run.phase}` : ""}
|
||||
{(r.v.error || r.run?.error) && r.v.state === "failed" ? ` · ${(r.v.error ?? r.run?.error ?? "").slice(0, 60)}` : ""}
|
||||
</td>
|
||||
{setup.columns.map((c) => (
|
||||
<td key={c.key} className="px-3 py-2 font-mono text-xs">
|
||||
{setup.value(i, c.key) ?? "–"}
|
||||
</td>
|
||||
))}
|
||||
{cell(r.decode, bestOf.decode, (x) => x.toFixed(1))}
|
||||
{hasQuality && cell(r.quality, bestOf.quality, (x) => `${x}%`)}
|
||||
{cell(r.ttft, bestOf.ttft, (x) => x.toFixed(0))}
|
||||
{cell(r.prefill, bestOf.prefill, (x) => x.toFixed(0))}
|
||||
{cell(r.peak, bestOf.peak, (x) => x.toFixed(1))}
|
||||
{cell(r.cpu, bestOf.cpu, (x) => x.toFixed(2))}
|
||||
{cell(r.ram, bestOf.ram, (x) => formatBytes(x))}
|
||||
{cell(r.vram, bestOf.vram, (x) => `${(x / 1024).toFixed(1)} GiB`)}
|
||||
{cell(r.power, bestOf.power, (x) => `${Math.round(x)} W`)}
|
||||
{cell(r.temp, bestOf.temp, (x) => `${Math.round(x)} °C`)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
|
||||
@@ -64,6 +64,7 @@ export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initia
|
||||
const keys = base ? sweepKeysFor(base.engine, base.accelerator) : [];
|
||||
const [params, setParams] = useState<Param[]>([{ key: "contextSize", text: "", files: [] }]);
|
||||
const [label, setLabel] = useState("");
|
||||
const [quality, setQuality] = useState(false);
|
||||
const [mode, setMode] = useState("quick");
|
||||
const [passes, setPasses] = useState("10");
|
||||
const [phases, setPhases] = useState<BenchmarkPhase[]>(["decode", "prefill", "concurrency"]);
|
||||
@@ -95,6 +96,7 @@ export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initia
|
||||
quick: mode === "quick",
|
||||
passes: mode === "custom" ? Number(passes) || 10 : null,
|
||||
phases: phases.length === PHASES.length ? [] : phases,
|
||||
quality,
|
||||
}),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
@@ -205,6 +207,13 @@ export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initia
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<label className="flex cursor-pointer items-start gap-2 text-sm">
|
||||
<Checkbox checked={quality} onCheckedChange={(v) => setQuality(v === true)} className="mt-0.5" />
|
||||
<span className="flex flex-col">
|
||||
<span>Also run the quality eval on each variant</span>
|
||||
<span className="text-xs text-muted-foreground">Tool calling, coding and long-context retrieval, after the speed run (adds a few minutes per variant).</span>
|
||||
</span>
|
||||
</label>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="sw-label">Label</Label>
|
||||
<Input id="sw-label" value={label} onChange={(e) => setLabel(e.target.value)} maxLength={80} placeholder="e.g. context vs KV cache (optional)" />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { GaugeIcon, GitCompareArrowsIcon, Grid3x3Icon } from "lucide-react";
|
||||
import { BadgeCheckIcon, GaugeIcon, GitCompareArrowsIcon, Grid3x3Icon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
@@ -14,6 +14,8 @@ import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { abHeadline } from "@/lib/ab-report";
|
||||
import { headline } from "@/lib/benchmark-view";
|
||||
import type { BenchmarkPhase } from "@/lib/db/schema";
|
||||
import { QUALITY_SECTIONS, type QualitySection } from "@/lib/db/schema";
|
||||
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ListRow } from "../../benchmarks/benchmark-list";
|
||||
|
||||
@@ -23,7 +25,7 @@ const PHASES: { id: BenchmarkPhase; label: string; hint: string }[] = [
|
||||
{ id: "concurrency", label: "Parallel requests", hint: "1, 2, 4 and 8 at once" },
|
||||
];
|
||||
|
||||
type Mode = "run" | "ab" | "sweep";
|
||||
type Mode = "run" | "ab" | "quality" | "sweep";
|
||||
type Peer = { id: string; name: string; state: string; modelId: string };
|
||||
|
||||
/** Benchmark this deployment: a single run, a paired A/B against another one, or a sweep. */
|
||||
@@ -34,12 +36,14 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
|
||||
const [passes, setPasses] = useState("10");
|
||||
const [phases, setPhases] = useState<BenchmarkPhase[]>(["decode", "prefill", "concurrency"]);
|
||||
const [label, setLabel] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [runs, setRuns] = useState(initial);
|
||||
const [peers, setPeers] = useState<Peer[] | null>(null);
|
||||
const [peerId, setPeerId] = useState("");
|
||||
const [mde, setMde] = useState("1");
|
||||
const [maxPairs, setMaxPairs] = useState("200");
|
||||
const [sections, setSections] = useState<QualitySection[]>([...QUALITY_SECTIONS]);
|
||||
|
||||
const active = runs.some((r) => r.state === "queued" || r.state === "running");
|
||||
useEffect(() => {
|
||||
@@ -73,7 +77,7 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
|
||||
async function start(body: Record<string, unknown>) {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/benchmarks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ deploymentId, label: label.trim() || null, ...body }) });
|
||||
const res = await fetch("/api/benchmarks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ deploymentId, label: label.trim() || null, description: description.trim() || null, ...body }) });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`);
|
||||
router.push(`/benchmarks/${json.id}`);
|
||||
@@ -86,6 +90,7 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
|
||||
const TABS: { id: Mode; label: string; icon: typeof GaugeIcon }[] = [
|
||||
{ id: "run", label: "Run", icon: GaugeIcon },
|
||||
{ id: "ab", label: "A/B", icon: GitCompareArrowsIcon },
|
||||
{ id: "quality", label: "Quality", icon: BadgeCheckIcon },
|
||||
{ id: "sweep", label: "Sweep", icon: Grid3x3Icon },
|
||||
];
|
||||
|
||||
@@ -138,6 +143,7 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
|
||||
))}
|
||||
</div>
|
||||
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
|
||||
<Input value={description} onChange={(e) => setDescription(e.target.value)} maxLength={4000} placeholder="Description: what this run tries out (optional, published with it)" />
|
||||
<Button
|
||||
onClick={() =>
|
||||
start({ quick: mode === "quick", passes: mode === "custom" ? Number(passes) || 10 : null, phases: phases.length === PHASES.length ? [] : phases })
|
||||
@@ -195,6 +201,7 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
|
||||
</label>
|
||||
</div>
|
||||
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. f16 vs q8_0 KV (optional)" />
|
||||
<Input value={description} onChange={(e) => setDescription(e.target.value)} maxLength={4000} placeholder="Description: what this run tries out (optional, published with it)" />
|
||||
<Button
|
||||
onClick={() => start({ deploymentBId: peerId, mdePct: Number(mde) || 1, maxPairs: Math.max(12, Number(maxPairs) || 200) })}
|
||||
disabled={!running || busy || !peer || peer.state !== "running"}
|
||||
@@ -208,6 +215,32 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === "quality" && (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A short, deterministic check of the answers (greedy decoding, fixed seed, thinking off): to see whether a quant, KV cache type or build changes quality,
|
||||
next to the speed numbers.
|
||||
</p>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{QUALITY_SECTIONS.map((s) => (
|
||||
<label key={s} className="flex cursor-pointer items-start gap-2">
|
||||
<Checkbox checked={sections.includes(s)} onCheckedChange={(v) => setSections((cur) => (v ? [...cur, s] : cur.filter((x) => x !== s)))} className="mt-0.5" />
|
||||
<span className="flex flex-col">
|
||||
<span>{SECTION_LABEL[s]}</span>
|
||||
<span className="text-xs text-muted-foreground">{SECTION_HINT[s]}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
|
||||
<Button onClick={() => start({ kind: "eval", evalSections: sections.length === QUALITY_SECTIONS.length ? [] : sections })} disabled={!running || busy || sections.length === 0}>
|
||||
<BadgeCheckIcon />
|
||||
Run quality eval
|
||||
</Button>
|
||||
{!running && <p className="text-xs text-muted-foreground">Start the deployment to evaluate it.</p>}
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === "sweep" && (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
@@ -228,11 +261,15 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
|
||||
return (
|
||||
<Link key={r.id} href={`/benchmarks/${r.id}`} className="flex items-center justify-between gap-2 rounded-md px-1.5 py-1 hover:bg-muted">
|
||||
<span className="min-w-0 truncate">
|
||||
{r.kind === "ab" && <span className="mr-1 rounded border px-1 text-[10px] text-muted-foreground">A/B</span>}
|
||||
{r.kind !== "run" && <span className="mr-1 rounded border px-1 text-[10px] text-muted-foreground">{r.kind === "ab" ? "A/B" : "quality"}</span>}
|
||||
{r.label ?? new Date(r.createdAt).toLocaleString()}
|
||||
</span>
|
||||
<span className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground tabular-nums">
|
||||
{r.kind === "ab" ? r.ab && abHeadline(r.ab.decode_tps) : h.decode != null && `${h.decode.toFixed(1)} t/s`}
|
||||
{r.kind === "ab"
|
||||
? r.ab && abHeadline(r.ab.decode_tps)
|
||||
: r.kind === "eval"
|
||||
? r.quality?.score != null && `${r.quality.score}%`
|
||||
: h.decode != null && `${h.decode.toFixed(1)} t/s`}
|
||||
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
|
||||
</span>
|
||||
</Link>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { ExternalLinkIcon, PencilIcon, PlayIcon, SendIcon, SquareIcon, Trash2Icon } from "lucide-react";
|
||||
import { ExternalLinkIcon, PencilIcon, PlayIcon, SendIcon, ShieldCheckIcon, ShieldIcon, SquareIcon, Trash2Icon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { AgentApprovalBar } from "@/components/approval-bar";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
@@ -83,6 +86,13 @@ export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment;
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h1 className="text-xl font-semibold">{d.name}</h1>
|
||||
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
|
||||
<RequestedByBadge name={d.requestedBy} />
|
||||
{d.protected && (
|
||||
<span className="inline-flex items-center gap-1 rounded-4xl border border-emerald-500/30 bg-emerald-500/10 px-2 text-xs text-emerald-700 dark:text-emerald-300">
|
||||
<ShieldCheckIcon className="size-3" />
|
||||
protected
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<Link href={`/${d.repoId}`} className="hover:underline">
|
||||
@@ -118,6 +128,19 @@ export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment;
|
||||
Start
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
title={d.protected ? "Agents can't touch it now; click to allow them again" : "Agents (API tokens) can't edit, stop, delete or benchmark a protected deployment, nor crowd it out of VRAM"}
|
||||
onClick={async () => {
|
||||
const res = await fetch(`/api/deployments/${d.id}/protect`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ protected: !d.protected }) });
|
||||
if (!res.ok) return void toast.error(`Could not change it (${res.status})`);
|
||||
setD({ ...d, protected: !d.protected });
|
||||
toast.success(d.protected ? "No longer protected from agents" : "Protected from agents");
|
||||
}}
|
||||
>
|
||||
{d.protected ? <ShieldCheckIcon /> : <ShieldIcon />}
|
||||
{d.protected ? "Protected" : "Protect"}
|
||||
</Button>
|
||||
<Link
|
||||
href={`/deployments/${d.id}/edit`}
|
||||
className={cn(buttonVariants({ variant: "outline" }), active && "pointer-events-none opacity-50")}
|
||||
@@ -153,6 +176,13 @@ export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment;
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{d.startRequestedAt && (
|
||||
<AgentApprovalBar
|
||||
requestedBy={d.requestedBy}
|
||||
what={`start this deployment (${d.runtimeName}${file ? `, ${file}` : ""}, context ${d.options.contextSize}${d.memoryMb ? `, ${formatBytes(d.memoryMb * 2 ** 20)} RAM limit` : ""})`}
|
||||
base={`/api/deployments/${d.id}`}
|
||||
/>
|
||||
)}
|
||||
|
||||
{d.state === "failed" && d.error && (
|
||||
<pre className="max-h-72 overflow-auto rounded-xl bg-destructive/10 px-4 py-3 text-xs whitespace-pre-wrap text-destructive">{d.error}</pre>
|
||||
|
||||
@@ -22,6 +22,7 @@ import { Label } from "@/components/ui/label";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import type {
|
||||
DeploymentOptions,
|
||||
HardwareGpu,
|
||||
HostGpu,
|
||||
RuntimeAccelerator,
|
||||
RuntimeEngine,
|
||||
@@ -32,6 +33,7 @@ import {
|
||||
buildCommand,
|
||||
ENGINE_PORT,
|
||||
estimateMemoryMb,
|
||||
estimateVramMb,
|
||||
renderCommand,
|
||||
} from "@/lib/deploy-command";
|
||||
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
|
||||
@@ -62,6 +64,8 @@ export type FormHost = {
|
||||
cpuFeatures: string[];
|
||||
nvidia: boolean;
|
||||
gpus: HostGpu[];
|
||||
/** All GPUs on the host with Settings → Hardware applied (Intel/AMD VRAM for the estimate). */
|
||||
hardwareGpus: HardwareGpu[];
|
||||
} | null;
|
||||
export type FormInitial = {
|
||||
id?: string;
|
||||
@@ -343,6 +347,10 @@ export function DeploymentForm({
|
||||
? hostGpus.filter((g) => gpuIds.includes(g.uuid))
|
||||
: hostGpus;
|
||||
const vramMb = chosenGpus.reduce((s, g) => s + g.memoryMb, 0);
|
||||
// Intel/AMD GPUs come in as /dev/dri: all of them, VRAM as detected (or set in Settings → Hardware).
|
||||
const driGpus = (host?.hardwareGpus ?? []).filter((g) => (accelerator === "rocm" ? g.vendor === "amd" : g.vendor === "intel" || g.vendor === "amd"));
|
||||
const gpuVramMb = accelerator === "nvidia" ? vramMb || null : driGpus.some((g) => g.vramMb) ? driGpus.reduce((s, g) => s + (g.vramMb ?? 0), 0) : null;
|
||||
const vramEstimate = model && gpu ? estimateVramMb(fileBytes, options.contextSize, engine, options, gpuVramMb) : null;
|
||||
const memory = memoryTouched ? intOrNull(memoryMb) : estimate;
|
||||
const preview =
|
||||
runtime && model
|
||||
@@ -683,7 +691,7 @@ export function DeploymentForm({
|
||||
Accepts any of the {apiKeyCount} key
|
||||
{apiKeyCount === 1 ? "" : "s"} from{" "}
|
||||
<Link href="/settings/api-keys" className="underline">
|
||||
Settings → API keys
|
||||
Settings → Runtime API keys
|
||||
</Link>{" "}
|
||||
as{" "}
|
||||
<code className="font-mono">Authorization: Bearer</code>.
|
||||
@@ -840,6 +848,20 @@ export function DeploymentForm({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{accelerator !== "nvidia" && driGpus.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground sm:col-span-2">
|
||||
{driGpus.map((g) => `${g.name ?? "GPU"}${g.vramMb ? ` (${formatBytes(g.vramMb * 2 ** 20)})` : ""}`).join(", ")} via /dev/dri
|
||||
</p>
|
||||
)}
|
||||
{model && (
|
||||
<p className={`text-xs sm:col-span-2 ${vramEstimate != null && gpuVramMb != null && vramEstimate > gpuVramMb ? "text-amber-700 dark:text-amber-300" : "text-muted-foreground"}`}>
|
||||
{vramEstimate == null
|
||||
? "VRAM need: depends on how many layers/experts go to the GPU."
|
||||
: `VRAM need, roughly: ${formatBytes(vramEstimate * 2 ** 20)}${gpuVramMb ? ` of ${formatBytes(gpuVramMb * 2 ** 20)}` : ""}${
|
||||
engine === "vllm" ? " (vLLM reserves its GPU memory share up front)" : " (weights, KV cache, compute buffers)"
|
||||
}${gpuVramMb != null && vramEstimate > gpuVramMb ? ". Doesn't fit: lower the context, quantize the KV cache or offload fewer layers." : ""}`}
|
||||
</p>
|
||||
)}
|
||||
{engine === "llama.cpp" ? (
|
||||
<>
|
||||
<Field
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import { ExternalLinkIcon, PlayIcon, RocketIcon, SquareIcon } from "lucide-react";
|
||||
import {
|
||||
ExternalLinkIcon,
|
||||
PlayIcon,
|
||||
RocketIcon,
|
||||
SquareIcon,
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
import { DeploymentStateBadge } from "@/components/deployment-state";
|
||||
import { RequestedByBadge } from "@/components/requested-by-badge";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
|
||||
@@ -12,23 +19,45 @@ import { formatBytes } from "@/lib/format";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
import { startDeployment, stopDeployment } from "./actions";
|
||||
|
||||
type Row = Omit<DeploymentRow, "startedAt" | "readyAt" | "stoppedAt" | "createdAt"> & {
|
||||
type Row = Omit<
|
||||
DeploymentRow,
|
||||
"startedAt" | "readyAt" | "stoppedAt" | "createdAt"
|
||||
> & {
|
||||
startedAt: string | null;
|
||||
readyAt: string | null;
|
||||
stoppedAt: string | null;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
const isActive = (r: Row) => r.desiredState === "running" || r.state === "starting" || r.state === "running" || r.state === "stopping";
|
||||
const isActive = (r: Row) =>
|
||||
r.desiredState === "running" ||
|
||||
r.state === "starting" ||
|
||||
r.state === "running" ||
|
||||
r.state === "stopping";
|
||||
|
||||
/** Live list (polls every 2 s while something is starting/stopping, else every 5 s). */
|
||||
export function DeploymentList({ rows: initial }: { rows: Row[] }) {
|
||||
const [rows, setRows] = useState(initial);
|
||||
// "" = everything, "-" = created in the UI, else a token name.
|
||||
const [by, setBy] = useState("");
|
||||
const tokens = [
|
||||
...new Set(rows.map((r) => r.requestedBy).filter((x): x is string => !!x)),
|
||||
].sort();
|
||||
const shown = rows.filter(
|
||||
(r) => !by || (by === "-" ? !r.requestedBy : r.requestedBy === by),
|
||||
);
|
||||
const hostname = useHostname();
|
||||
const busy = rows.some((r) => r.state === "starting" || r.state === "stopping" || (r.desiredState === "running") !== (r.state === "running"));
|
||||
const busy = rows.some(
|
||||
(r) =>
|
||||
r.state === "starting" ||
|
||||
r.state === "stopping" ||
|
||||
(r.desiredState === "running") !== (r.state === "running"),
|
||||
);
|
||||
|
||||
async function reload() {
|
||||
const res = await fetch("/api/deployments", { cache: "no-store" }).catch(() => null);
|
||||
const res = await fetch("/api/deployments", { cache: "no-store" }).catch(
|
||||
() => null,
|
||||
);
|
||||
if (res?.ok) setRows(await res.json());
|
||||
}
|
||||
useEffect(() => {
|
||||
@@ -40,7 +69,10 @@ export function DeploymentList({ rows: initial }: { rows: Row[] }) {
|
||||
return (
|
||||
<Card className="items-center gap-3 py-10 text-center">
|
||||
<RocketIcon className="size-8 text-muted-foreground" />
|
||||
<p className="text-sm text-muted-foreground">No deployments yet. Pick a runtime and a downloaded model to start one.</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No deployments yet. Pick a runtime and a downloaded model to start
|
||||
one.
|
||||
</p>
|
||||
<Link href="/deployments/new" className="text-sm underline">
|
||||
New deployment
|
||||
</Link>
|
||||
@@ -49,59 +81,130 @@ export function DeploymentList({ rows: initial }: { rows: Row[] }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{rows.map((r) => {
|
||||
const file = r.options.modelFile ? (quantGroup(r.options.modelFile) ?? r.options.modelFile) : null;
|
||||
const loadSecs = r.readyAt && r.startedAt ? (new Date(r.readyAt).getTime() - new Date(r.startedAt).getTime()) / 1000 : null;
|
||||
return (
|
||||
<Card key={r.id} className="gap-3 px-4 py-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
<Link href={`/deployments/${r.id}`} className="truncate font-medium hover:underline">
|
||||
{r.name}
|
||||
</Link>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{r.repoId}
|
||||
{file && ` · ${file}`}
|
||||
{r.options.mmproj && " · vision"}
|
||||
{r.options.draftFile && " · MTP/draft"}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">{r.runtimeName}</span>
|
||||
<div className="flex flex-col gap-3">
|
||||
{tokens.length > 0 && (
|
||||
<label className="flex items-center gap-2 self-end text-xs text-muted-foreground">
|
||||
Requested by
|
||||
<NativeSelect
|
||||
value={by}
|
||||
onChange={(e) => setBy(e.target.value)}
|
||||
className="h-7 text-xs"
|
||||
aria-label="Requested by"
|
||||
>
|
||||
<option value="">Anyone</option>
|
||||
<option value="-">Created in Kaname</option>
|
||||
{tokens.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{t} (API)
|
||||
</option>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</label>
|
||||
)}
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{shown.map((r) => {
|
||||
const file = r.options.modelFile
|
||||
? (quantGroup(r.options.modelFile) ?? r.options.modelFile)
|
||||
: null;
|
||||
const loadSecs =
|
||||
r.readyAt && r.startedAt
|
||||
? (new Date(r.readyAt).getTime() -
|
||||
new Date(r.startedAt).getTime()) /
|
||||
1000
|
||||
: null;
|
||||
return (
|
||||
<Card key={r.id} className="gap-3 px-4 py-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
<Link
|
||||
href={`/deployments/${r.id}`}
|
||||
className="truncate font-medium hover:underline"
|
||||
>
|
||||
{r.name}
|
||||
</Link>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{r.repoId}
|
||||
{file && ` · ${file}`}
|
||||
{r.options.mmproj && " · vision"}
|
||||
{r.options.draftFile && " · MTP/draft"}
|
||||
</span>
|
||||
<span className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
|
||||
{r.runtimeName}
|
||||
<RequestedByBadge
|
||||
name={r.requestedBy}
|
||||
className="h-4 text-[10px]"
|
||||
/>
|
||||
{r.protected && (
|
||||
<span className="text-emerald-700 dark:text-emerald-300">
|
||||
protected
|
||||
</span>
|
||||
)}
|
||||
{r.startRequestedAt && (
|
||||
<span className="text-amber-700 dark:text-amber-300">
|
||||
start awaits approval
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<DeploymentStateBadge
|
||||
state={r.state}
|
||||
desiredState={r.desiredState}
|
||||
/>
|
||||
</div>
|
||||
<DeploymentStateBadge state={r.state} desiredState={r.desiredState} />
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||
<span className="tabular-nums">
|
||||
{r.state === "running" && r.stats
|
||||
? `CPU ${(r.stats.cpuPercent / 100).toFixed(1)} cores · RAM ${formatBytes(r.stats.memoryBytes)}${r.memoryMb ? ` / ${formatBytes(r.memoryMb * 2 ** 20)}` : ""}`
|
||||
: r.state === "failed"
|
||||
? (r.error?.split("\n")[0] ?? "failed")
|
||||
: `ctx ${r.options.contextSize}${r.memoryMb ? ` · ${formatBytes(r.memoryMb * 2 ** 20)} RAM` : ""}`}
|
||||
{r.state === "running" && loadSecs != null && ` · loaded in ${loadSecs.toFixed(1)} s`}
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
{r.state === "running" && webUiUrl(r, hostname) && (
|
||||
<a href={webUiUrl(r, hostname)!} target="_blank" rel="noreferrer" className={buttonVariants({ size: "xs", variant: "outline" })}>
|
||||
<ExternalLinkIcon />
|
||||
Web UI
|
||||
</a>
|
||||
)}
|
||||
{isActive(r) ? (
|
||||
<Button size="xs" variant="outline" onClick={async () => (await stopDeployment(r.id)) && reload()}>
|
||||
<SquareIcon />
|
||||
Stop
|
||||
</Button>
|
||||
) : (
|
||||
<Button size="xs" onClick={async () => (await startDeployment(r.id)) && reload()}>
|
||||
<PlayIcon />
|
||||
Start
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||
<span className="tabular-nums">
|
||||
{r.state === "running" && r.stats
|
||||
? `CPU ${(r.stats.cpuPercent / 100).toFixed(1)} cores · RAM ${formatBytes(r.stats.memoryBytes)}${r.memoryMb ? ` / ${formatBytes(r.memoryMb * 2 ** 20)}` : ""}`
|
||||
: r.state === "failed"
|
||||
? (r.error?.split("\n")[0] ?? "failed")
|
||||
: `ctx ${r.options.contextSize}${r.memoryMb ? ` · ${formatBytes(r.memoryMb * 2 ** 20)} RAM` : ""}`}
|
||||
{r.state === "running" &&
|
||||
loadSecs != null &&
|
||||
` · loaded in ${loadSecs.toFixed(1)} s`}
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
{r.state === "running" && webUiUrl(r, hostname) && (
|
||||
<a
|
||||
href={webUiUrl(r, hostname)!}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={buttonVariants({
|
||||
size: "xs",
|
||||
variant: "outline",
|
||||
})}
|
||||
>
|
||||
<ExternalLinkIcon />
|
||||
Web UI
|
||||
</a>
|
||||
)}
|
||||
{isActive(r) ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={async () =>
|
||||
(await stopDeployment(r.id)) && reload()
|
||||
}
|
||||
>
|
||||
<SquareIcon />
|
||||
Stop
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="xs"
|
||||
onClick={async () =>
|
||||
(await startDeployment(r.id)) && reload()
|
||||
}
|
||||
>
|
||||
<PlayIcon />
|
||||
Start
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,16 +1,47 @@
|
||||
import "server-only";
|
||||
import { listApiKeys } from "@/lib/api-keys";
|
||||
import { listDeployableModels } from "@/lib/deployments";
|
||||
import { applyOverrides } from "@/lib/hardware";
|
||||
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
|
||||
import { getHardwareOverrides } from "@/lib/settings";
|
||||
import type { FormHost, FormModel, FormRuntime } from "./deployment-form";
|
||||
|
||||
/** Everything the deployment form needs: runtimes, servable models, host facts, API key count. */
|
||||
export async function formData(): Promise<{ runtimes: FormRuntime[]; models: FormModel[]; host: FormHost; apiKeyCount: number }> {
|
||||
const [runtimes, models, docker, keys] = await Promise.all([listRuntimes(), listDeployableModels(), getDockerInfo(), listApiKeys()]);
|
||||
export async function formData(): Promise<{
|
||||
runtimes: FormRuntime[];
|
||||
models: FormModel[];
|
||||
host: FormHost;
|
||||
apiKeyCount: number;
|
||||
}> {
|
||||
const [runtimes, models, docker, keys, overrides] = await Promise.all([
|
||||
listRuntimes(),
|
||||
listDeployableModels(),
|
||||
getDockerInfo(),
|
||||
listApiKeys(),
|
||||
getHardwareOverrides(),
|
||||
]);
|
||||
return {
|
||||
runtimes: runtimes.map((r) => ({ id: r.id, name: r.name, engine: r.engine, image: r.image, imageState: r.imageState, env: r.env, extraArgs: r.extraArgs, accelerator: r.accelerator })),
|
||||
runtimes: runtimes.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
engine: r.engine,
|
||||
image: r.image,
|
||||
imageState: r.imageState,
|
||||
env: r.env,
|
||||
extraArgs: r.extraArgs,
|
||||
accelerator: r.accelerator,
|
||||
})),
|
||||
models,
|
||||
host: docker ? { cpus: docker.cpus, memoryBytes: docker.memoryBytes, cpuFeatures: docker.cpuFeatures, nvidia: !!docker.nvidia, gpus: docker.gpus ?? [] } : null,
|
||||
host: docker
|
||||
? {
|
||||
cpus: docker.cpus,
|
||||
memoryBytes: docker.memoryBytes,
|
||||
cpuFeatures: docker.cpuFeatures,
|
||||
nvidia: !!docker.nvidia,
|
||||
gpus: docker.gpus ?? [],
|
||||
hardwareGpus: applyOverrides(docker.hardware, overrides)?.gpus ?? [],
|
||||
}
|
||||
: null,
|
||||
apiKeyCount: keys.length,
|
||||
};
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
"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 { 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";
|
||||
@@ -21,6 +24,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);
|
||||
@@ -46,6 +50,7 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
|
||||
{job.repoId}
|
||||
</Link>
|
||||
</h1>
|
||||
<RequestedByBadge name={job.requestedBy} />
|
||||
{open && (
|
||||
<Button
|
||||
className="ml-auto"
|
||||
@@ -63,12 +68,20 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{job.state === "pending_approval" && <ApprovalBar job={job} onRemoved={() => router.push("/")} />}
|
||||
|
||||
<Card>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<JobProgress job={job} />
|
||||
<dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-1 text-sm">
|
||||
<dt className="text-muted-foreground">Created</dt>
|
||||
<dd><LocalTime value={job.createdAt} /></dd>
|
||||
{job.requestedBy && (
|
||||
<>
|
||||
<dt className="text-muted-foreground">Requested by</dt>
|
||||
<dd>{job.requestedBy} (API token)</dd>
|
||||
</>
|
||||
)}
|
||||
<dt className="text-muted-foreground">Started</dt>
|
||||
<dd>
|
||||
<LocalTime value={job.startedAt} />
|
||||
|
||||
@@ -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 { Badge } from "@/components/ui/badge";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
@@ -28,11 +29,12 @@ import {
|
||||
type Filters,
|
||||
matchesFilters,
|
||||
matchesQuery,
|
||||
PENDING_APPROVAL,
|
||||
type SearchableModel,
|
||||
} from "@/lib/search";
|
||||
import { FacetFilter } from "./facet-filter";
|
||||
|
||||
const OPEN = ["queued", "downloading", "verifying"];
|
||||
const OPEN = ["pending_approval", "queued", "downloading", "verifying"];
|
||||
|
||||
const FACET_LABEL: Record<Facet, string> = {
|
||||
author: "Author",
|
||||
@@ -40,9 +42,10 @@ 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 {
|
||||
@@ -63,6 +66,8 @@ function toSearchable(r: LibraryRow): SearchableModel {
|
||||
: r.updateAvailable
|
||||
? "update available"
|
||||
: null,
|
||||
requestedBy: r.requestedBy,
|
||||
pendingApproval: r.pendingApproval,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -197,6 +202,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
|
||||
{r.repoId}
|
||||
</Link>
|
||||
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||||
<RequestedByBadge name={r.requestedBy} className="h-4 text-[10px]" />
|
||||
{base && base !== r.repoId && <span>base {base}</span>}
|
||||
{r.architecture && <span>{r.architecture}</span>}
|
||||
{r.deployments.map((d) => (
|
||||
@@ -243,7 +249,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">
|
||||
|
||||
@@ -28,7 +28,7 @@ export function ApiKeySettings({ keys }: { keys: ApiKeyRow[] }) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>API keys</CardTitle>
|
||||
<CardTitle>Runtime API keys</CardTitle>
|
||||
<CardDescription>
|
||||
Deployments with “Require an API key” accept any of these keys as <code className="font-mono text-xs">Authorization: Bearer <key></code>.
|
||||
Changes apply when a deployment (re)starts.
|
||||
|
||||
@@ -3,7 +3,7 @@ import { listApiKeys } from "@/lib/api-keys";
|
||||
import { ApiKeySettings } from "./api-key-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "API keys · Settings" };
|
||||
export const metadata: Metadata = { title: "Runtime API keys · Settings" };
|
||||
|
||||
export default async function ApiKeySettingsPage() {
|
||||
return <ApiKeySettings keys={await listApiKeys()} />;
|
||||
|
||||
@@ -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 requested with a token, across all tokens. Downloads you start in the UI are not affected.</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 “pending approval”</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."}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
“Agent jobs at once” counts requests 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,27 @@
|
||||
import type { Metadata } from "next";
|
||||
import { listActivity } from "@/lib/agent-activity";
|
||||
import { listTokens } from "@/lib/api-tokens";
|
||||
import { listRuntimes } from "@/lib/runtimes";
|
||||
import { getGuardrails, getTuning } from "@/lib/settings";
|
||||
import { GuardrailSettings } from "./guardrail-settings";
|
||||
import { TokenSettings } from "./token-settings";
|
||||
import { TuningSettings } from "./tuning-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "API tokens · Settings" };
|
||||
|
||||
export default async function ApiTokenSettingsPage() {
|
||||
const [tokens, guardrails, tuning, runtimes] = await Promise.all([listTokens(), getGuardrails(), getTuning(), listRuntimes()]);
|
||||
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} />
|
||||
<TuningSettings initial={tuning} runtimes={runtimes.map((r) => ({ id: r.id, name: r.name, pulled: r.imageState === "present" }))} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
"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/schema";
|
||||
|
||||
/** 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's API at{" "}
|
||||
<code className="font-mono text-xs">/api/v1</code> with{" "}
|
||||
<code className="font-mono text-xs">
|
||||
Authorization: Bearer <token>
|
||||
</code>
|
||||
. No token can delete models or files, change settings, or manage
|
||||
runtimes and tokens.
|
||||
</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 “{created.name}” 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 “requested by” 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 “{token.name}
|
||||
”?
|
||||
</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> = {
|
||||
deployment: (id) => `/deployments/${id}`,
|
||||
benchmark: (id) => `/benchmarks/${id}`,
|
||||
sweep: (id) => `/benchmarks/sweeps/${id}`,
|
||||
model: (id) => `/models/${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,166 @@
|
||||
"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 { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { NativeSelect } from "@/components/ui/native-select";
|
||||
import type { ApprovalMode } from "@/lib/agent-guardrails";
|
||||
import { DEFAULT_ALLOWED_ARGS, parseFlagList, type TuningGuardrails } from "@/lib/agent-tuning";
|
||||
|
||||
const intText = (s: string) => s.replace(/\D/g, "");
|
||||
const decText = (s: string) => s.replace(/[^\d.,]/g, "");
|
||||
const num = (s: string) => Number(s.replace(",", "."));
|
||||
|
||||
/** Limits for deployments, benchmark runs and sweeps requested through the API. */
|
||||
export function TuningSettings({ initial, runtimes }: { initial: TuningGuardrails; runtimes: { id: string; name: string; pulled: boolean }[] }) {
|
||||
const router = useRouter();
|
||||
const [mode, setMode] = useState<ApprovalMode>(initial.approvalMode);
|
||||
const [maxDeps, setMaxDeps] = useState(String(initial.maxAgentDeployments));
|
||||
const [runMin, setRunMin] = useState(String(initial.maxRunMinutes));
|
||||
const [sweepMin, setSweepMin] = useState(String(initial.maxSweepMinutes));
|
||||
const [variants, setVariants] = useState(String(initial.maxSweepVariants));
|
||||
const [allowed, setAllowed] = useState<string[]>(initial.allowedRuntimeIds);
|
||||
const [llamaArgs, setLlamaArgs] = useState(initial.allowedArgs["llama.cpp"].join(" "));
|
||||
const [vllmArgs, setVllmArgs] = useState(initial.allowedArgs.vllm.join(" "));
|
||||
const [portFrom, setPortFrom] = useState(initial.hostPortRange ? String(initial.hostPortRange.from) : "");
|
||||
const [portTo, setPortTo] = useState(initial.hostPortRange ? String(initial.hostPortRange.to) : "");
|
||||
const [memGiB, setMemGiB] = useState(initial.maxMemoryMb ? String(Math.round((initial.maxMemoryMb / 1024) * 10) / 10) : "");
|
||||
const [cpus, setCpus] = useState(initial.maxCpus != null ? String(initial.maxCpus) : "");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
let argError: string | null = null;
|
||||
let llama: string[] = [];
|
||||
let vllm: string[] = [];
|
||||
try {
|
||||
llama = parseFlagList(llamaArgs);
|
||||
vllm = parseFlagList(vllmArgs);
|
||||
} catch (err) {
|
||||
argError = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (argError) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/settings/tuning", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
approvalMode: mode,
|
||||
maxAgentDeployments: num(maxDeps),
|
||||
maxRunMinutes: num(runMin),
|
||||
maxSweepMinutes: num(sweepMin),
|
||||
maxSweepVariants: num(variants),
|
||||
allowedRuntimeIds: allowed,
|
||||
allowedArgs: { "llama.cpp": llama, vllm },
|
||||
hostPortRange: portFrom && portTo ? { from: num(portFrom), to: num(portTo) } : null,
|
||||
maxMemoryMb: memGiB ? Math.round(num(memGiB) * 1024) : null,
|
||||
maxCpus: cpus ? num(cpus) : null,
|
||||
}),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return void toast.error(json.error?.message ?? `Could not save (${res.status})`);
|
||||
toast.success("Guardrails saved");
|
||||
router.refresh();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const field = (id: string, label: string, value: string, set: (v: string) => void, opts: { placeholder?: string; decimal?: boolean } = {}) => (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={id}>{label}</Label>
|
||||
<Input id={id} value={value} onChange={(e) => set((opts.decimal ? decText : intText)(e.target.value))} inputMode={opts.decimal ? "decimal" : "numeric"} placeholder={opts.placeholder} />
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-1.5">
|
||||
<ShieldCheckIcon className="size-4 text-muted-foreground" />
|
||||
Guardrails for API deployments and benchmarks
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
For tokens with the deployments and benchmarks scopes. Agents only change and benchmark deployments their own token created, never protected ones (the
|
||||
shield on a deployment's page), and can't start anything that would crowd a running protected deployment out of VRAM.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={save} className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="t-mode">Approval</Label>
|
||||
<NativeSelect id="t-mode" value={mode} onChange={(e) => setMode(e.target.value as ApprovalMode)} className="max-w-md">
|
||||
<option value="approve">Ask me: starts, runs and sweeps wait for approval</option>
|
||||
<option value="auto">Automatic: they go ahead right away</option>
|
||||
</NativeSelect>
|
||||
<p className="text-xs text-muted-foreground">Creating or editing a stopped deployment, stopping and deleting their own ones never needs approval.</p>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{field("t-deps", "Agent deployments at once", maxDeps, setMaxDeps)}
|
||||
{field("t-run", "Max minutes per run", runMin, setRunMin)}
|
||||
{field("t-sweep", "Max minutes per sweep", sweepMin, setSweepMin)}
|
||||
{field("t-var", "Max variants per sweep", variants, setVariants)}
|
||||
</div>
|
||||
<p className="-mt-2 text-xs text-muted-foreground">
|
||||
One agent run or sweep at a time, and no agent deployment starts while one is measured. Raise “deployments at once” to 2 for A/B runs.
|
||||
</p>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{field("t-mem", "Memory cap per deployment (GiB)", memGiB, setMemGiB, { placeholder: "host RAM", decimal: true })}
|
||||
{field("t-cpu", "CPU cap (cores)", cpus, setCpus, { placeholder: "all cores", decimal: true })}
|
||||
{field("t-pf", "Host ports from", portFrom, setPortFrom, { placeholder: "none" })}
|
||||
{field("t-pt", "Host ports to", portTo, setPortTo, { placeholder: "none" })}
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>Runtimes agents may use</Label>
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1.5">
|
||||
{runtimes.map((r) => (
|
||||
<label key={r.id} className="flex cursor-pointer items-center gap-2 text-sm">
|
||||
<Checkbox checked={allowed.includes(r.id)} onCheckedChange={(v) => setAllowed((cur) => (v ? [...cur, r.id] : cur.filter((x) => x !== r.id)))} />
|
||||
{r.name}
|
||||
{!r.pulled && <span className="text-xs text-muted-foreground">(not pulled)</span>}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">None ticked: every runtime with a pulled image.</p>
|
||||
</div>
|
||||
{(
|
||||
[
|
||||
["llama.cpp", llamaArgs, setLlamaArgs],
|
||||
["vllm", vllmArgs, setVllmArgs],
|
||||
] as const
|
||||
).map(([engine, value, set]) => (
|
||||
<div key={engine} className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={`t-args-${engine}`}>Extra argument flags agents may use: {engine}</Label>
|
||||
<textarea
|
||||
id={`t-args-${engine}`}
|
||||
value={value}
|
||||
onChange={(e) => set(e.target.value)}
|
||||
rows={3}
|
||||
spellCheck={false}
|
||||
className="w-full rounded-md border bg-transparent px-2.5 py-1.5 font-mono text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
|
||||
/>
|
||||
<button type="button" className="self-start text-xs text-muted-foreground underline" onClick={() => set(DEFAULT_ALLOWED_ARGS[engine].join(" "))}>
|
||||
Reset to the default list
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{argError ??
|
||||
"Anything else is refused with the offending argument named, and values can't be paths or URLs. Docker options (devices, volumes, privileges, network) never come from arguments: they belong to the runtime, which tokens can't change."}
|
||||
</p>
|
||||
<Button type="submit" className="self-start" disabled={busy || !!argError}>
|
||||
Save guardrails
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { LocalTime } from "@/components/local-time";
|
||||
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 { HardwareOverrides, HostHardware } from "@/lib/db/schema";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { formatLink, onOff } from "@/lib/hardware";
|
||||
|
||||
type GpuForm = { name: string; vramMb: string; linkCurrent: string; linkMax: string; rebar: "" | "on" | "off" };
|
||||
|
||||
const toForm = (o: NonNullable<HardwareOverrides["gpus"]>[string] | undefined): GpuForm => ({
|
||||
name: o?.name ?? "",
|
||||
vramMb: o?.vramMb != null ? String(o.vramMb) : "",
|
||||
linkCurrent: o?.linkCurrent ?? "",
|
||||
linkMax: o?.linkMax ?? "",
|
||||
rebar: o?.rebar == null ? "" : o.rebar ? "on" : "off",
|
||||
});
|
||||
|
||||
const STORAGE_KIND: Record<string, string> = { nvme: "NVMe", ssd: "SSD", hdd: "HDD", virtual: "virtual disk" };
|
||||
|
||||
/** What Kaname detected on the Docker host, with manual values for what it can't see. */
|
||||
export function HardwareSettings({
|
||||
detected,
|
||||
overrides,
|
||||
summary,
|
||||
dockerConnected,
|
||||
}: {
|
||||
detected: HostHardware | null;
|
||||
overrides: HardwareOverrides;
|
||||
summary: string[];
|
||||
dockerConnected: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [gpus, setGpus] = useState<Record<string, GpuForm>>(() => Object.fromEntries((detected?.gpus ?? []).map((g) => [g.pciAddress, toForm(overrides.gpus?.[g.pciAddress])])));
|
||||
const [p2p, setP2p] = useState(overrides.p2p ?? "");
|
||||
const [storage, setStorage] = useState(overrides.storage ?? "");
|
||||
const [hypervisor, setHypervisor] = useState(overrides.hypervisor ?? "");
|
||||
const [passthrough, setPassthrough] = useState(overrides.gpuPassthrough == null ? "" : overrides.gpuPassthrough ? "yes" : "no");
|
||||
const [gpuDriver, setGpuDriver] = useState(overrides.gpuDriver ?? "");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const setGpu = (addr: string, patch: Partial<GpuForm>) => setGpus((g) => ({ ...g, [addr]: { ...g[addr], ...patch } }));
|
||||
|
||||
async function save() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const body: HardwareOverrides = {
|
||||
gpus: Object.fromEntries(
|
||||
Object.entries(gpus).map(([addr, g]) => [
|
||||
addr,
|
||||
{
|
||||
name: g.name || undefined,
|
||||
vramMb: g.vramMb ? Number(g.vramMb) : undefined,
|
||||
linkCurrent: g.linkCurrent || undefined,
|
||||
linkMax: g.linkMax || undefined,
|
||||
rebar: g.rebar ? g.rebar === "on" : undefined,
|
||||
},
|
||||
]),
|
||||
),
|
||||
p2p: (p2p || undefined) as HardwareOverrides["p2p"],
|
||||
storage: storage || undefined,
|
||||
hypervisor: hypervisor || undefined,
|
||||
gpuPassthrough: passthrough ? passthrough === "yes" : undefined,
|
||||
gpuDriver: gpuDriver || undefined,
|
||||
};
|
||||
const res = await fetch("/api/settings/hardware", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
const out = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return void toast.error(out.error?.message ?? `Could not save (${res.status})`);
|
||||
toast.success("Saved; new benchmark runs use these values");
|
||||
router.refresh();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!detected) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Hardware</CardTitle>
|
||||
<CardDescription>
|
||||
{dockerConnected ? "The worker hasn't reported its hardware yet (it checks every few minutes)." : "Hardware is detected by the worker once Docker is connected (Settings → Runtimes)."}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const v = detected.virtualization;
|
||||
return (
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void save();
|
||||
}}
|
||||
>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>GPUs</CardTitle>
|
||||
<CardDescription>
|
||||
Recorded with every benchmark run. Detected from sysfs as the worker sees it; in a VM the PCIe link is the one the VM sees, which may not be the physical
|
||||
slot. Fill in a field to replace the detected value (empty = detected).
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
{detected.gpus.length === 0 && <p className="text-sm text-muted-foreground">No NVIDIA, Intel or AMD GPU found.</p>}
|
||||
{detected.gpus.map((g) => {
|
||||
const f = gpus[g.pciAddress];
|
||||
return (
|
||||
<div key={g.pciAddress} className="flex flex-col gap-3 rounded-lg border p-3">
|
||||
<div className="text-sm">
|
||||
<span className="font-medium">{g.name ?? "Unknown GPU"}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{" "}
|
||||
· {g.pciAddress} · {g.driver ?? "no driver"}
|
||||
{g.driverVersion ? ` ${g.driverVersion}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<Field id={`n-${g.pciAddress}`} label="Name" detected={g.name} value={f.name} onChange={(x) => setGpu(g.pciAddress, { name: x })} />
|
||||
<Field
|
||||
id={`v-${g.pciAddress}`}
|
||||
label="VRAM (MiB)"
|
||||
detected={g.vramMb != null ? String(g.vramMb) : null}
|
||||
value={f.vramMb}
|
||||
onChange={(x) => setGpu(g.pciAddress, { vramMb: x.replace(/\D/g, "") })}
|
||||
/>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={`r-${g.pciAddress}`}>ReBAR</Label>
|
||||
<NativeSelect id={`r-${g.pciAddress}`} value={f.rebar} onChange={(e) => setGpu(g.pciAddress, { rebar: e.target.value as GpuForm["rebar"] })}>
|
||||
<option value="">Detected: {onOff(g.rebar)}</option>
|
||||
<option value="on">on</option>
|
||||
<option value="off">off</option>
|
||||
</NativeSelect>
|
||||
<p className="text-xs text-muted-foreground">Largest BAR {g.barMb != null ? formatBytes(g.barMb * 2 ** 20) : "unknown"}</p>
|
||||
</div>
|
||||
<Field
|
||||
id={`lc-${g.pciAddress}`}
|
||||
label="PCIe link (current)"
|
||||
detected={formatLink(g.linkCurrent)}
|
||||
value={f.linkCurrent}
|
||||
placeholderHint="e.g. Gen4 x8"
|
||||
onChange={(x) => setGpu(g.pciAddress, { linkCurrent: x })}
|
||||
/>
|
||||
<Field
|
||||
id={`lm-${g.pciAddress}`}
|
||||
label="PCIe link (maximum)"
|
||||
detected={formatLink(g.linkMax)}
|
||||
value={f.linkMax}
|
||||
placeholderHint="e.g. Gen5 x16"
|
||||
onChange={(x) => setGpu(g.pciAddress, { linkMax: x })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{detected.gpus.length > 1 && (
|
||||
<div className="flex max-w-xs flex-col gap-1.5">
|
||||
<Label htmlFor="hw-p2p">Peer-to-peer between GPUs</Label>
|
||||
<NativeSelect id="hw-p2p" value={p2p} onChange={(e) => setP2p(e.target.value as typeof p2p)}>
|
||||
<option value="">Detected: {detected.p2p ?? "unknown"}</option>
|
||||
<option value="on">on</option>
|
||||
<option value="partial">partial</option>
|
||||
<option value="off">off</option>
|
||||
</NativeSelect>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>System</CardTitle>
|
||||
<CardDescription>Part of the system summary recorded with each run, passed to BetterBench and shown in the launch80 preview.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field
|
||||
id="hw-storage"
|
||||
label="Models disk"
|
||||
detected={detected.storage ? [detected.storage.model, detected.storage.kind && STORAGE_KIND[detected.storage.kind]].filter(Boolean).join(", ") : null}
|
||||
value={storage}
|
||||
onChange={setStorage}
|
||||
/>
|
||||
<Field
|
||||
id="hw-virt"
|
||||
label="Virtualization"
|
||||
detected={v.vm == null ? null : v.vm ? `VM${v.hypervisor ? ` (${v.hypervisor})` : ""}` : "bare metal"}
|
||||
value={hypervisor}
|
||||
placeholderHint="e.g. Proxmox VE 9 (KVM)"
|
||||
onChange={setHypervisor}
|
||||
/>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="hw-pt">GPU passthrough</Label>
|
||||
<NativeSelect id="hw-pt" value={passthrough} onChange={(e) => setPassthrough(e.target.value)}>
|
||||
<option value="">Detected: {v.vm ? (detected.gpus.length ? "yes" : "no") : v.vm === false ? "no (bare metal)" : "unknown"}</option>
|
||||
<option value="yes">yes</option>
|
||||
<option value="no">no</option>
|
||||
</NativeSelect>
|
||||
</div>
|
||||
<Field
|
||||
id="hw-driver"
|
||||
label="GPU driver"
|
||||
detected={[...new Set(detected.gpus.map((g) => [g.driver, g.driverVersion].filter(Boolean).join(" ")))].join(", ") || null}
|
||||
value={gpuDriver}
|
||||
placeholderHint="e.g. xe, compute runtime 25.35"
|
||||
onChange={setGpuDriver}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Button type="submit" disabled={busy}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>System summary</CardTitle>
|
||||
<CardDescription>
|
||||
Exactly what runs record and publish (after saving). Never the hostname, IP addresses, users or paths. Checked <LocalTime value={detected.checkedAt} />.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ul className="flex flex-col gap-1 text-sm">
|
||||
{summary.map((l) => (
|
||||
<li key={l}>{l}</li>
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({
|
||||
id,
|
||||
label,
|
||||
detected,
|
||||
value,
|
||||
onChange,
|
||||
placeholderHint,
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
detected: string | null;
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
placeholderHint?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor={id}>{label}</Label>
|
||||
<Input id={id} value={value} onChange={(e) => onChange(e.target.value)} placeholder={detected ?? placeholderHint ?? "unknown"} maxLength={120} />
|
||||
<p className="text-xs text-muted-foreground">Detected: {detected ?? "unknown"}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { Metadata } from "next";
|
||||
import { kanameVersion } from "@/lib/benchmark-snapshot";
|
||||
import { applyOverrides, systemSummary, systemSummaryLines } from "@/lib/hardware";
|
||||
import { getDockerInfo } from "@/lib/runtimes";
|
||||
import { getHardwareOverrides } from "@/lib/settings";
|
||||
import { HardwareSettings } from "./hardware-settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata: Metadata = { title: "Hardware · Settings" };
|
||||
|
||||
export default async function HardwareSettingsPage() {
|
||||
const [docker, overrides] = await Promise.all([getDockerInfo(), getHardwareOverrides()]);
|
||||
const hardware = docker?.hardware ?? null;
|
||||
const effective = applyOverrides(hardware, overrides);
|
||||
return (
|
||||
<HardwareSettings
|
||||
detected={hardware}
|
||||
overrides={overrides}
|
||||
summary={systemSummaryLines(systemSummary(effective, docker?.os ?? null, kanameVersion()))}
|
||||
dockerConnected={!!docker?.connected}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { BoxesIcon, DownloadIcon, KeyRoundIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { BotIcon, BoxesIcon, CpuIcon, DownloadIcon, KeyRoundIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { SettingsNav } from "./settings-nav";
|
||||
|
||||
const SECTIONS = [
|
||||
@@ -6,7 +6,9 @@ const SECTIONS = [
|
||||
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
|
||||
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
|
||||
{ href: "/settings/runtimes", label: "Runtimes", icon: <BoxesIcon className="size-4" /> },
|
||||
{ href: "/settings/api-keys", label: "API keys", icon: <KeyRoundIcon className="size-4" /> },
|
||||
{ href: "/settings/hardware", label: "Hardware", icon: <CpuIcon className="size-4" /> },
|
||||
{ href: "/settings/api-keys", label: "Runtime API keys", icon: <KeyRoundIcon className="size-4" /> },
|
||||
{ href: "/settings/api-tokens", label: "API tokens", icon: <BotIcon className="size-4" /> },
|
||||
];
|
||||
|
||||
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
|
||||
|
||||
@@ -37,6 +37,7 @@ export function RuntimeForm({
|
||||
const [accelerator, setAccelerator] = useState<RuntimeAccelerator>(initial.accelerator ?? "cpu");
|
||||
const [image, setImage] = useState(initial.image);
|
||||
const [description, setDescription] = useState(initial.description ?? "");
|
||||
const [engineName, setEngineName] = useState(initial.engineName ?? "");
|
||||
const [envText, setEnvText] = useState(formatEnvLines(initial.env ?? {}));
|
||||
const [argRows, setArgRows] = useState(() => argsToRows(initial.extraArgs ?? []));
|
||||
const [devicesText, setDevicesText] = useState((initial.devices ?? []).join(", "));
|
||||
@@ -55,6 +56,7 @@ export function RuntimeForm({
|
||||
accelerator,
|
||||
image,
|
||||
description,
|
||||
engineName,
|
||||
env: parseEnvLines(envText),
|
||||
extraArgs: rowsToArgs(argRows),
|
||||
devices: devicesText.split(/[,\s]+/),
|
||||
@@ -151,6 +153,12 @@ export function RuntimeForm({
|
||||
<Input id="rt-desc" value={description} onChange={(e) => setDescription(e.target.value)} maxLength={2000} />
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="rt-engine-name">Engine name</Label>
|
||||
<Input id="rt-engine-name" value={engineName} onChange={(e) => setEngineName(e.target.value)} maxLength={60} placeholder={engine} spellCheck={false} />
|
||||
<p className="text-xs text-muted-foreground">For forks: recorded with every benchmark next to the version the server reports, e.g. vllm-radiance.</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="rt-env">Environment</Label>
|
||||
<textarea
|
||||
|
||||
@@ -66,6 +66,7 @@ const toInput = (r: Runtime): RuntimeInput => ({
|
||||
accelerator: r.accelerator,
|
||||
image: r.image,
|
||||
description: r.description,
|
||||
engineName: r.engineName,
|
||||
env: r.env,
|
||||
extraArgs: r.extraArgs,
|
||||
devices: r.devices,
|
||||
@@ -279,6 +280,12 @@ function ImageState({ r }: { r: Runtime }) {
|
||||
· built <LocalTime value={r.imageCreated} />
|
||||
</span>
|
||||
)}
|
||||
{r.imageDigest && (
|
||||
<span className="font-mono text-muted-foreground" title={r.imageDigest}>
|
||||
{" "}
|
||||
· {r.imageDigest.slice(0, 19)}…
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { approveBenchmark, BenchmarkError } from "@/lib/benchmarks";
|
||||
|
||||
/** Let a benchmark run an API token asked for. */
|
||||
export const POST = withAuth<RouteContext<"/api/benchmarks/[id]/approve">>(async (_req, { params }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
await approveBenchmark(id);
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (err) {
|
||||
if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { BenchmarkError, rejectBenchmark } from "@/lib/benchmarks";
|
||||
|
||||
/** Turn down a benchmark run an API token asked for. */
|
||||
export const POST = withAuth<RouteContext<"/api/benchmarks/[id]/reject">>(async (_req, { params }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
await rejectBenchmark(id);
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (err) {
|
||||
if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { BenchmarkError, deleteBenchmark, getBenchmark, updateBenchmarkLabel } from "@/lib/benchmarks";
|
||||
import { BenchmarkError, DESCRIPTION_MAX, deleteBenchmark, getBenchmark, updateBenchmark } from "@/lib/benchmarks";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -11,12 +11,12 @@ export const GET = withAuth<RouteContext<"/api/benchmarks/[id]">>(async (_req, {
|
||||
return run ? NextResponse.json(run) : apiError(404, "not_found", "Benchmark not found.");
|
||||
});
|
||||
|
||||
const Patch = z.object({ label: z.string().max(120).nullable() });
|
||||
const Patch = z.object({ label: z.string().max(120).nullable().optional(), description: z.string().max(DESCRIPTION_MAX).nullable().optional() });
|
||||
|
||||
/** Rename (label) a run. */
|
||||
/** Rename (label) a run or change its description. */
|
||||
export const PATCH = withAuth<RouteContext<"/api/benchmarks/[id]">>(async (req, { params }) => {
|
||||
try {
|
||||
await updateBenchmarkLabel((await params).id, Patch.parse(await req.json()).label);
|
||||
await updateBenchmark((await params).id, Patch.parse(await req.json()));
|
||||
return new NextResponse(null, { status: 204 });
|
||||
} catch (err) {
|
||||
if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { DeploymentError, setDesiredState } from "@/lib/deployments";
|
||||
|
||||
/** Let the start of a deployment an API token asked for. */
|
||||
export const POST = withAuth<RouteContext<"/api/deployments/[id]/approve">>(async (_req, { params }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
await setDesiredState(id, "running");
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (err) {
|
||||
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { DeploymentError, setProtected } from "@/lib/deployments";
|
||||
|
||||
const Body = z.object({ protected: z.boolean() });
|
||||
|
||||
/** Protect a deployment from agents (or lift it). */
|
||||
export const POST = withAuth<RouteContext<"/api/deployments/[id]/protect">>(async (req, { params }) => {
|
||||
try {
|
||||
const { protected: value } = Body.parse(await req.json());
|
||||
await setProtected((await params).id, value);
|
||||
return NextResponse.json({ protected: value });
|
||||
} catch (err) {
|
||||
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { DeploymentError, rejectStart } from "@/lib/deployments";
|
||||
|
||||
/** Turn down the start of a deployment an API token asked for. */
|
||||
export const POST = withAuth<RouteContext<"/api/deployments/[id]/reject">>(async (_req, { params }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
await rejectStart(id);
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (err) {
|
||||
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { getHardwareOverrides, saveHardwareOverrides, SettingsError } from "@/lib/settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Manual hardware values for benchmark records (Settings → Hardware). */
|
||||
export const GET = withAuth(async () => NextResponse.json(await getHardwareOverrides()));
|
||||
|
||||
export const PUT = withAuth(async (req) => {
|
||||
try {
|
||||
return NextResponse.json(await saveHardwareOverrides(await req.json()));
|
||||
} catch (err) {
|
||||
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
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 { getTuning, saveTuning, SettingsError } from "@/lib/settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Guardrails for deployments and benchmarks requested through the API. */
|
||||
export const GET = withAuth(async () => NextResponse.json(await getTuning()));
|
||||
|
||||
const Body = z
|
||||
.object({
|
||||
approvalMode: z.enum(APPROVAL_MODES),
|
||||
maxAgentDeployments: z.number().int(),
|
||||
maxRunMinutes: z.number().int(),
|
||||
maxSweepMinutes: z.number().int(),
|
||||
maxSweepVariants: z.number().int(),
|
||||
allowedRuntimeIds: z.array(z.string().max(64)).max(100),
|
||||
allowedArgs: z.object({ "llama.cpp": z.array(z.string().max(80)).max(500), vllm: z.array(z.string().max(80)).max(500) }),
|
||||
hostPortRange: z.object({ from: z.number().int(), to: z.number().int() }).nullable(),
|
||||
maxMemoryMb: z.number().nullable(),
|
||||
maxCpus: z.number().nullable(),
|
||||
})
|
||||
.partial();
|
||||
|
||||
export const PUT = withAuth(async (req) => {
|
||||
try {
|
||||
return NextResponse.json(await saveTuning(Body.parse(await req.json())));
|
||||
} catch (err) {
|
||||
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { decideSweep, SweepRequestError } from "@/lib/sweeps";
|
||||
|
||||
/** Let a sweep an API token asked for. */
|
||||
export const POST = withAuth<RouteContext<"/api/sweeps/[id]/approve">>(async (_req, { params }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
await decideSweep(id, true);
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (err) {
|
||||
if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withAuth } from "@/lib/api-auth";
|
||||
import { apiError, handleApiError } from "@/lib/api-errors";
|
||||
import { decideSweep, SweepRequestError } from "@/lib/sweeps";
|
||||
|
||||
/** Turn down a sweep an API token asked for. */
|
||||
export const POST = withAuth<RouteContext<"/api/sweeps/[id]/reject">>(async (_req, { params }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
await decideSweep(id, false);
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (err) {
|
||||
if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message);
|
||||
return handleApiError(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { act } from "@/lib/agent-activity";
|
||||
import { ownRun } from "@/lib/agent-runs";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Json } from "@/lib/api-v1";
|
||||
import { cancelBenchmark } from "@/lib/benchmarks";
|
||||
|
||||
/** Cancel a run this token started. */
|
||||
export const POST = withToken<RouteContext<"/api/v1/benchmarks/[id]/cancel">>("benchmarks:run", async (_req, { params, token }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
await act(token, "benchmark.cancel", { type: "benchmark", id }, async () => {
|
||||
await ownRun(token, id);
|
||||
await cancelBenchmark(id);
|
||||
return { id };
|
||||
});
|
||||
return v1Json({ id, cancelled: true });
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { runSettled, runView } from "@/lib/agent-runs";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Error, v1Json } from "@/lib/api-v1";
|
||||
import { getBenchmark } from "@/lib/benchmarks";
|
||||
import { parseWait, waitFor } from "@/lib/wait";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* A run's state and compact result (headline numbers, setup, resources). ?wait=<s> (max 900) blocks
|
||||
* until it is finished or waits for approval; ?full=1 adds BetterBench's full summary.
|
||||
*/
|
||||
export const GET = withToken<RouteContext<"/api/v1/benchmarks/[id]">>("benchmarks:read", async (req, { params, token }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
const q = new URL(req.url).searchParams;
|
||||
const { value: run, waitedS, timedOut } = await waitFor(() => getBenchmark(id), (r) => !r || runSettled(r.state), parseWait(q), { signal: req.signal });
|
||||
if (!run) return v1Error(404, "not_found", "No benchmark run with this id.");
|
||||
return v1Json({ ...runView(run, token, q.get("full") === "1"), ...(waitedS ? { waitedSeconds: waitedS, timedOut } : {}) });
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { compareRuns } from "@/lib/agent-runs";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Error, v1Json } from "@/lib/api-v1";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** ?ids=a,b,c (2–16 runs): headline numbers side by side, the setup values that differ, and the shared ones. */
|
||||
export const GET = withToken("benchmarks:read", async (req) => {
|
||||
try {
|
||||
const ids = (new URL(req.url).searchParams.get("ids") ?? "").split(",").map((s) => s.trim()).filter(Boolean).slice(0, 16);
|
||||
if (ids.length < 2) return v1Error(400, "invalid_request", "Pass at least two run ids: ?ids=<id>,<id>");
|
||||
return v1Json(await compareRuns(ids));
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { act } from "@/lib/agent-activity";
|
||||
import { AgentRunBody, listRunsFor, requestRun, runView } from "@/lib/agent-runs";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Json } from "@/lib/api-v1";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Recent runs, newest first: ?deployment=<id>, ?requested_by=<token name>, ?limit=N (max 50). */
|
||||
export const GET = withToken("benchmarks:read", async (req, { token }) => {
|
||||
try {
|
||||
const q = new URL(req.url).searchParams;
|
||||
const limit = Math.min(50, Math.max(1, Number(q.get("limit")) || 20));
|
||||
const runs = await listRunsFor({ deploymentId: q.get("deployment") ?? undefined, requestedBy: q.get("requested_by") ?? undefined, limit });
|
||||
return v1Json({ count: runs.length, runs: runs.map((r) => runView(r, token)) });
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
|
||||
/** Queue a speed run (kind "run"), a paired A/B ("ab") or the quality eval ("eval") on the token's own running deployment(s). */
|
||||
export const POST = withToken("benchmarks:run", async (req, { token }) => {
|
||||
try {
|
||||
const body = AgentRunBody.parse(await req.json());
|
||||
const r = await act(token, `benchmark.${body.kind}`, { type: "benchmark" }, () => requestRun(token, body));
|
||||
return v1Json(
|
||||
{
|
||||
...r,
|
||||
message:
|
||||
r.state === "pending_approval"
|
||||
? "Requested; it waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop."
|
||||
: `Queued; GET /api/v1/benchmarks/${r.id}?wait=900 for the result (stopped after ${r.timeLimitMinutes} min).`,
|
||||
},
|
||||
201,
|
||||
);
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { act } from "@/lib/agent-activity";
|
||||
import { AgentDeploymentPatch, deleteAgentDeployment, deploymentSettled, deploymentView, updateAgentDeployment } from "@/lib/agent-deployments";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Error, v1Json } from "@/lib/api-v1";
|
||||
import { getDeployment, listDeploymentLogs } from "@/lib/deployments";
|
||||
import { parseWait, waitFor } from "@/lib/wait";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const MAX_LOG = 200;
|
||||
|
||||
/**
|
||||
* State, endpoint, options, live usage. ?wait=<s> (max 900) blocks until it is settled (running,
|
||||
* stopped, failed or waiting for approval); ?log=N adds the last N log lines.
|
||||
*/
|
||||
export const GET = withToken<RouteContext<"/api/v1/deployments/[id]">>("deployments:read", async (req, { params, token }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
const q = new URL(req.url).searchParams;
|
||||
const { value: d, waitedS, timedOut } = await waitFor(
|
||||
() => getDeployment(id),
|
||||
(x) => !x || deploymentSettled(x) || !!x.startRequestedAt,
|
||||
parseWait(q),
|
||||
{ signal: req.signal },
|
||||
);
|
||||
if (!d) return v1Error(404, "not_found", "No deployment with this id.");
|
||||
const n = Math.min(MAX_LOG, Math.max(0, Number(q.get("log")) || 0));
|
||||
const log = n > 0 ? (await listDeploymentLogs(id, 0, n)).map((l) => `${new Date(l.ts).toISOString()} [${l.stream}] ${l.line}`) : undefined;
|
||||
return v1Json({ ...deploymentView(d, token), ...(waitedS ? { waitedSeconds: waitedS, timedOut } : {}), ...(log ? { log } : {}) });
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
|
||||
/** Change an own, stopped deployment (fields left out stay). Returns the new command and estimates. */
|
||||
export const PATCH = withToken<RouteContext<"/api/v1/deployments/[id]">>("deployments:write", async (req, { params, token }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
const patch = AgentDeploymentPatch.parse(await req.json());
|
||||
const preview = await act(token, "deployment.update", { type: "deployment", id }, async () => ({ id, ...(await updateAgentDeployment(token, id, patch)) }));
|
||||
return v1Json({ ...preview, deployment: deploymentView((await getDeployment(id))!, token) });
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
|
||||
/** Delete an own deployment (the container is stopped and removed). */
|
||||
export const DELETE = withToken<RouteContext<"/api/v1/deployments/[id]">>("deployments:write", async (_req, { params, token }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
await act(token, "deployment.delete", { type: "deployment", id }, async () => {
|
||||
await deleteAgentDeployment(token, id);
|
||||
return { id };
|
||||
});
|
||||
return v1Json({ id, deleted: true });
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import { act } from "@/lib/agent-activity";
|
||||
import { startAgentDeployment } from "@/lib/agent-deployments";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Json } from "@/lib/api-v1";
|
||||
|
||||
/** Start an own deployment; with approval mode "approve" it waits for the user. */
|
||||
export const POST = withToken<RouteContext<"/api/v1/deployments/[id]/start">>("deployments:write", async (_req, { params, token }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
const r = await act(token, "deployment.start", { type: "deployment", id }, async () => ({ id, ...(await startAgentDeployment(token, id)) }));
|
||||
return v1Json({
|
||||
...r,
|
||||
message:
|
||||
r.state === "pending_approval"
|
||||
? "The start waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop."
|
||||
: `Starting; GET /api/v1/deployments/${id}?wait=600 until it is running.`,
|
||||
});
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { act } from "@/lib/agent-activity";
|
||||
import { stopAgentDeployment } from "@/lib/agent-deployments";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Json } from "@/lib/api-v1";
|
||||
|
||||
/** Stop an own deployment (no approval needed). */
|
||||
export const POST = withToken<RouteContext<"/api/v1/deployments/[id]/stop">>("deployments:write", async (_req, { params, token }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
await act(token, "deployment.stop", { type: "deployment", id }, async () => {
|
||||
await stopAgentDeployment(token, id);
|
||||
return { id };
|
||||
});
|
||||
return v1Json({ id, state: "stopping", message: `Stopping; GET /api/v1/deployments/${id}?wait=60 if you need to know it is stopped.` });
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { act } from "@/lib/agent-activity";
|
||||
import { AgentDeploymentBody, createAgentDeployment, deploymentView } from "@/lib/agent-deployments";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Json } from "@/lib/api-v1";
|
||||
import { listDeployments } from "@/lib/deployments";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** All deployments (agents may only change their own: "mine": true). ?mine=1 lists only those. */
|
||||
export const GET = withToken("deployments:read", async (req, { token }) => {
|
||||
try {
|
||||
const mine = new URL(req.url).searchParams.get("mine") === "1";
|
||||
const rows = (await listDeployments()).filter((d) => !d.sweepId && (!mine || d.requestedByTokenId === token.id));
|
||||
return v1Json({ count: rows.length, deployments: rows.map((d) => deploymentView(d, token)) });
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Create a deployment (and start it unless start: false). dryRun: true only validates and returns the
|
||||
* command and estimates. Same validation and command as the UI, plus the agent guardrails.
|
||||
*/
|
||||
export const POST = withToken("deployments:write", async (req, { token }) => {
|
||||
try {
|
||||
const body = AgentDeploymentBody.parse(await req.json());
|
||||
if (body.dryRun) return v1Json(await createAgentDeployment(token, body));
|
||||
const r = await act(token, "deployment.create", { type: "deployment" }, () => createAgentDeployment(token, body));
|
||||
return v1Json(
|
||||
{
|
||||
...r,
|
||||
message:
|
||||
r.state === "pending_approval"
|
||||
? "Created; the start waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop."
|
||||
: r.state === "starting"
|
||||
? `Created and starting; GET /api/v1/deployments/${r.id}?wait=600 until it is running.`
|
||||
: "Created (stopped).",
|
||||
},
|
||||
201,
|
||||
);
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
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 download slot; GET with ?wait=900 instead of polling.",
|
||||
downloading: "Downloading; GET with ?wait=900 instead of polling.",
|
||||
verifying: "Checking the downloaded files.",
|
||||
completed: "Done.",
|
||||
failed: "Failed; see error. Tell the user; retrying the same request returns this job.",
|
||||
cancelled: "Cancelled or rejected by the user. 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"]);
|
||||
|
||||
/**
|
||||
* 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;
|
||||
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,
|
||||
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: NEXT[job.state] ?? null,
|
||||
...(waitedS ? { waitedSeconds: waitedS, timedOut } : {}),
|
||||
...(log ? { log } : {}),
|
||||
});
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
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";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** One model: status, pinned commit, selected files 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] = await listModelJobs(model.id, 1);
|
||||
return v1Json({
|
||||
id: model.id,
|
||||
repoId: model.repoId,
|
||||
status: model.status,
|
||||
trackedRevision: model.trackedRevision,
|
||||
pinnedSha: model.pinnedSha,
|
||||
requestedBy: model.requestedBy,
|
||||
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, state: job.state, requestedBy: job.requestedBy } : null,
|
||||
createdAt: model.createdAt.toISOString(),
|
||||
downloadedAt: model.downloadedAt?.toISOString() ?? null,
|
||||
});
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
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,
|
||||
status: r.status,
|
||||
pendingApproval: r.pendingApproval,
|
||||
pinnedSha: 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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { size, v1Json } from "@/lib/api-v1";
|
||||
import { getGuardrails, getTuning } 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, t] = await Promise.all([getGuardrails(), getTuning()]);
|
||||
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,
|
||||
},
|
||||
deploymentGuardrails: {
|
||||
approvalMode: t.approvalMode,
|
||||
maxAgentDeployments: t.maxAgentDeployments,
|
||||
oneRunAtATime: true,
|
||||
maxRunMinutes: t.maxRunMinutes,
|
||||
maxSweepMinutes: t.maxSweepMinutes,
|
||||
maxSweepVariants: t.maxSweepVariants,
|
||||
allowedRuntimeIds: t.allowedRuntimeIds,
|
||||
hostPortRange: t.hostPortRange,
|
||||
maxMemoryMb: t.maxMemoryMb,
|
||||
maxCpus: t.maxCpus,
|
||||
ownDeploymentsOnly: true,
|
||||
protectedDeploymentsUntouchable: true,
|
||||
},
|
||||
endpoints: [
|
||||
"GET /api/v1/hub/lookup?repo=org/name[&revision=main][&files=all]",
|
||||
"GET /api/v1/models[?q=&author=&family=&quant=&tag=&status=&requested_by=]",
|
||||
"GET /api/v1/models/{id}",
|
||||
"POST /api/v1/downloads {repoId, sha, quant | include[], tags?, revision?}",
|
||||
"GET /api/v1/jobs/{id}[?wait=900][&log=50]",
|
||||
"GET /api/v1/disk",
|
||||
"GET /api/v1/runtimes",
|
||||
"GET /api/v1/deployments[?mine=1]",
|
||||
"POST /api/v1/deployments {runtimeId, modelId, options, cpus?, memoryMb?, hostPort?, name?, start?, dryRun?}",
|
||||
"GET /api/v1/deployments/{id}[?wait=600][&log=50]",
|
||||
"PATCH /api/v1/deployments/{id} {options?, cpus?, memoryMb?, hostPort?, name?}",
|
||||
"POST /api/v1/deployments/{id}/start | /stop",
|
||||
"DELETE /api/v1/deployments/{id}",
|
||||
"GET /api/v1/benchmarks[?deployment=&requested_by=&limit=]",
|
||||
"POST /api/v1/benchmarks {kind: run|ab, deploymentId, deploymentBId?, quick?, passes?, phases?, label?, description?}",
|
||||
"GET /api/v1/benchmarks/{id}[?wait=900][&full=1]",
|
||||
"POST /api/v1/benchmarks/{id}/cancel",
|
||||
"GET /api/v1/benchmarks/compare?ids=a,b",
|
||||
"POST /api/v1/sweeps {baseDeploymentId, params: [{key, values}], quick?, passes?, phases?, label?}",
|
||||
"GET /api/v1/sweeps/{id}[?wait=900]",
|
||||
"POST /api/v1/sweeps/{id}/cancel",
|
||||
],
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Json } from "@/lib/api-v1";
|
||||
import { effectiveHardware } from "@/lib/benchmark-snapshot";
|
||||
import { listRuntimes } from "@/lib/runtimes";
|
||||
import { getTuning } from "@/lib/settings";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Runtimes with a pulled image, what they serve, whether agents may use them; plus the host's GPUs. */
|
||||
export const GET = withToken("deployments:read", async () => {
|
||||
try {
|
||||
const [rts, g, { hardware }] = await Promise.all([listRuntimes(), getTuning(), effectiveHardware()]);
|
||||
return v1Json({
|
||||
runtimes: rts
|
||||
.filter((r) => r.imageState === "present")
|
||||
.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
engine: r.engine,
|
||||
engineName: r.engineName ?? r.engine,
|
||||
accelerator: r.accelerator,
|
||||
image: r.image,
|
||||
digest: r.imageDigest,
|
||||
serves: r.engine === "llama.cpp" ? "GGUF files (options.modelFile = the .gguf path)" : 'safetensors repos (options.modelFile = "")',
|
||||
allowed: g.allowedRuntimeIds.length === 0 || g.allowedRuntimeIds.includes(r.id),
|
||||
allowedExtraArgs: g.allowedArgs[r.engine],
|
||||
})),
|
||||
gpus: (hardware?.gpus ?? []).map((x) => ({ vendor: x.vendor, name: x.name, vramMb: x.vramMb })),
|
||||
});
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { act } from "@/lib/agent-activity";
|
||||
import { ownSweep } from "@/lib/agent-runs";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Json } from "@/lib/api-v1";
|
||||
import { cancelSweep } from "@/lib/sweeps";
|
||||
|
||||
/** Cancel a sweep this token started (its current variant's deployment is removed). */
|
||||
export const POST = withToken<RouteContext<"/api/v1/sweeps/[id]/cancel">>("benchmarks:run", async (_req, { params, token }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
await act(token, "sweep.cancel", { type: "sweep", id }, async () => {
|
||||
await ownSweep(token, id);
|
||||
await cancelSweep(id);
|
||||
return { id };
|
||||
});
|
||||
return v1Json({ id, cancelled: true });
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { runSettled, sweepView } from "@/lib/agent-runs";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Error, v1Json } from "@/lib/api-v1";
|
||||
import { getSweep } from "@/lib/sweeps";
|
||||
import { parseWait, waitFor } from "@/lib/wait";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** A sweep with each variant's headline numbers and setup. ?wait=<s> (max 900) blocks until it is finished or waits for approval. */
|
||||
export const GET = withToken<RouteContext<"/api/v1/sweeps/[id]">>("benchmarks:read", async (req, { params, token }) => {
|
||||
try {
|
||||
const id = (await params).id;
|
||||
const { value, waitedS, timedOut } = await waitFor(() => getSweep(id), (s) => !s || runSettled(s.sweep.state), parseWait(new URL(req.url).searchParams), { signal: req.signal });
|
||||
if (!value) return v1Error(404, "not_found", "No sweep with this id.");
|
||||
return v1Json({ ...sweepView(value, token), ...(waitedS ? { waitedSeconds: waitedS, timedOut } : {}) });
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { act } from "@/lib/agent-activity";
|
||||
import { AgentSweepBody, requestSweep } from "@/lib/agent-runs";
|
||||
import { withToken } from "@/lib/api-tokens";
|
||||
import { v1Catch, v1Json } from "@/lib/api-v1";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Queue a sweep: one or two settings varied from the token's own base deployment. Each variant is
|
||||
* deployed, benchmarked and removed again, one after another.
|
||||
*/
|
||||
export const POST = withToken("benchmarks:run", async (req, { token }) => {
|
||||
try {
|
||||
const body = AgentSweepBody.parse(await req.json());
|
||||
const r = await act(token, "sweep.create", { type: "sweep" }, () => requestSweep(token, body));
|
||||
return v1Json(
|
||||
{
|
||||
...r,
|
||||
message:
|
||||
r.state === "pending_approval"
|
||||
? "Requested; it waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop."
|
||||
: `Queued (${r.variants} variants, stopped after ${r.timeLimitMinutes} min); GET /api/v1/sweeps/${r.id}?wait=900 for progress.`,
|
||||
},
|
||||
201,
|
||||
);
|
||||
} catch (err) {
|
||||
return v1Catch(err);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
"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 { toast } from "sonner";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
|
||||
/** 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 {formatBytes(job.totalBytes)}
|
||||
{job.purpose === "add" ? " of additional files" : ""}. 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>
|
||||
);
|
||||
}
|
||||
|
||||
/** Something else an API token asked for (a deployment start, a run, a sweep): approve or reject. */
|
||||
export function AgentApprovalBar({ requestedBy, what, base }: { requestedBy: string | null; what: string; base: string }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function decide(kind: "approve" | "reject") {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch(`${base}/${kind}`, { method: "POST" });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
toast.error(body.error?.message ?? `Request failed (${res.status})`);
|
||||
return;
|
||||
}
|
||||
toast.success(kind === "approve" ? "Approved" : "Rejected");
|
||||
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>{requestedBy ?? "An API token"}</strong> asks to {what}. It goes ahead once you approve it.
|
||||
</span>
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" disabled={busy} onClick={() => decide("approve")}>
|
||||
<CheckIcon />
|
||||
Approve
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" disabled={busy} onClick={() => decide("reject")}>
|
||||
<XIcon />
|
||||
Reject
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import type { ResourceStats } from "@/lib/db/schema";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
|
||||
const cores = (v: number | null) => (v == null ? "—" : v.toFixed(v >= 10 ? 0 : 1));
|
||||
const mib = (v: number | null | undefined) => (v == null ? "—" : formatBytes(v * 2 ** 20));
|
||||
const round = (v: number | null | undefined, unit: string) => (v == null ? "—" : `${Math.round(v)}${unit}`);
|
||||
|
||||
function Cell({ label, value, note }: { label: string; value: string; note?: string }) {
|
||||
return (
|
||||
@@ -42,10 +44,11 @@ export function BenchmarkResources({ stats, names }: { stats: ResourceStats; nam
|
||||
<span className="text-xs font-medium">
|
||||
GPU {g.index} · {g.name}
|
||||
</span>
|
||||
<div className="grid gap-2 sm:grid-cols-3">
|
||||
<Cell label="VRAM, peak" value={formatBytes(g.vramPeakMb * 2 ** 20)} note={`of ${formatBytes(g.vramTotalMb * 2 ** 20)} · average ${formatBytes(g.vramAvgMb * 2 ** 20)}`} />
|
||||
<Cell label="Utilization" value={`${Math.round(g.utilAvg)}%`} note={`average · peak ${Math.round(g.utilPeak)}%`} />
|
||||
<Cell label="Power" value={g.powerAvgW != null ? `${Math.round(g.powerAvgW)} W` : "—"} note={g.powerPeakW != null ? `average · peak ${Math.round(g.powerPeakW)} W` : undefined} />
|
||||
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<Cell label="VRAM, peak" value={mib(g.vramPeakMb)} note={`of ${mib(g.vramTotalMb)} · average ${mib(g.vramAvgMb)}`} />
|
||||
<Cell label="Utilization" value={round(g.utilAvg, "%")} note={g.utilPeak != null ? `average · peak ${round(g.utilPeak, "%")}` : "not reported"} />
|
||||
<Cell label="Power" value={round(g.powerAvgW, " W")} note={g.powerPeakW != null ? `average · peak ${round(g.powerPeakW, " W")}` : "not reported"} />
|
||||
<Cell label="Temperature" value={round(g.tempAvgC, " °C")} note={g.tempPeakC != null ? `average · peak ${round(g.tempPeakC, " °C")}` : "not reported"} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { LoaderCircleIcon } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const STYLE: Record<string, string> = {
|
||||
pending_approval: "border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",
|
||||
queued: "border-foreground/15 text-muted-foreground",
|
||||
running: "border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300",
|
||||
completed: "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",
|
||||
@@ -10,7 +11,7 @@ const STYLE: Record<string, string> = {
|
||||
};
|
||||
|
||||
export function BenchmarkStateBadge({ state, cancelling, className }: { state: string; cancelling?: boolean; className?: string }) {
|
||||
const label = state === "running" && cancelling ? "cancelling" : state;
|
||||
const label = state === "running" && cancelling ? "cancelling" : state === "pending_approval" ? "awaiting approval" : state;
|
||||
return (
|
||||
<span className={cn("inline-flex h-5 shrink-0 items-center gap-1 rounded-4xl border px-2 text-xs font-medium whitespace-nowrap", STYLE[state] ?? STYLE.queued, className)}>
|
||||
{state === "running" && <LoaderCircleIcon className="size-3 animate-spin" />}
|
||||
|
||||
@@ -31,3 +31,21 @@ export async function startUpdate(modelId: string): Promise<boolean> {
|
||||
if (ok) toast.success("Update queued");
|
||||
return ok;
|
||||
}
|
||||
|
||||
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");
|
||||
return ok;
|
||||
}
|
||||
|
||||
/** Returns whether the model left the library (it was only added by this request), or null on error. */
|
||||
export async function rejectJob(jobId: string): Promise<{ removedModel: boolean } | null> {
|
||||
const res = await fetch(`/api/jobs/${jobId}/reject`, { method: "POST" });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
toast.error(body.error?.message ?? `Request failed (${res.status})`);
|
||||
return null;
|
||||
}
|
||||
toast.info(body.removedModel ? "Rejected; the model was removed from the library" : "Rejected");
|
||||
return body;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { formatBytes, formatDuration, formatSpeed, percent } from "@/lib/format"
|
||||
import type { JobSnapshot } from "@/lib/jobs";
|
||||
|
||||
const STATE_VARIANT: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
|
||||
pending_approval: "outline",
|
||||
queued: "outline",
|
||||
downloading: "secondary",
|
||||
verifying: "secondary",
|
||||
@@ -14,7 +15,12 @@ const STATE_VARIANT: Record<string, "default" | "secondary" | "destructive" | "o
|
||||
};
|
||||
|
||||
export function JobStateBadge({ job }: { job: Pick<JobSnapshot, "state" | "cancelRequested"> }) {
|
||||
const label = job.cancelRequested && !["cancelled", "completed", "failed"].includes(job.state) ? "cancelling" : job.state;
|
||||
const label =
|
||||
job.cancelRequested && !["cancelled", "completed", "failed"].includes(job.state)
|
||||
? "cancelling"
|
||||
: job.state === "pending_approval"
|
||||
? "awaiting approval"
|
||||
: job.state;
|
||||
return <Badge variant={STATE_VARIANT[job.state] ?? "outline"}>{label}</Badge>;
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { metaRows } from "@/lib/benchmark-meta";
|
||||
import type { RunMeta, SystemSummary } from "@/lib/db/schema";
|
||||
import { systemSummaryLines } from "@/lib/hardware";
|
||||
|
||||
/** Hardware, runtime and model a run measured (A and B side by side for an A/B), plus the system summary. */
|
||||
export function RunMetaCard({ meta, metaB, system }: { meta: RunMeta | null; metaB?: RunMeta | null; system: SystemSummary | null }) {
|
||||
if (!meta && !system) return null;
|
||||
const a = meta ? metaRows(meta) : [];
|
||||
const b = metaB ? metaRows(metaB) : null;
|
||||
const keys = [...new Set([...a, ...(b ?? [])].map((r) => r.key))];
|
||||
const label = (k: string) => (a.find((r) => r.key === k) ?? b?.find((r) => r.key === k))!.label;
|
||||
const value = (rows: typeof a | null, k: string) => rows?.find((r) => r.key === k)?.value ?? "–";
|
||||
return (
|
||||
<Card size="sm">
|
||||
<CardHeader>
|
||||
<CardTitle>Hardware & runtime</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
{meta && (
|
||||
<dl className={`grid gap-x-4 gap-y-1 text-xs ${b ? "grid-cols-[max-content_1fr_1fr]" : "grid-cols-[max-content_1fr]"}`}>
|
||||
{b && (
|
||||
<>
|
||||
<span />
|
||||
<span className="font-medium">A</span>
|
||||
<span className="font-medium">B</span>
|
||||
</>
|
||||
)}
|
||||
{keys.map((k) => (
|
||||
<div key={k} className="contents">
|
||||
<dt className="text-muted-foreground">{label(k)}</dt>
|
||||
<dd className="min-w-0 font-mono break-all">{value(a, k)}</dd>
|
||||
{b && <dd className="min-w-0 font-mono break-all">{value(b, k)}</dd>}
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)}
|
||||
{meta && meta.overridden.length > 0 && <p className="text-[11px] text-muted-foreground">From Settings → Hardware: {meta.overridden.join(", ")}.</p>}
|
||||
{system && (
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="text-xs text-muted-foreground">System</span>
|
||||
<ul className="flex flex-col gap-0.5 text-xs">
|
||||
{systemSummaryLines(system).map((l) => (
|
||||
<li key={l}>{l}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { BoxesIcon, KeyRoundIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import { BotIcon, BoxesIcon, CpuIcon, KeyRoundIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useTransition } from "react";
|
||||
@@ -71,9 +71,17 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
|
||||
<BoxesIcon />
|
||||
Runtimes
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem render={<Link href="/settings/hardware" />}>
|
||||
<CpuIcon />
|
||||
Hardware
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem render={<Link href="/settings/api-keys" />}>
|
||||
<KeyRoundIcon />
|
||||
API keys
|
||||
Runtime API keys
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem render={<Link href="/settings/api-tokens" />}>
|
||||
<BotIcon />
|
||||
API tokens
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
{
|
||||
"instructions": "Write the Python 3 function described below. Use only the standard library. Reply with the complete function definition, starting with def, in a single ```python code block and nothing else.",
|
||||
"items": [
|
||||
{
|
||||
"id": "is-palindrome",
|
||||
"prompt": "is_palindrome(s: str) -> bool: True if s reads the same forwards and backwards, ignoring case and every character that isn't a letter or a digit.",
|
||||
"tests": [
|
||||
"assert is_palindrome('A man, a plan, a canal: Panama') is True",
|
||||
"assert is_palindrome('race a car') is False",
|
||||
"assert is_palindrome('') is True",
|
||||
"assert is_palindrome('No lemon, no melon') is True",
|
||||
"assert is_palindrome('ab2a') is False"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "fizzbuzz",
|
||||
"prompt": "fizzbuzz(n: int) -> list[str]: for 1..n, 'Fizz' for multiples of 3, 'Buzz' for multiples of 5, 'FizzBuzz' for multiples of both, else the number as a string.",
|
||||
"tests": [
|
||||
"assert fizzbuzz(5) == ['1', '2', 'Fizz', '4', 'Buzz']",
|
||||
"assert fizzbuzz(15)[-1] == 'FizzBuzz'",
|
||||
"assert fizzbuzz(0) == []",
|
||||
"assert len(fizzbuzz(100)) == 100"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "merge-intervals",
|
||||
"prompt": "merge_intervals(intervals: list[list[int]]) -> list[list[int]]: merge overlapping or touching [start, end] intervals and return them sorted by start.",
|
||||
"tests": [
|
||||
"assert merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]",
|
||||
"assert merge_intervals([[1, 4], [4, 5]]) == [[1, 5]]",
|
||||
"assert merge_intervals([]) == []",
|
||||
"assert merge_intervals([[5, 7], [1, 2]]) == [[1, 2], [5, 7]]",
|
||||
"assert merge_intervals([[1, 10], [2, 3], [4, 5]]) == [[1, 10]]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "word-count",
|
||||
"prompt": "word_count(text: str) -> dict[str, int]: count words, lowercased, where a word is a run of letters (anything else separates words).",
|
||||
"tests": [
|
||||
"assert word_count('Hello, hello world!') == {'hello': 2, 'world': 1}",
|
||||
"assert word_count('') == {}",
|
||||
"assert word_count('one-two three') == {'one': 1, 'two': 1, 'three': 1}",
|
||||
"assert word_count('A a A b') == {'a': 3, 'b': 1}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "roman-to-int",
|
||||
"prompt": "roman_to_int(s: str) -> int: convert a Roman numeral (I, V, X, L, C, D, M, with subtractive forms like IV and CM) to an integer.",
|
||||
"tests": [
|
||||
"assert roman_to_int('III') == 3",
|
||||
"assert roman_to_int('LVIII') == 58",
|
||||
"assert roman_to_int('MCMXCIV') == 1994",
|
||||
"assert roman_to_int('XLIX') == 49",
|
||||
"assert roman_to_int('MMXXVI') == 2026"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "flatten",
|
||||
"prompt": "flatten(nested: list) -> list: return all non-list items of an arbitrarily nested list, in order.",
|
||||
"tests": [
|
||||
"assert flatten([1, [2, [3, [4]], 5]]) == [1, 2, 3, 4, 5]",
|
||||
"assert flatten([]) == []",
|
||||
"assert flatten([[], [[]], [1]]) == [1]",
|
||||
"assert flatten(['a', ['b', ['c']]]) == ['a', 'b', 'c']"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "second-largest",
|
||||
"prompt": "second_largest(nums: list[int]) -> int | None: the second largest distinct value, or None if there isn't one.",
|
||||
"tests": [
|
||||
"assert second_largest([3, 1, 4, 1, 5, 9, 2, 6]) == 6",
|
||||
"assert second_largest([7, 7, 7]) is None",
|
||||
"assert second_largest([]) is None",
|
||||
"assert second_largest([-2, -5, -1]) == -2",
|
||||
"assert second_largest([10, 9]) == 9"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "rle-encode",
|
||||
"prompt": "rle_encode(s: str) -> str: run-length encode a string as each character followed by its run length, e.g. 'aaabcc' -> 'a3b1c2'.",
|
||||
"tests": [
|
||||
"assert rle_encode('aaabcc') == 'a3b1c2'",
|
||||
"assert rle_encode('') == ''",
|
||||
"assert rle_encode('abc') == 'a1b1c1'",
|
||||
"assert rle_encode('zzzzzzzzzzzz') == 'z12'"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"lengths": [0.25, 0.5, 1.0],
|
||||
"positions": [0.1, 0.5, 0.9],
|
||||
"reserveTokens": 384,
|
||||
"seed": 20261021,
|
||||
"needle": "Note for later: the access code for the {color} vault is {code}.",
|
||||
"question": "In the text above there is one note with an access code for the {color} vault. What is that access code? Answer with the six-digit number only.",
|
||||
"colors": ["amber", "cobalt", "crimson", "jade", "silver", "violet", "ochre", "teal", "scarlet"],
|
||||
"filler": [
|
||||
"The river bends twice before it reaches the old mill at the edge of the valley.",
|
||||
"Most of the orchard was planted after the long winter, when the soil had recovered.",
|
||||
"A narrow path leads from the station to the market square, lined with plane trees.",
|
||||
"In spring the meadows fill with clover and the bees return to the wooden hives.",
|
||||
"The library keeps its oldest maps in a cool room behind the reading hall.",
|
||||
"Fishing boats leave the harbour before dawn and come back around midday.",
|
||||
"The bakery on the corner opens at six and is usually sold out by ten.",
|
||||
"Snow rarely stays on the lower slopes for more than a few days at a time.",
|
||||
"An old stone bridge crosses the stream where the two footpaths meet.",
|
||||
"The town hall clock was repaired last year and now runs a minute fast.",
|
||||
"Every autumn the vineyards hire extra hands for the harvest weeks.",
|
||||
"The lighthouse has been automated, but a keeper still checks it each week.",
|
||||
"A small museum by the church shows tools that farmers used a century ago.",
|
||||
"The tram line was extended to the university campus in the north.",
|
||||
"Wild garlic grows along the shaded banks of the brook in early May.",
|
||||
"The guesthouse serves breakfast in a garden room that faces the hills.",
|
||||
"Cyclists often stop at the fountain to refill their bottles before the climb.",
|
||||
"The weekly market sells cheese from three farms in the neighbouring villages.",
|
||||
"On clear nights the observatory opens its dome to visitors after nine.",
|
||||
"The ferry runs every hour in summer and twice a day in the colder months.",
|
||||
"A row of chestnut trees marks the old boundary of the monastery grounds.",
|
||||
"The pottery workshop fires its kiln on Thursdays and sells seconds on Fridays.",
|
||||
"Fog settles in the valley on most mornings and lifts by late morning.",
|
||||
"The cooperative store stocks seeds, rope, lamp oil and tinned food.",
|
||||
"Herons nest in the reeds at the far end of the lake each year.",
|
||||
"The school bus takes the long way round when the pass is closed.",
|
||||
"A painter rents the attic above the bookshop for the summer months.",
|
||||
"The old railway embankment is now a walking trail through the woods.",
|
||||
"Shepherds move the flocks to the high pastures in the first week of June.",
|
||||
"The smithy still repairs gates and hinges for the farms nearby."
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
{
|
||||
"tools": {
|
||||
"get_weather": {
|
||||
"description": "Current weather for a city.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": { "type": "string", "description": "City name, e.g. Berlin" },
|
||||
"unit": { "type": "string", "enum": ["celsius", "fahrenheit"] }
|
||||
},
|
||||
"required": ["city", "unit"]
|
||||
}
|
||||
},
|
||||
"convert_currency": {
|
||||
"description": "Convert an amount of money between currencies.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"amount": { "type": "number" },
|
||||
"from": { "type": "string", "description": "ISO 4217 code, e.g. USD" },
|
||||
"to": { "type": "string", "description": "ISO 4217 code, e.g. EUR" }
|
||||
},
|
||||
"required": ["amount", "from", "to"]
|
||||
}
|
||||
},
|
||||
"create_calendar_event": {
|
||||
"description": "Add an event to the user's calendar.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": { "type": "string" },
|
||||
"date": { "type": "string", "description": "YYYY-MM-DD" },
|
||||
"time": { "type": "string", "description": "HH:MM, 24-hour" },
|
||||
"duration_minutes": { "type": "integer" }
|
||||
},
|
||||
"required": ["title", "date", "time", "duration_minutes"]
|
||||
}
|
||||
},
|
||||
"set_timer": {
|
||||
"description": "Start a countdown timer.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": { "minutes": { "type": "integer" } },
|
||||
"required": ["minutes"]
|
||||
}
|
||||
},
|
||||
"get_stock_price": {
|
||||
"description": "Latest price of a stock by its ticker symbol.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": { "ticker": { "type": "string", "description": "e.g. AAPL" } },
|
||||
"required": ["ticker"]
|
||||
}
|
||||
},
|
||||
"search_files": {
|
||||
"description": "Search the user's files.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": { "type": "string" },
|
||||
"extension": { "type": "string", "description": "File extension without the dot, e.g. pdf" }
|
||||
},
|
||||
"required": ["query"]
|
||||
}
|
||||
},
|
||||
"send_message": {
|
||||
"description": "Send a chat message to a contact.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"recipient": { "type": "string" },
|
||||
"text": { "type": "string" }
|
||||
},
|
||||
"required": ["recipient", "text"]
|
||||
}
|
||||
},
|
||||
"calculate": {
|
||||
"description": "Evaluate an arithmetic expression.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": { "expression": { "type": "string", "description": "e.g. 3 * (4 + 5)" } },
|
||||
"required": ["expression"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "weather-berlin",
|
||||
"tools": ["get_weather", "get_stock_price", "set_timer"],
|
||||
"prompt": "What's the weather in Berlin right now? Use Celsius.",
|
||||
"expect": { "name": "get_weather", "args": { "city": "Berlin", "unit": "celsius" } }
|
||||
},
|
||||
{
|
||||
"id": "currency-usd-eur",
|
||||
"tools": ["convert_currency", "calculate", "get_stock_price"],
|
||||
"prompt": "How much is 250 US dollars in euros?",
|
||||
"expect": { "name": "convert_currency", "args": { "amount": 250, "from": "USD", "to": "EUR" } }
|
||||
},
|
||||
{
|
||||
"id": "calendar-budget",
|
||||
"tools": ["create_calendar_event", "set_timer", "send_message"],
|
||||
"prompt": "Put a meeting called Budget review on 2026-11-03 at 14:30 for 45 minutes in my calendar.",
|
||||
"expect": { "name": "create_calendar_event", "args": { "title": { "contains": "budget review" }, "date": "2026-11-03", "time": "14:30", "duration_minutes": 45 } }
|
||||
},
|
||||
{
|
||||
"id": "timer-12",
|
||||
"tools": ["set_timer", "create_calendar_event", "get_weather"],
|
||||
"prompt": "Set a timer for 12 minutes.",
|
||||
"expect": { "name": "set_timer", "args": { "minutes": 12 } }
|
||||
},
|
||||
{
|
||||
"id": "stock-aapl",
|
||||
"tools": ["get_stock_price", "convert_currency", "search_files"],
|
||||
"prompt": "What's Apple's stock price at the moment? The ticker is AAPL.",
|
||||
"expect": { "name": "get_stock_price", "args": { "ticker": "AAPL" } }
|
||||
},
|
||||
{
|
||||
"id": "files-invoices",
|
||||
"tools": ["search_files", "send_message", "calculate"],
|
||||
"prompt": "Find my PDF files about invoices.",
|
||||
"expect": { "name": "search_files", "args": { "query": { "contains": "invoice" }, "extension": { "oneOf": ["pdf", ".pdf"] } } }
|
||||
},
|
||||
{
|
||||
"id": "message-maria",
|
||||
"tools": ["send_message", "create_calendar_event", "set_timer"],
|
||||
"prompt": "Tell Maria that I'll be ten minutes late.",
|
||||
"expect": { "name": "send_message", "args": { "recipient": "Maria", "text": { "contains": "late" } } }
|
||||
},
|
||||
{
|
||||
"id": "weather-tokyo-f",
|
||||
"tools": ["get_weather", "convert_currency", "search_files"],
|
||||
"prompt": "Weather in Tokyo, in Fahrenheit please.",
|
||||
"expect": { "name": "get_weather", "args": { "city": "Tokyo", "unit": "fahrenheit" } }
|
||||
},
|
||||
{
|
||||
"id": "currency-jpy-chf",
|
||||
"tools": ["calculate", "convert_currency", "get_weather"],
|
||||
"prompt": "Convert 1200 Japanese yen to Swiss francs.",
|
||||
"expect": { "name": "convert_currency", "args": { "amount": 1200, "from": "JPY", "to": "CHF" } }
|
||||
},
|
||||
{
|
||||
"id": "timer-90",
|
||||
"tools": ["create_calendar_event", "set_timer", "send_message"],
|
||||
"prompt": "I need a 90 minute timer.",
|
||||
"expect": { "name": "set_timer", "args": { "minutes": 90 } }
|
||||
},
|
||||
{
|
||||
"id": "calendar-dentist",
|
||||
"tools": ["send_message", "get_weather", "create_calendar_event"],
|
||||
"prompt": "Schedule 'Dentist' for 2026-12-01 at 09:00, it takes 30 minutes.",
|
||||
"expect": { "name": "create_calendar_event", "args": { "title": { "contains": "dentist" }, "date": "2026-12-01", "time": "09:00", "duration_minutes": 30 } }
|
||||
},
|
||||
{
|
||||
"id": "calc-17x23",
|
||||
"tools": ["calculate", "get_stock_price", "set_timer"],
|
||||
"prompt": "What is 17 times 23? Use the calculator.",
|
||||
"expect": { "name": "calculate", "args": { "expression": { "matches": "^\\s*17\\s*[*x×]\\s*23\\s*$" } } }
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
import "server-only";
|
||||
import { and, eq, inArray, isNotNull, isNull, ne, or, sql } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { checkArgs, checkHostPort, checkLimits, checkStart, checkVram, type GpuLoad, TuningError, type TuningGuardrails } from "@/lib/agent-tuning";
|
||||
import type { TokenIdentity } from "@/lib/api-tokens";
|
||||
import { effectiveHardware } from "@/lib/benchmark-snapshot";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { benchmarkRuns, benchmarkSweeps, type DeploymentOptions, deployments, models, type RuntimeAccelerator, runtimes } from "@/lib/db/schema";
|
||||
import { API_KEY_PLACEHOLDER, buildCommand, ENGINE_PORT, estimateMemoryMb, estimateVramMb, renderCommand } from "@/lib/deploy-command";
|
||||
import {
|
||||
createDeployment,
|
||||
DeploymentBody,
|
||||
DeploymentError,
|
||||
type DeploymentInput,
|
||||
type DeploymentRow,
|
||||
deploymentFileBytes,
|
||||
getDeployment,
|
||||
requestDelete,
|
||||
setDesiredState,
|
||||
updateDeployment,
|
||||
validateDeployment,
|
||||
} from "@/lib/deployments";
|
||||
import { getDockerInfo } from "@/lib/runtimes";
|
||||
import { getTuning } from "@/lib/settings";
|
||||
|
||||
// Deployments through the API: the same validation, estimates and command as the UI, plus the agent
|
||||
// guardrails (runtime allowlist, argument allowlist, ports, caps, one GPU job at a time, protected
|
||||
// deployments, approval). Agents only change deployments their own token created.
|
||||
|
||||
const RUN_OPEN = ["pending_approval", "queued", "running"] as const;
|
||||
|
||||
/** Stored (already validated) options as request input; they're validated again on the way in. */
|
||||
const asInput = (o: DeploymentOptions) => o as DeploymentInput["options"];
|
||||
|
||||
export const AgentDeploymentBody = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(80).optional(),
|
||||
runtimeId: z.string().min(1),
|
||||
modelId: z.string().min(1),
|
||||
options: DeploymentBody.shape.options.strict(),
|
||||
cpus: z.number().min(0.1).max(1024).nullable().optional(),
|
||||
memoryMb: z.number().int().min(256).max(4_194_304).nullable().optional(),
|
||||
hostPort: z.number().int().min(1024).max(65_535).nullable().optional(),
|
||||
/** Start right away (default); with approval mode "approve" the start waits for the user. */
|
||||
start: z.boolean().default(true),
|
||||
/** Only validate and return the command and estimates; nothing is created. */
|
||||
dryRun: z.boolean().default(false),
|
||||
})
|
||||
.strict();
|
||||
export type AgentDeploymentInput = z.infer<typeof AgentDeploymentBody>;
|
||||
|
||||
export const AgentDeploymentPatch = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(80).optional(),
|
||||
options: DeploymentBody.shape.options.partial().strict().optional(),
|
||||
cpus: z.number().min(0.1).max(1024).nullable().optional(),
|
||||
memoryMb: z.number().int().min(256).max(4_194_304).nullable().optional(),
|
||||
hostPort: z.number().int().min(1024).max(65_535).nullable().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Agent deployments, runs and sweeps that keep the GPU busy right now (all tokens). */
|
||||
export async function gpuLoad(selfId?: string): Promise<GpuLoad> {
|
||||
const notSelf = selfId ? ne(deployments.id, selfId) : undefined;
|
||||
const agentDep = and(isNotNull(deployments.requestedByTokenId), isNull(deployments.deleteRequestedAt), notSelf);
|
||||
const [[dep], [starting], [runs], [sweeps]] = await Promise.all([
|
||||
db()
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(deployments)
|
||||
.where(and(agentDep, or(eq(deployments.desiredState, "running"), isNotNull(deployments.startRequestedAt), inArray(deployments.state, ["starting", "running"])))),
|
||||
db()
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(deployments)
|
||||
.where(and(agentDep, eq(deployments.state, "starting"))),
|
||||
db()
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(benchmarkRuns)
|
||||
.where(and(isNotNull(benchmarkRuns.requestedByTokenId), inArray(benchmarkRuns.state, [...RUN_OPEN]))),
|
||||
db()
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(benchmarkSweeps)
|
||||
.where(and(isNotNull(benchmarkSweeps.requestedByTokenId), inArray(benchmarkSweeps.state, [...RUN_OPEN]))),
|
||||
]);
|
||||
return { agentDeployments: Number(dep.n), agentStarting: Number(starting.n), agentRuns: Number(runs.n) + Number(sweeps.n) };
|
||||
}
|
||||
|
||||
type Pool = { accelerator: RuntimeAccelerator; gpus: string[] | null };
|
||||
const sharesGpus = (a: Pool, b: Pool) =>
|
||||
a.accelerator !== "cpu" &&
|
||||
b.accelerator !== "cpu" &&
|
||||
(a.accelerator === "nvidia") === (b.accelerator === "nvidia") &&
|
||||
(a.accelerator !== "nvidia" || !a.gpus?.length || !b.gpus?.length || a.gpus.some((g) => b.gpus!.includes(g)));
|
||||
|
||||
/** VRAM of the GPUs a deployment gets (NVIDIA: the picked ones or all; /dev/dri: Intel and AMD). */
|
||||
async function poolVramMb(pool: Pool): Promise<number | null> {
|
||||
const { hardware, nvidia } = await effectiveHardware();
|
||||
if (pool.accelerator === "nvidia") {
|
||||
const gs = pool.gpus?.length ? nvidia.filter((g) => pool.gpus!.includes(g.uuid)) : nvidia;
|
||||
return gs.length ? gs.reduce((s, g) => s + g.memoryMb, 0) : null;
|
||||
}
|
||||
const gs = (hardware?.gpus ?? []).filter((g) => (pool.accelerator === "rocm" ? g.vendor === "amd" : g.vendor !== "nvidia"));
|
||||
return gs.length && gs.every((g) => g.vramMb) ? gs.reduce((s, g) => s + (g.vramMb ?? 0), 0) : null;
|
||||
}
|
||||
|
||||
/** Estimated VRAM (null: can't tell) of a deployment's options. */
|
||||
async function vramOf(modelId: string, engine: "llama.cpp" | "vllm", options: DeploymentOptions, totalMb: number | null) {
|
||||
return estimateVramMb(await deploymentFileBytes(modelId, options, engine), options.contextSize, engine, options, totalMb);
|
||||
}
|
||||
|
||||
/** Refuse a start that would crowd a running protected deployment on the same GPUs out of VRAM. */
|
||||
async function checkProtectedVram(self: { id?: string; modelId: string; engine: "llama.cpp" | "vllm"; accelerator: RuntimeAccelerator; options: DeploymentOptions }) {
|
||||
if (self.accelerator === "cpu") return;
|
||||
const pool: Pool = { accelerator: self.accelerator, gpus: self.options.gpus ?? null };
|
||||
const running = (
|
||||
await db()
|
||||
.select({ id: deployments.id, name: deployments.name, protected: deployments.protected, modelId: deployments.modelId, options: deployments.options, engine: runtimes.engine, accelerator: runtimes.accelerator })
|
||||
.from(deployments)
|
||||
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
|
||||
.where(and(isNull(deployments.deleteRequestedAt), inArray(deployments.state, ["starting", "running"]), self.id ? ne(deployments.id, self.id) : undefined))
|
||||
).filter((d) => sharesGpus(pool, { accelerator: d.accelerator, gpus: d.options.gpus ?? null }));
|
||||
const protectedNames = running.filter((d) => d.protected).map((d) => d.name);
|
||||
if (protectedNames.length === 0) return;
|
||||
const totalMb = await poolVramMb(pool);
|
||||
checkVram({
|
||||
protectedNames,
|
||||
newMb: await vramOf(self.modelId, self.engine, self.options, totalMb),
|
||||
runningMb: await Promise.all(running.map(async (d) => (await vramOf(d.modelId, d.engine, d.options, totalMb)) ?? -1)),
|
||||
totalMb,
|
||||
});
|
||||
}
|
||||
|
||||
async function runtimeFor(g: TuningGuardrails, runtimeId: string) {
|
||||
const rt = await db().query.runtimes.findFirst({ where: eq(runtimes.id, runtimeId) });
|
||||
if (!rt) throw new DeploymentError("not_found", "Runtime not found. List them with GET /api/v1/runtimes.", 404);
|
||||
if (g.allowedRuntimeIds.length && !g.allowedRuntimeIds.includes(rt.id)) {
|
||||
throw new TuningError("runtime_not_allowed", `runtime "${rt.name}" isn't on the agents' allowlist. Pick one from GET /api/v1/runtimes with "allowed": true.`, 403);
|
||||
}
|
||||
if (rt.imageState !== "present") throw new TuningError("runtime_not_pulled", `runtime "${rt.name}" has no pulled image; ask the user to pull it in Settings → Runtimes.`, 409);
|
||||
return rt;
|
||||
}
|
||||
|
||||
/** The checked deployment: validated options, memory limit, estimates and the command it would run. */
|
||||
async function prepare(g: TuningGuardrails, input: { name: string; runtimeId: string; modelId: string; options: z.infer<typeof DeploymentBody>["options"]; cpus?: number | null; memoryMb?: number | null; hostPort?: number | null }, selfId?: string) {
|
||||
const rt = await runtimeFor(g, input.runtimeId);
|
||||
checkArgs(g, rt.engine, input.options.extraArgs);
|
||||
checkHostPort(g, input.hostPort);
|
||||
const options = await validateDeployment({ ...input, cpus: input.cpus ?? null, memoryMb: input.memoryMb ?? null, hostPort: input.hostPort ?? null }, selfId);
|
||||
const model = await db().query.models.findFirst({ columns: { repoId: true, localPath: true }, where: eq(models.id, input.modelId) });
|
||||
const fileBytes = await deploymentFileBytes(input.modelId, options, rt.engine);
|
||||
const docker = await getDockerInfo();
|
||||
const estimateMb = estimateMemoryMb(fileBytes, options.contextSize, rt.engine, { ...options, accelerator: rt.accelerator });
|
||||
const { memoryMb, cpus } = checkLimits(g, { memoryMb: input.memoryMb, cpus: input.cpus, estimateMb, hostMemoryMb: docker?.memoryBytes ? docker.memoryBytes / 2 ** 20 : null, hostCpus: docker?.cpus ?? null });
|
||||
const totalVram = rt.accelerator === "cpu" ? null : await poolVramMb({ accelerator: rt.accelerator, gpus: options.gpus ?? null });
|
||||
const vramMb = rt.accelerator === "cpu" ? null : estimateVramMb(fileBytes, options.contextSize, rt.engine, options, totalVram);
|
||||
const cmd = buildCommand({
|
||||
engine: rt.engine,
|
||||
options,
|
||||
model: { repoId: model?.repoId ?? "", localPath: model?.localPath ?? "" },
|
||||
runtime: rt,
|
||||
apiKeys: options.requireApiKey ? [API_KEY_PLACEHOLDER] : [],
|
||||
});
|
||||
return {
|
||||
rt,
|
||||
options,
|
||||
memoryMb,
|
||||
cpus,
|
||||
preview: {
|
||||
command: renderCommand(rt.image, cmd),
|
||||
estimates: { memoryMb: estimateMb, vramMb, gpuVramMb: totalVram },
|
||||
limits: { memoryMb, cpus },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Create (and by default start) a deployment for a token. */
|
||||
export async function createAgentDeployment(token: TokenIdentity, body: AgentDeploymentInput, g?: TuningGuardrails) {
|
||||
const guard = g ?? (await getTuning());
|
||||
const name = body.name ?? `${token.name} ${new Date().toISOString().slice(0, 16).replace("T", " ")}`;
|
||||
const p = await prepare(guard, { ...body, name });
|
||||
if (body.start) {
|
||||
checkStart(guard, await gpuLoad());
|
||||
await checkProtectedVram({ modelId: body.modelId, engine: p.rt.engine, accelerator: p.rt.accelerator, options: p.options });
|
||||
}
|
||||
if (body.dryRun) return { dryRun: true as const, created: false, id: null, state: "dry_run", ...p.preview };
|
||||
const pending = body.start && guard.approvalMode === "approve";
|
||||
const { id } = await createDeployment(
|
||||
{ name, runtimeId: body.runtimeId, modelId: body.modelId, options: asInput(p.options), cpus: p.cpus, memoryMb: p.memoryMb, hostPort: body.hostPort ?? null },
|
||||
body.start,
|
||||
{ requestedBy: { tokenId: token.id, name: token.name }, startPendingApproval: pending },
|
||||
);
|
||||
return { dryRun: false as const, created: true, id, state: pending ? "pending_approval" : body.start ? "starting" : "stopped", ...p.preview };
|
||||
}
|
||||
|
||||
/** A deployment this token may change: its own, and not protected. */
|
||||
async function ownDeployment(token: TokenIdentity, id: string): Promise<DeploymentRow> {
|
||||
const d = await getDeployment(id);
|
||||
if (!d) throw new DeploymentError("not_found", "No deployment with this id.", 404);
|
||||
if (d.protected) throw new TuningError("protected", `"${d.name}" is protected; agents can't change, stop, delete or benchmark it.`, 403);
|
||||
if (d.requestedByTokenId !== token.id) throw new TuningError("not_owner", `"${d.name}" wasn't created by this token; agents only change their own deployments.`, 403);
|
||||
return d;
|
||||
}
|
||||
|
||||
/** Change an own, stopped deployment's launch options (fields left out stay). */
|
||||
export async function updateAgentDeployment(token: TokenIdentity, id: string, patch: z.infer<typeof AgentDeploymentPatch>) {
|
||||
const guard = await getTuning();
|
||||
const d = await ownDeployment(token, id);
|
||||
if (d.state !== "stopped" && d.state !== "failed") throw new DeploymentError("busy", "Stop the deployment first (POST …/stop), then change it.", 409);
|
||||
const input = {
|
||||
name: patch.name ?? d.name,
|
||||
runtimeId: d.runtimeId,
|
||||
modelId: d.modelId,
|
||||
options: asInput({ ...d.options, ...patch.options }),
|
||||
cpus: patch.cpus !== undefined ? patch.cpus : d.cpus,
|
||||
memoryMb: patch.memoryMb !== undefined ? patch.memoryMb : d.memoryMb,
|
||||
hostPort: patch.hostPort !== undefined ? patch.hostPort : d.hostPort,
|
||||
};
|
||||
// The memory limit follows the options unless the agent sets one: re-estimate when it was implicit.
|
||||
const p = await prepare(guard, { ...input, memoryMb: patch.memoryMb !== undefined ? patch.memoryMb : patch.options ? null : d.memoryMb }, id);
|
||||
await updateDeployment(id, { ...input, options: asInput(p.options), memoryMb: p.memoryMb, cpus: p.cpus });
|
||||
return p.preview;
|
||||
}
|
||||
|
||||
/** Start an own deployment (waits for approval in mode "approve"). */
|
||||
export async function startAgentDeployment(token: TokenIdentity, id: string): Promise<{ state: string }> {
|
||||
const guard = await getTuning();
|
||||
const d = await ownDeployment(token, id);
|
||||
if (d.desiredState === "running") return { state: d.state };
|
||||
if (d.startRequestedAt) return { state: "pending_approval" };
|
||||
await runtimeFor(guard, d.runtimeId);
|
||||
checkStart(guard, await gpuLoad(id));
|
||||
await checkProtectedVram({ id, modelId: d.modelId, engine: d.engine, accelerator: d.accelerator, options: d.options });
|
||||
if (guard.approvalMode === "approve") {
|
||||
await db().update(deployments).set({ startRequestedAt: new Date() }).where(eq(deployments.id, id));
|
||||
return { state: "pending_approval" };
|
||||
}
|
||||
await setDesiredState(id, "running");
|
||||
return { state: "starting" };
|
||||
}
|
||||
|
||||
export async function stopAgentDeployment(token: TokenIdentity, id: string): Promise<void> {
|
||||
await ownDeployment(token, id);
|
||||
await setDesiredState(id, "stopped");
|
||||
}
|
||||
|
||||
export async function deleteAgentDeployment(token: TokenIdentity, id: string): Promise<void> {
|
||||
await ownDeployment(token, id);
|
||||
await requestDelete(id);
|
||||
}
|
||||
|
||||
/** Compact deployment state for agents; the log only on request. */
|
||||
export function deploymentView(d: DeploymentRow, token: TokenIdentity) {
|
||||
const port = ENGINE_PORT[d.engine];
|
||||
const pending = !!d.startRequestedAt;
|
||||
const state = pending ? "pending_approval" : d.state;
|
||||
return {
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
state,
|
||||
desiredState: d.desiredState,
|
||||
protected: d.protected,
|
||||
requestedBy: d.requestedBy,
|
||||
mine: d.requestedByTokenId === token.id,
|
||||
runtime: { id: d.runtimeId, name: d.runtimeName, engine: d.engine, accelerator: d.accelerator, image: d.runtimeImage },
|
||||
model: { id: d.modelId, repoId: d.repoId },
|
||||
options: d.options,
|
||||
limits: { cpus: d.cpus, memoryMb: d.memoryMb },
|
||||
hostPort: d.hostPort,
|
||||
endpoint: d.state === "running" && d.containerName ? `http://${d.containerName}:${port}/v1` : null,
|
||||
engine: d.engineInfo ? { version: d.engineInfo.version, slots: d.engineInfo.slots, contextSize: d.engineInfo.contextSize } : null,
|
||||
usage: d.stats ? { cpuPercent: Math.round(d.stats.cpuPercent), memoryBytes: d.stats.memoryBytes, memoryLimitBytes: d.stats.memoryLimitBytes, at: d.stats.at } : null,
|
||||
error: d.error,
|
||||
startedAt: d.startedAt?.toISOString() ?? null,
|
||||
readyAt: d.readyAt?.toISOString() ?? null,
|
||||
next: deploymentNext(state, d.desiredState),
|
||||
};
|
||||
}
|
||||
|
||||
function deploymentNext(state: string, desired: string): string {
|
||||
if (state === "pending_approval") return "The start waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop.";
|
||||
if (state === "starting" || (desired === "running" && state === "stopped")) return "Starting (loading the model); GET this deployment with ?wait=600 instead of polling.";
|
||||
if (state === "running") return "Ready: benchmark it with POST /api/v1/benchmarks.";
|
||||
if (state === "failed") return "Failed to start; see error (and ?log=50). Change the options (PATCH) and start again, or tell the user.";
|
||||
if (state === "stopping") return "Stopping.";
|
||||
return "Stopped.";
|
||||
}
|
||||
|
||||
/** Settled for ?wait=: not on the way between states. */
|
||||
export function deploymentSettled(v: { state: string; desiredState: string }): boolean {
|
||||
if (v.state === "starting" || v.state === "stopping") return false;
|
||||
if (v.desiredState === "running" && v.state === "stopped") return false;
|
||||
if (v.desiredState === "stopped" && v.state === "running") return false;
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
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 } 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";
|
||||
|
||||
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 jobs 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), inArray(jobs.state, [...OPEN_STATES])));
|
||||
return Number(r.n);
|
||||
}
|
||||
|
||||
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") return "Already downloaded.";
|
||||
return `The last download ended as "${state}"; ask the user to retry it in Kaname.`;
|
||||
}
|
||||
|
||||
/** 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) });
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 && 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 download 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);
|
||||
const worker = await getWorkerStatus();
|
||||
checkGuardrails(g, {
|
||||
repoId: hub.repoId,
|
||||
requestBytes,
|
||||
freeBytes: worker.online ? worker.modelsDirFreeBytes : null,
|
||||
reservedBytes: await reservedBytes(),
|
||||
openAgentJobs: await openAgentJobs(),
|
||||
});
|
||||
|
||||
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 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): Promise<{ removedModel: boolean }> {
|
||||
const job = await pendingJob(jobId);
|
||||
await db()
|
||||
.update(jobs)
|
||||
.set({ state: "cancelled", finishedAt: new Date(), errorMessage: "Rejected by the user." })
|
||||
.where(eq(jobs.id, job.id));
|
||||
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 };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
// 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. */
|
||||
export function checkGuardrails(g: Guardrails, x: GuardrailInput): void {
|
||||
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(" · ");
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import "server-only";
|
||||
import { and, desc, eq, or } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { checkRun, TuningError, type TuningGuardrails } from "@/lib/agent-tuning";
|
||||
import { gpuLoad } from "@/lib/agent-deployments";
|
||||
import type { TokenIdentity } from "@/lib/api-tokens";
|
||||
import { metaRows } from "@/lib/benchmark-meta";
|
||||
import { headline } from "@/lib/benchmark-view";
|
||||
import { BENCHMARK_PHASES, type BenchmarkSummary, benchmarkRuns, QUALITY_SECTIONS, type QualityResult, type RunMeta } from "@/lib/db/schema";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { BenchmarkBody, type BenchmarkRow, createBenchmark, getBenchmark, getBenchmarks } from "@/lib/benchmarks";
|
||||
import { getDeployment } from "@/lib/deployments";
|
||||
import { getTuning } from "@/lib/settings";
|
||||
import { MAX_SWEEP_PARAMS, splitValues } from "@/lib/sweep";
|
||||
import { createSweep, getSweep, type SweepRow } from "@/lib/sweeps";
|
||||
|
||||
// Benchmark runs, A/B runs and sweeps through the API: on the token's own deployments only, one at a
|
||||
// time across all agents, with time limits and (by default) the user's approval.
|
||||
|
||||
export const AgentRunBody = z
|
||||
.object({
|
||||
/** run: BetterBench speed; ab: paired A/B; eval: the quality eval (tool calling, coding, retrieval). */
|
||||
kind: z.enum(["run", "ab", "eval"]).default("run"),
|
||||
deploymentId: z.string().min(1),
|
||||
/** A/B: the second deployment (same model). */
|
||||
deploymentBId: z.string().min(1).optional(),
|
||||
label: z.string().trim().max(120).optional(),
|
||||
description: z.string().trim().max(4000).optional(),
|
||||
/** quick: 5 passes, a smoke check; full (default): 20 passes, comparable. */
|
||||
quick: z.boolean().default(false),
|
||||
passes: z.number().int().min(1).max(200).optional(),
|
||||
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
|
||||
mdePct: z.number().min(0.1).max(50).optional(),
|
||||
maxPairs: z.number().int().min(12).max(2000).optional(),
|
||||
/** eval: which sections (default all). */
|
||||
sections: z.array(z.enum(QUALITY_SECTIONS)).max(3).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const AgentSweepBody = z
|
||||
.object({
|
||||
baseDeploymentId: z.string().min(1),
|
||||
label: z.string().trim().max(80).optional(),
|
||||
/** One or two settings with their values, e.g. [{ key: "kvCache", values: ["f16", "q8_0"] }]. */
|
||||
params: z
|
||||
.array(z.object({ key: z.string().min(1).max(40), values: z.array(z.string().max(1024)).min(1).max(16) }).strict())
|
||||
.min(1)
|
||||
.max(MAX_SWEEP_PARAMS),
|
||||
quick: z.boolean().default(true),
|
||||
passes: z.number().int().min(1).max(200).optional(),
|
||||
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
|
||||
/** Also run the quality eval on each variant. */
|
||||
quality: z.boolean().default(false),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** A deployment this token may benchmark: its own, not protected, running. */
|
||||
async function benchmarkable(token: TokenIdentity, id: string, role: string) {
|
||||
const d = await getDeployment(id);
|
||||
if (!d) throw new TuningError("not_owner", `${role} not found.`, 404);
|
||||
if (d.protected) throw new TuningError("protected", `"${d.name}" is protected; agents can't benchmark it.`, 403);
|
||||
if (d.requestedByTokenId !== token.id) throw new TuningError("not_owner", `"${d.name}" wasn't created by this token; agents only benchmark their own deployments. Deploy the model yourself (POST /api/v1/deployments).`, 403);
|
||||
return d;
|
||||
}
|
||||
|
||||
const requested = (token: TokenIdentity) => ({ tokenId: token.id, name: token.name });
|
||||
|
||||
/** Queue a run or A/B against the token's own running deployment(s). */
|
||||
export async function requestRun(token: TokenIdentity, body: z.infer<typeof AgentRunBody>, g?: TuningGuardrails) {
|
||||
const guard = g ?? (await getTuning());
|
||||
await benchmarkable(token, body.deploymentId, body.kind === "ab" ? "Deployment A" : "The deployment");
|
||||
if (body.kind === "ab") {
|
||||
if (!body.deploymentBId) throw new TuningError("not_owner", "An A/B needs deploymentBId (your second deployment of the same model).", 400);
|
||||
await benchmarkable(token, body.deploymentBId, "Deployment B");
|
||||
}
|
||||
checkRun(await gpuLoad());
|
||||
const pending = guard.approvalMode === "approve";
|
||||
const row = await createBenchmark(
|
||||
BenchmarkBody.parse({
|
||||
deploymentId: body.deploymentId,
|
||||
deploymentBId: body.kind === "ab" ? body.deploymentBId : null,
|
||||
label: body.label ?? null,
|
||||
description: body.description ?? null,
|
||||
quick: body.quick,
|
||||
passes: body.passes ?? null,
|
||||
phases: body.phases,
|
||||
mdePct: body.mdePct ?? null,
|
||||
maxPairs: body.maxPairs ?? null,
|
||||
kind: body.kind,
|
||||
evalSections: body.sections,
|
||||
}),
|
||||
{ requestedBy: requested(token), pendingApproval: pending, timeLimitS: guard.maxRunMinutes * 60 },
|
||||
);
|
||||
return { id: row.id, state: pending ? "pending_approval" : "queued", timeLimitMinutes: guard.maxRunMinutes };
|
||||
}
|
||||
|
||||
/** Queue a sweep from the token's own base deployment (each variant deploys and is removed again). */
|
||||
export async function requestSweep(token: TokenIdentity, body: z.infer<typeof AgentSweepBody>, g?: TuningGuardrails) {
|
||||
const guard = g ?? (await getTuning());
|
||||
const base = await benchmarkable(token, body.baseDeploymentId, "The base deployment");
|
||||
const load = await gpuLoad();
|
||||
checkRun(load);
|
||||
// Each variant starts its own deployment; an agent deployment still running would share the GPU.
|
||||
if (load.agentDeployments > 0) {
|
||||
throw new TuningError("gpu_busy", "an agent deployment is still running or waiting to start; a sweep deploys each variant itself. Stop yours first (POST /api/v1/deployments/{id}/stop).", 429);
|
||||
}
|
||||
const count = body.params.reduce((n, p) => n * splitValues(p.values.join(",")).length, 1);
|
||||
if (count > guard.maxSweepVariants) {
|
||||
throw new TuningError("too_many_variants", `That's ${count} variants; agents may run at most ${guard.maxSweepVariants} per sweep. Vary fewer values.`);
|
||||
}
|
||||
const pending = guard.approvalMode === "approve";
|
||||
const row = await createSweep(
|
||||
{ baseDeploymentId: base.id, label: body.label ?? null, params: body.params, quick: body.quick, passes: body.passes ?? null, phases: body.phases, quality: body.quality },
|
||||
{
|
||||
requestedBy: requested(token),
|
||||
pendingApproval: pending,
|
||||
timeLimitS: guard.maxSweepMinutes * 60,
|
||||
runTimeLimitS: guard.maxRunMinutes * 60,
|
||||
maxVariants: guard.maxSweepVariants,
|
||||
},
|
||||
);
|
||||
return { id: row.id, state: pending ? "pending_approval" : "queued", variants: count, timeLimitMinutes: guard.maxSweepMinutes };
|
||||
}
|
||||
|
||||
/** Cancel a run or sweep this token asked for. */
|
||||
export async function ownRun(token: TokenIdentity, id: string) {
|
||||
const run = await getBenchmark(id);
|
||||
if (!run) throw new TuningError("not_owner", "No benchmark run with this id.", 404);
|
||||
if (run.requestedByTokenId !== token.id) throw new TuningError("not_owner", "This run wasn't started by this token; agents only cancel their own runs.", 403);
|
||||
return run;
|
||||
}
|
||||
|
||||
export async function ownSweep(token: TokenIdentity, id: string) {
|
||||
const s = await getSweep(id);
|
||||
if (!s) throw new TuningError("not_owner", "No sweep with this id.", 404);
|
||||
if (s.sweep.requestedByTokenId !== token.id) throw new TuningError("not_owner", "This sweep wasn't started by this token; agents only cancel their own sweeps.", 403);
|
||||
return s;
|
||||
}
|
||||
|
||||
const r1 = (v: number | null | undefined) => (v == null ? null : Math.round(v * 10) / 10);
|
||||
|
||||
/** The quality eval in short: overall score and per section. */
|
||||
export function qualityView(q: QualityResult | null | undefined) {
|
||||
if (!q) return null;
|
||||
return {
|
||||
evalSet: q.evalSet,
|
||||
score: q.score,
|
||||
sections: Object.fromEntries(q.sections.map((s) => [s.section, s.unsupported ? `n/a (${s.unsupported})` : `${s.passed}/${s.total}`])),
|
||||
};
|
||||
}
|
||||
|
||||
/** Headline numbers + the setup (section 1 metadata) as key/value. */
|
||||
function compact(summary: BenchmarkSummary | null, meta: RunMeta | null, quality?: QualityResult | null) {
|
||||
const h = headline(summary);
|
||||
return {
|
||||
...(quality ? { quality: qualityView(quality) } : {}),
|
||||
headline: {
|
||||
decodeTps: r1(h.decode),
|
||||
prefillTps: r1(h.prefill?.tps),
|
||||
prefillDepth: h.prefill?.depth ?? null,
|
||||
ttftMs: r1(h.ttftMs),
|
||||
peakParallelTps: r1(h.peak?.tps),
|
||||
peakParallelLevel: h.peak?.level ?? null,
|
||||
},
|
||||
setup: meta ? Object.fromEntries(metaRows(meta).map((r) => [r.key, r.value])) : null,
|
||||
};
|
||||
}
|
||||
|
||||
const RUN_NEXT: Record<string, string> = {
|
||||
pending_approval: "Waiting for the user's approval in Kaname. Don't retry or poll; tell the user and stop.",
|
||||
queued: "Queued (one benchmark at a time). GET it with ?wait=900 instead of polling.",
|
||||
running: "Running. GET it with ?wait=900 instead of polling.",
|
||||
completed: "Done. Compare runs with GET /api/v1/benchmarks/compare?ids=…",
|
||||
failed: "Failed; see error. Fix the cause before trying again.",
|
||||
cancelled: "Cancelled or rejected by the user (or by you).",
|
||||
};
|
||||
|
||||
export const runSettled = (state: string) => state !== "queued" && state !== "running";
|
||||
|
||||
/** Compact run state: headline numbers, setup, resources; the full summary with `full`. */
|
||||
export function runView(r: BenchmarkRow, token: TokenIdentity, full = false) {
|
||||
const res = r.resources;
|
||||
return {
|
||||
id: r.id,
|
||||
kind: r.kind,
|
||||
state: r.state,
|
||||
label: r.label,
|
||||
description: r.description,
|
||||
deploymentId: r.deploymentId,
|
||||
deploymentBId: r.deploymentBId,
|
||||
deployment: r.snapshot.deploymentName,
|
||||
requestedBy: r.requestedBy,
|
||||
mine: r.requestedByTokenId === token.id,
|
||||
settings: r.settings,
|
||||
phase: r.phase,
|
||||
error: r.error,
|
||||
timeLimitMinutes: r.timeLimitS ? Math.round(r.timeLimitS / 60) : null,
|
||||
startedAt: r.startedAt ? new Date(r.startedAt).toISOString() : null,
|
||||
finishedAt: r.finishedAt ? new Date(r.finishedAt).toISOString() : null,
|
||||
...compact(r.summary, r.meta, r.quality),
|
||||
...(r.kind === "eval" && r.quality && full ? { failed: r.quality.items.filter((i) => !i.pass) } : {}),
|
||||
...(r.kind === "ab" && r.ab
|
||||
? {
|
||||
ab: {
|
||||
pairs: r.ab.pairs,
|
||||
verdict: r.ab.decode_tps.verdict,
|
||||
decodeDiffPct: r1(r.ab.decode_tps.pct_diff),
|
||||
ciPct: [r1(r.ab.decode_tps.ci_low_pct), r1(r.ab.decode_tps.ci_high_pct)],
|
||||
significant: r.ab.decode_tps.significant,
|
||||
setupB: r.metaB ? Object.fromEntries(metaRows(r.metaB).map((x) => [x.key, x.value])) : null,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
resources: res
|
||||
? {
|
||||
cpuAvgCores: r1(res.containers[0]?.cpuAvg),
|
||||
ramPeakBytes: res.containers[0]?.memPeakBytes ?? null,
|
||||
gpus: res.gpus.map((g) => ({ name: g.name, vramPeakMb: g.vramPeakMb, vramTotalMb: g.vramTotalMb, utilAvg: r1(g.utilAvg), powerAvgW: r1(g.powerAvgW), tempPeakC: r1(g.tempPeakC) })),
|
||||
}
|
||||
: null,
|
||||
next: RUN_NEXT[r.state] ?? null,
|
||||
...(full ? { summary: r.summary } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function sweepView(data: NonNullable<Awaited<ReturnType<typeof getSweep>>>, token: TokenIdentity) {
|
||||
const s: SweepRow = data.sweep;
|
||||
return {
|
||||
id: s.id,
|
||||
state: s.state,
|
||||
label: s.label,
|
||||
baseDeploymentId: s.baseDeploymentId,
|
||||
params: s.params,
|
||||
settings: s.settings,
|
||||
requestedBy: s.requestedBy,
|
||||
mine: s.requestedByTokenId === token.id,
|
||||
error: s.error,
|
||||
timeLimitMinutes: s.timeLimitS ? Math.round(s.timeLimitS / 60) : null,
|
||||
variants: s.variants.map((v) => {
|
||||
const run = data.runs.find((r) => r.id === v.runId);
|
||||
const ev = data.runs.find((r) => r.id === v.evalRunId);
|
||||
return {
|
||||
label: v.label,
|
||||
overrides: v.overrides,
|
||||
state: v.state,
|
||||
runId: v.runId ?? null,
|
||||
evalRunId: v.evalRunId ?? null,
|
||||
error: v.error ?? null,
|
||||
...compact(run?.summary ?? null, run?.meta ?? null, ev?.quality ?? null),
|
||||
};
|
||||
}),
|
||||
startedAt: s.startedAt?.toISOString() ?? null,
|
||||
finishedAt: s.finishedAt?.toISOString() ?? null,
|
||||
next: s.state === "pending_approval" ? RUN_NEXT.pending_approval : s.state === "queued" || s.state === "running" ? "Running variant by variant. GET it with ?wait=900 instead of polling." : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Runs side by side: headline numbers and the setup keys whose values differ. */
|
||||
export async function compareRuns(ids: string[]) {
|
||||
const runs = await getBenchmarks(ids);
|
||||
const rows = runs.map((r) => ({ id: r.id, kind: r.kind, label: r.label ?? r.snapshot.deploymentName, state: r.state, ...compact(r.summary, r.meta, r.quality) }));
|
||||
const keys = [...new Set(rows.flatMap((r) => Object.keys(r.setup ?? {})))];
|
||||
const differs = keys.filter((k) => new Set(rows.map((r) => r.setup?.[k] ?? "")).size > 1);
|
||||
return {
|
||||
runs: rows.map((r) => ({ ...r, setup: undefined, differs: Object.fromEntries(differs.map((k) => [k, r.setup?.[k] ?? null])) })),
|
||||
same: Object.fromEntries(keys.filter((k) => !differs.includes(k)).map((k) => [k, rows[0]?.setup?.[k] ?? null])),
|
||||
note: "Headline: decode t/s (weighted), prefill t/s at the deepest prompt, TTFT p50 ms; quality: the eval score 0–100 (same evalSet only). Differences under ~2 % between separate speed runs are noise; use an A/B for small effects.",
|
||||
};
|
||||
}
|
||||
|
||||
/** Recent runs, newest first, optionally of one deployment or token. */
|
||||
export async function listRunsFor(filter: { deploymentId?: string; requestedBy?: string; limit: number }) {
|
||||
const rows = await db()
|
||||
.select({ id: benchmarkRuns.id })
|
||||
.from(benchmarkRuns)
|
||||
.where(
|
||||
and(
|
||||
filter.deploymentId ? or(eq(benchmarkRuns.deploymentId, filter.deploymentId), eq(benchmarkRuns.deploymentBId, filter.deploymentId)) : undefined,
|
||||
filter.requestedBy ? eq(benchmarkRuns.requestedBy, filter.requestedBy.toLowerCase()) : undefined,
|
||||
),
|
||||
)
|
||||
.orderBy(desc(benchmarkRuns.createdAt))
|
||||
.limit(filter.limit);
|
||||
return getBenchmarks(rows.map((r) => r.id));
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { checkArgs, checkHostPort, checkLimits, checkRun, checkStart, checkVram, DEFAULT_TUNING, overTime, parseFlagList, parseTuning, type TuningError } from "./agent-tuning";
|
||||
import { parseWait, waitFor } from "./wait";
|
||||
|
||||
const g = DEFAULT_TUNING;
|
||||
const rejects = (fn: () => void, code: TuningError["code"], message?: RegExp) =>
|
||||
assert.throws(fn, (e: TuningError) => e.code === code && (!message || message.test(e.message)));
|
||||
|
||||
describe("tuning guardrails: settings", () => {
|
||||
it("defaults: approve, 1 deployment, 30/180 min, 8 variants, no ports, no caps", () => {
|
||||
assert.deepEqual(parseTuning(null), DEFAULT_TUNING);
|
||||
assert.equal(g.approvalMode, "approve");
|
||||
assert.equal(g.maxAgentDeployments, 1);
|
||||
assert.equal(g.maxRunMinutes, 30);
|
||||
assert.equal(g.maxSweepMinutes, 180);
|
||||
assert.equal(g.maxSweepVariants, 8);
|
||||
assert.equal(g.hostPortRange, null);
|
||||
});
|
||||
|
||||
it("falls back to defaults for invalid stored values and drops non-flags", () => {
|
||||
const t = parseTuning({ approvalMode: "yolo", maxAgentDeployments: 0, maxSweepVariants: 99, hostPortRange: { from: 9000, to: 80 }, allowedArgs: { "llama.cpp": ["--no-mmap", "rm -rf"], vllm: "x" } });
|
||||
assert.equal(t.approvalMode, "approve");
|
||||
assert.equal(t.maxAgentDeployments, 1);
|
||||
assert.equal(t.maxSweepVariants, 8);
|
||||
assert.equal(t.hostPortRange, null);
|
||||
assert.deepEqual(t.allowedArgs["llama.cpp"], ["--no-mmap"]);
|
||||
assert.deepEqual(t.allowedArgs.vllm, DEFAULT_TUNING.allowedArgs.vllm);
|
||||
assert.deepEqual(parseFlagList("--no-mmap, -ctk --mlock --no-mmap"), ["--no-mmap", "-ctk", "--mlock"]);
|
||||
assert.throws(() => parseFlagList("--ok /etc/passwd"), /isn't a flag/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tuning guardrails: extra arguments", () => {
|
||||
it("passes allowlisted flags with values", () => {
|
||||
checkArgs(g, "llama.cpp", ["--no-mmap", "-ctk", "q8_0", "--override-tensor=blk\\..*_exps=CPU", "-n", "-1"]);
|
||||
checkArgs(g, "vllm", ["--kv-cache-dtype", "fp8", "--enable-prefix-caching"]);
|
||||
});
|
||||
|
||||
it("refuses flags not on the engine's list, naming them", () => {
|
||||
rejects(() => checkArgs(g, "llama.cpp", ["--host", "0.0.0.0"]), "arg_not_allowed", /"--host"/);
|
||||
rejects(() => checkArgs(g, "llama.cpp", ["--api-key=x"]), "arg_not_allowed", /"--api-key"/);
|
||||
rejects(() => checkArgs(g, "llama.cpp", ["-m", "x.gguf"]), "arg_not_allowed", /"-m"/);
|
||||
rejects(() => checkArgs(g, "vllm", ["--trust-remote-code"]), "arg_not_allowed", /"--trust-remote-code"/);
|
||||
rejects(() => checkArgs(g, "vllm", ["--no-mmap"]), "arg_not_allowed", /on vllm/);
|
||||
});
|
||||
|
||||
it("refuses paths, URLs and stray values", () => {
|
||||
rejects(() => checkArgs(g, "llama.cpp", ["--chat-template", "/etc/passwd"]), "arg_not_allowed", /path or URL/);
|
||||
rejects(() => checkArgs(g, "llama.cpp", ["--chat-template=../x"]), "arg_not_allowed", /path or URL/);
|
||||
rejects(() => checkArgs(g, "vllm", ["--compilation-config", "http://evil/x"]), "arg_not_allowed", /path or URL/);
|
||||
rejects(() => checkArgs(g, "llama.cpp", ["q8_0"]), "arg_not_allowed", /isn't a value of a flag/);
|
||||
rejects(() => checkArgs(g, "llama.cpp", ["--no-mmap=1", "extra"]), "arg_not_allowed", /isn't a value/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tuning guardrails: ports and limits", () => {
|
||||
it("allows no host ports unless a range is set", () => {
|
||||
checkHostPort(g, null);
|
||||
rejects(() => checkHostPort(g, 18080), "port_not_allowed", /none configured/);
|
||||
const r = { ...g, hostPortRange: { from: 18000, to: 18099 } };
|
||||
checkHostPort(r, 18080);
|
||||
rejects(() => checkHostPort(r, 19000), "port_not_allowed", /18000–18099/);
|
||||
});
|
||||
|
||||
it("applies the memory cap to the given limit or the estimate, and the CPU cap", () => {
|
||||
const capped = { ...g, maxMemoryMb: 16384, maxCpus: 8 };
|
||||
assert.deepEqual(checkLimits(capped, { memoryMb: null, cpus: null, estimateMb: 9000, hostMemoryMb: 65536, hostCpus: 32 }), { memoryMb: 9000, cpus: 8 });
|
||||
rejects(() => checkLimits(capped, { memoryMb: 20000, cpus: null, estimateMb: 9000, hostMemoryMb: 65536, hostCpus: 32 }), "limit_exceeded", /16384 MiB/);
|
||||
rejects(() => checkLimits(capped, { memoryMb: null, cpus: null, estimateMb: 30000, hostMemoryMb: 65536, hostCpus: 32 }), "limit_exceeded", /the estimate/);
|
||||
rejects(() => checkLimits(capped, { memoryMb: 1024, cpus: 12, estimateMb: 900, hostMemoryMb: 65536, hostCpus: 32 }), "limit_exceeded", /8 cores/);
|
||||
// Without caps, the host's size is the cap.
|
||||
rejects(() => checkLimits(g, { memoryMb: 70000, cpus: null, estimateMb: 1, hostMemoryMb: 65536, hostCpus: 32 }), "limit_exceeded");
|
||||
});
|
||||
});
|
||||
|
||||
describe("tuning guardrails: one GPU job at a time", () => {
|
||||
const idle = { agentDeployments: 0, agentRuns: 0, agentStarting: 0 };
|
||||
it("lets a deployment start when nothing of an agent runs", () => {
|
||||
checkStart(g, idle);
|
||||
checkRun(idle);
|
||||
});
|
||||
|
||||
it("refuses starts while an agent run is open or a deployment is loading, and over the count", () => {
|
||||
rejects(() => checkStart(g, { ...idle, agentRuns: 1 }), "gpu_busy", /benchmark or sweep/);
|
||||
rejects(() => checkStart(g, { ...idle, agentStarting: 1 }), "gpu_busy", /starting/);
|
||||
rejects(() => checkStart(g, { ...idle, agentDeployments: 1 }), "too_many_deployments", /the limit is 1/);
|
||||
checkStart({ ...g, maxAgentDeployments: 2 }, { ...idle, agentDeployments: 1 });
|
||||
});
|
||||
|
||||
it("refuses a second run, and runs while a deployment is loading", () => {
|
||||
rejects(() => checkRun({ ...idle, agentRuns: 1 }), "gpu_busy", /only one at a time/);
|
||||
rejects(() => checkRun({ ...idle, agentStarting: 1 }), "gpu_busy", /still starting/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tuning guardrails: protected deployments' VRAM", () => {
|
||||
it("ignores GPUs without protected deployments", () => {
|
||||
checkVram({ protectedNames: [], newMb: null, runningMb: [30000], totalMb: 32768 });
|
||||
});
|
||||
|
||||
it("refuses what wouldn't fit next to a protected deployment", () => {
|
||||
checkVram({ protectedNames: ["prod"], newMb: 8000, runningMb: [20000], totalMb: 32768 });
|
||||
rejects(() => checkVram({ protectedNames: ["prod"], newMb: 12000, runningMb: [20000], totalMb: 32768 }), "vram_protected", /crowd protected deployment\(s\) prod/);
|
||||
});
|
||||
|
||||
it("refuses when the need can't be estimated", () => {
|
||||
rejects(() => checkVram({ protectedNames: ["prod"], newMb: null, runningMb: [20000], totalMb: 32768 }), "vram_protected", /can't be estimated/);
|
||||
rejects(() => checkVram({ protectedNames: ["prod"], newMb: 1000, runningMb: [-1], totalMb: 32768 }), "vram_protected");
|
||||
rejects(() => checkVram({ protectedNames: ["prod"], newMb: 1000, runningMb: [], totalMb: null }), "vram_protected");
|
||||
});
|
||||
|
||||
it("knows when a run or sweep is over its time limit", () => {
|
||||
const start = new Date(1_000_000);
|
||||
assert.equal(overTime(start, 60, 1_000_000 + 59_000), false);
|
||||
assert.equal(overTime(start, 60, 1_000_000 + 61_000), true);
|
||||
assert.equal(overTime(null, 60), false);
|
||||
assert.equal(overTime(start, null), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("?wait=", () => {
|
||||
it("parses and caps the seconds", () => {
|
||||
assert.equal(parseWait(new URLSearchParams("wait=30")), 30);
|
||||
assert.equal(parseWait(new URLSearchParams("wait=5000")), 900);
|
||||
assert.equal(parseWait(new URLSearchParams("wait=-1")), 0);
|
||||
assert.equal(parseWait(new URLSearchParams("")), 0);
|
||||
});
|
||||
|
||||
it("returns once the state settles", async () => {
|
||||
let n = 0;
|
||||
const r = await waitFor(async () => ++n, (v) => v >= 3, 5, { pollMs: 10 });
|
||||
assert.equal(r.value, 3);
|
||||
assert.equal(r.timedOut, false);
|
||||
});
|
||||
|
||||
it("returns right away when already settled, and after the wait otherwise", async () => {
|
||||
let loads = 0;
|
||||
const now = await waitFor(async () => (loads++, "done"), () => true, 900, { pollMs: 10 });
|
||||
assert.equal(loads, 1);
|
||||
assert.equal(now.waitedS, 0);
|
||||
const t0 = Date.now();
|
||||
const late = await waitFor(async () => "running", () => false, 1, { pollMs: 50 });
|
||||
assert.ok(Date.now() - t0 >= 950);
|
||||
assert.equal(late.timedOut, true);
|
||||
});
|
||||
|
||||
it("stops waiting when the client goes away", async () => {
|
||||
const ac = new AbortController();
|
||||
setTimeout(() => ac.abort(), 50);
|
||||
const t0 = Date.now();
|
||||
await waitFor(async () => "running", () => false, 30, { pollMs: 20, signal: ac.signal });
|
||||
assert.ok(Date.now() - t0 < 1000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,351 @@
|
||||
// Guardrails for deployments and benchmarks requested through the API (an agent tuning launch
|
||||
// options, not a person in the UI). Pure: settings parsing and the checks; the request flows are in
|
||||
// agent-deployments.ts and agent-runs.ts.
|
||||
|
||||
import { APPROVAL_MODES, type ApprovalMode } from "@/lib/agent-guardrails";
|
||||
import type { RuntimeEngine } from "@/lib/db/schema";
|
||||
|
||||
/**
|
||||
* Extra arguments an agent may pass, per engine: tuning flags only. Not allowed (not listed): paths
|
||||
* and files (-m, --log-file, --chat-template-file, --slot-save-path, --download-dir), network and
|
||||
* auth (--host, --port, --api-key, --rpc, --ssl-*), anything that fetches or runs code from
|
||||
* elsewhere (-hf, --model-url, --trust-remote-code, --tokenizer, --speculative-config, --lora).
|
||||
* Docker-level options (devices, volumes, privileges, capabilities, network) aren't arguments at
|
||||
* all: they come from the runtime, which tokens can't change.
|
||||
*/
|
||||
export const DEFAULT_ALLOWED_ARGS: Record<RuntimeEngine, string[]> = {
|
||||
"llama.cpp": [
|
||||
"--no-mmap",
|
||||
"--mlock",
|
||||
"--numa",
|
||||
"-fa",
|
||||
"--flash-attn",
|
||||
"-ctk",
|
||||
"--cache-type-k",
|
||||
"-ctv",
|
||||
"--cache-type-v",
|
||||
"-nkvo",
|
||||
"--no-kv-offload",
|
||||
"-kvu",
|
||||
"--kv-unified",
|
||||
"--no-kv-unified",
|
||||
"--swa-full",
|
||||
"-dt",
|
||||
"--defrag-thold",
|
||||
"-cb",
|
||||
"--cont-batching",
|
||||
"-nocb",
|
||||
"--no-cont-batching",
|
||||
"--cache-reuse",
|
||||
"--context-shift",
|
||||
"--no-context-shift",
|
||||
"-b",
|
||||
"--batch-size",
|
||||
"-ub",
|
||||
"--ubatch-size",
|
||||
"-t",
|
||||
"--threads",
|
||||
"-tb",
|
||||
"--threads-batch",
|
||||
"--prio",
|
||||
"--poll",
|
||||
"-sm",
|
||||
"--split-mode",
|
||||
"-ts",
|
||||
"--tensor-split",
|
||||
"-mg",
|
||||
"--main-gpu",
|
||||
"-ot",
|
||||
"--override-tensor",
|
||||
"--cpu-moe",
|
||||
"-cmoe",
|
||||
"--n-cpu-moe",
|
||||
"-ncmoe",
|
||||
"--rope-scaling",
|
||||
"--rope-scale",
|
||||
"--rope-freq-base",
|
||||
"--rope-freq-scale",
|
||||
"--yarn-orig-ctx",
|
||||
"--yarn-ext-factor",
|
||||
"--yarn-attn-factor",
|
||||
"--yarn-beta-slow",
|
||||
"--yarn-beta-fast",
|
||||
"--draft-max",
|
||||
"--draft-min",
|
||||
"--draft-p-min",
|
||||
"-ngld",
|
||||
"--gpu-layers-draft",
|
||||
"--spec-replace",
|
||||
"--jinja",
|
||||
"--no-jinja",
|
||||
"--chat-template",
|
||||
"--reasoning-format",
|
||||
"--reasoning-budget",
|
||||
"--slot-prompt-similarity",
|
||||
"--temp",
|
||||
"--top-k",
|
||||
"--top-p",
|
||||
"--min-p",
|
||||
"--repeat-penalty",
|
||||
"--presence-penalty",
|
||||
"-n",
|
||||
"--n-predict",
|
||||
"--threads-http",
|
||||
],
|
||||
vllm: [
|
||||
"--kv-cache-dtype",
|
||||
"--max-num-batched-tokens",
|
||||
"--enable-chunked-prefill",
|
||||
"--no-enable-chunked-prefill",
|
||||
"--enable-prefix-caching",
|
||||
"--no-enable-prefix-caching",
|
||||
"--block-size",
|
||||
"--swap-space",
|
||||
"--cpu-offload-gb",
|
||||
"--enforce-eager",
|
||||
"--max-seq-len-to-capture",
|
||||
"--compilation-config",
|
||||
"-O",
|
||||
"--quantization",
|
||||
"-q",
|
||||
"--pipeline-parallel-size",
|
||||
"-pp",
|
||||
"--enable-expert-parallel",
|
||||
"--async-scheduling",
|
||||
"--enable-auto-tool-choice",
|
||||
"--tool-call-parser",
|
||||
"--reasoning-parser",
|
||||
"--max-logprobs",
|
||||
"--seed",
|
||||
"--override-generation-config",
|
||||
"--limit-mm-per-prompt",
|
||||
"--mm-processor-kwargs",
|
||||
"--disable-log-requests",
|
||||
"--disable-log-stats",
|
||||
],
|
||||
};
|
||||
|
||||
export type TuningGuardrails = {
|
||||
/** approve: agent starts, runs and sweeps wait as "pending approval" until someone confirms them. */
|
||||
approvalMode: ApprovalMode;
|
||||
/** Agent deployments running (or waiting to start) at once, all tokens together. */
|
||||
maxAgentDeployments: number;
|
||||
maxRunMinutes: number;
|
||||
maxSweepMinutes: number;
|
||||
maxSweepVariants: number;
|
||||
/** Runtime ids agents may use; empty = every runtime with a pulled image. */
|
||||
allowedRuntimeIds: string[];
|
||||
/** Extra argument flags agents may use, per engine. */
|
||||
allowedArgs: Record<RuntimeEngine, string[]>;
|
||||
/** Host ports agents may publish; null = none (Kaname reaches deployments over the Docker network). */
|
||||
hostPortRange: { from: number; to: number } | null;
|
||||
/** Caps for an agent deployment's limits; null = the host's size. Agent deployments always get a memory limit. */
|
||||
maxMemoryMb: number | null;
|
||||
maxCpus: number | null;
|
||||
};
|
||||
|
||||
export const DEFAULT_TUNING: TuningGuardrails = {
|
||||
approvalMode: "approve",
|
||||
maxAgentDeployments: 1,
|
||||
maxRunMinutes: 30,
|
||||
maxSweepMinutes: 180,
|
||||
maxSweepVariants: 8,
|
||||
allowedRuntimeIds: [],
|
||||
allowedArgs: DEFAULT_ALLOWED_ARGS,
|
||||
hostPortRange: null,
|
||||
maxMemoryMb: null,
|
||||
maxCpus: null,
|
||||
};
|
||||
|
||||
export const TUNING_KEY = "agent.tuning";
|
||||
|
||||
export type TuningErrorCode =
|
||||
| "runtime_not_allowed"
|
||||
| "runtime_not_pulled"
|
||||
| "arg_not_allowed"
|
||||
| "port_not_allowed"
|
||||
| "limit_exceeded"
|
||||
| "too_many_deployments"
|
||||
| "gpu_busy"
|
||||
| "protected"
|
||||
| "not_owner"
|
||||
| "vram_protected"
|
||||
| "too_many_variants"
|
||||
| "approval_pending";
|
||||
|
||||
export class TuningError extends Error {
|
||||
constructor(
|
||||
public code: TuningErrorCode,
|
||||
message: string,
|
||||
public status = 422,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
const FLAG_RE = /^--?[A-Za-z][\w-]*$/;
|
||||
const int = (x: unknown, min: number, max: number, def: number) => (typeof x === "number" && Number.isInteger(x) && x >= min && x <= max ? x : def);
|
||||
const numOrNull = (x: unknown, min: number) => (typeof x === "number" && Number.isFinite(x) && x >= min ? x : null);
|
||||
|
||||
/** Stored value merged over the defaults; anything invalid falls back to the default. */
|
||||
export function parseTuning(v: unknown): TuningGuardrails {
|
||||
const o = (v && typeof v === "object" ? v : {}) as Record<string, unknown>;
|
||||
const args = (o.allowedArgs ?? {}) as Record<string, unknown>;
|
||||
const flags = (x: unknown, def: string[]) => (Array.isArray(x) ? [...new Set(x.filter((f): f is string => typeof f === "string" && FLAG_RE.test(f)))] : def);
|
||||
const range = o.hostPortRange as { from?: unknown; to?: unknown } | null | undefined;
|
||||
const from = int(range?.from, 1024, 65_535, 0);
|
||||
const to = int(range?.to, 1024, 65_535, 0);
|
||||
return {
|
||||
approvalMode: APPROVAL_MODES.includes(o.approvalMode as ApprovalMode) ? (o.approvalMode as ApprovalMode) : DEFAULT_TUNING.approvalMode,
|
||||
maxAgentDeployments: int(o.maxAgentDeployments, 1, 16, DEFAULT_TUNING.maxAgentDeployments),
|
||||
maxRunMinutes: int(o.maxRunMinutes, 1, 24 * 60, DEFAULT_TUNING.maxRunMinutes),
|
||||
maxSweepMinutes: int(o.maxSweepMinutes, 1, 7 * 24 * 60, DEFAULT_TUNING.maxSweepMinutes),
|
||||
maxSweepVariants: int(o.maxSweepVariants, 2, 16, DEFAULT_TUNING.maxSweepVariants),
|
||||
allowedRuntimeIds: Array.isArray(o.allowedRuntimeIds) ? o.allowedRuntimeIds.filter((x): x is string => typeof x === "string" && x.length <= 64) : [],
|
||||
allowedArgs: { "llama.cpp": flags(args["llama.cpp"], DEFAULT_ALLOWED_ARGS["llama.cpp"]), vllm: flags(args.vllm, DEFAULT_ALLOWED_ARGS.vllm) },
|
||||
hostPortRange: from && to && from <= to ? { from, to } : null,
|
||||
maxMemoryMb: numOrNull(o.maxMemoryMb, 256),
|
||||
maxCpus: numOrNull(o.maxCpus, 0.1),
|
||||
};
|
||||
}
|
||||
|
||||
/** "--no-mmap -ctk, --flash-attn" → flags; throws on something that isn't one. */
|
||||
export function parseFlagList(text: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const f of text.split(/[\s,]+/).filter(Boolean)) {
|
||||
if (!FLAG_RE.test(f)) throw new Error(`"${f}" isn't a flag (e.g. --no-mmap).`);
|
||||
if (!out.includes(f)) out.push(f);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra arguments: every flag must be on the engine's allowlist, every value must follow a flag and
|
||||
* may not be a path or URL. The error names the offending argument.
|
||||
*/
|
||||
export function checkArgs(g: TuningGuardrails, engine: RuntimeEngine, args: string[]): void {
|
||||
const allowed = g.allowedArgs[engine];
|
||||
let pending: string | null = null; // a flag still waiting for its value
|
||||
for (const raw of args) {
|
||||
const a = raw.trim();
|
||||
if (!a) continue;
|
||||
if (a.startsWith("-") && !/^-\d/.test(a)) {
|
||||
const flag = a.split("=")[0];
|
||||
if (!allowed.includes(flag)) {
|
||||
throw new TuningError(
|
||||
"arg_not_allowed",
|
||||
`extra argument "${flag}" isn't allowed for agents on ${engine}. The allowed flags are listed per runtime in GET /api/v1/runtimes (allowedExtraArgs); use the structured options (contextSize, gpuLayers, cacheTypeK, …) where there is one.`,
|
||||
403,
|
||||
);
|
||||
}
|
||||
const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : null;
|
||||
if (value != null) checkValue(flag, value);
|
||||
pending = value == null ? flag : null;
|
||||
continue;
|
||||
}
|
||||
if (!pending) throw new TuningError("arg_not_allowed", `extra argument "${a}" isn't a value of a flag. Pass flags as "--flag value" or "--flag=value".`, 403);
|
||||
checkValue(pending, a);
|
||||
pending = null;
|
||||
}
|
||||
}
|
||||
|
||||
function checkValue(flag: string, value: string) {
|
||||
if (/^[/~]|(^|[\\/])\.\.([\\/]|$)|:\/\//.test(value)) {
|
||||
throw new TuningError("arg_not_allowed", `value "${value}" of ${flag} looks like a path or URL; agents can't pass those.`, 403);
|
||||
}
|
||||
}
|
||||
|
||||
/** A host port must be in the configured range (none configured: no host ports for agents). */
|
||||
export function checkHostPort(g: TuningGuardrails, port: number | null | undefined): void {
|
||||
if (port == null) return;
|
||||
const r = g.hostPortRange;
|
||||
if (!r) throw new TuningError("port_not_allowed", "agents can't publish host ports (none configured). Leave hostPort out; Kaname reaches the deployment itself.", 403);
|
||||
if (port < r.from || port > r.to) throw new TuningError("port_not_allowed", `host port ${port} is outside the range agents may use (${r.from}–${r.to}).`, 403);
|
||||
}
|
||||
|
||||
/** Memory and CPU limits within the caps (null cap: the host's size). Returns the memory limit to use. */
|
||||
export function checkLimits(
|
||||
g: TuningGuardrails,
|
||||
x: { memoryMb: number | null | undefined; cpus: number | null | undefined; estimateMb: number; hostMemoryMb: number | null; hostCpus: number | null },
|
||||
): { memoryMb: number; cpus: number | null } {
|
||||
const memCap = g.maxMemoryMb ?? x.hostMemoryMb;
|
||||
const cpuCap = g.maxCpus ?? x.hostCpus;
|
||||
const memoryMb = x.memoryMb ?? x.estimateMb;
|
||||
if (memCap != null && memoryMb > memCap) {
|
||||
throw new TuningError(
|
||||
"limit_exceeded",
|
||||
`memory limit ${memoryMb} MiB exceeds the cap of ${Math.floor(memCap)} MiB for agent deployments${x.memoryMb == null ? " (the estimate for this model and context)" : ""}. Use a smaller quant or context, or ask the user to raise the cap.`,
|
||||
);
|
||||
}
|
||||
if (x.cpus != null && cpuCap != null && x.cpus > cpuCap) throw new TuningError("limit_exceeded", `CPU limit ${x.cpus} exceeds the cap of ${cpuCap} cores for agent deployments.`);
|
||||
return { memoryMb, cpus: x.cpus ?? (g.maxCpus ?? null) };
|
||||
}
|
||||
|
||||
export type GpuLoad = {
|
||||
/** Agent deployments running, starting or waiting to start (all tokens), not counting `self`. */
|
||||
agentDeployments: number;
|
||||
/** Agent runs and sweeps pending approval, queued or running. */
|
||||
agentRuns: number;
|
||||
/** Agent deployments currently starting (loading weights). */
|
||||
agentStarting: number;
|
||||
};
|
||||
|
||||
/** Starting an agent deployment: within the count, and nothing of an agent is being measured or loaded. */
|
||||
export function checkStart(g: TuningGuardrails, load: GpuLoad): void {
|
||||
if (load.agentRuns > 0) {
|
||||
throw new TuningError("gpu_busy", "an agent benchmark or sweep is pending or running; starting a deployment now would disturb it. Wait for it (GET …?wait=) and start afterwards.", 429);
|
||||
}
|
||||
if (load.agentStarting > 0) throw new TuningError("gpu_busy", "another agent deployment is starting; wait until it is running.", 429);
|
||||
if (load.agentDeployments >= g.maxAgentDeployments) {
|
||||
throw new TuningError(
|
||||
"too_many_deployments",
|
||||
`${load.agentDeployments} agent deployment(s) already running or waiting to start; the limit is ${g.maxAgentDeployments}. Stop one of yours first (POST /api/v1/deployments/{id}/stop).`,
|
||||
429,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Starting a run or sweep: one agent run/sweep at a time, and no agent deployment still loading. */
|
||||
export function checkRun(load: GpuLoad): void {
|
||||
if (load.agentRuns > 0) throw new TuningError("gpu_busy", "an agent benchmark or sweep is already pending or running; only one at a time. Wait for it to finish (GET …?wait=).", 429);
|
||||
if (load.agentStarting > 0) throw new TuningError("gpu_busy", "an agent deployment is still starting; wait until it is running.", 429);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starting next to a running protected deployment on the same GPUs: the estimated VRAM of everything
|
||||
* running there plus the new deployment must fit, with a margin, so the protected one isn't pushed out.
|
||||
*/
|
||||
export function checkVram(x: { protectedNames: string[]; newMb: number | null; runningMb: number[]; totalMb: number | null; marginMb?: number }): void {
|
||||
if (x.protectedNames.length === 0) return;
|
||||
const names = x.protectedNames.join(", ");
|
||||
if (x.newMb == null || x.totalMb == null || x.runningMb.some((m) => m < 0)) {
|
||||
throw new TuningError(
|
||||
"vram_protected",
|
||||
`protected deployment(s) ${names} run on these GPUs and the VRAM need can't be estimated (only some layers on the GPU, or VRAM unknown). Use gpuLayers "auto" or "all", or ask the user.`,
|
||||
409,
|
||||
);
|
||||
}
|
||||
const margin = x.marginMb ?? 1024;
|
||||
const used = x.runningMb.reduce((s, m) => s + m, 0);
|
||||
if (used + x.newMb + margin > x.totalMb) {
|
||||
throw new TuningError(
|
||||
"vram_protected",
|
||||
`would crowd protected deployment(s) ${names} out of VRAM: about ${x.newMb} MiB needed, ${used} MiB in use of ${x.totalMb} MiB (keeping ${margin} MiB free). Use a smaller quant or context, or a quantized KV cache.`,
|
||||
409,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Seconds since `startedAt` past the limit? */
|
||||
export const overTime = (startedAt: Date | null, limitS: number | null, now = Date.now()) => !!startedAt && !!limitS && now - startedAt.getTime() > limitS * 1000;
|
||||
|
||||
export function describeTuning(g: TuningGuardrails): string {
|
||||
return [
|
||||
g.approvalMode === "approve" ? "starts, runs and sweeps wait for approval" : "starts, runs and sweeps go ahead",
|
||||
`max ${g.maxAgentDeployments} agent deployment(s)`,
|
||||
"one agent run/sweep at a time",
|
||||
`runs ≤ ${g.maxRunMinutes} min, sweeps ≤ ${g.maxSweepMinutes} min and ${g.maxSweepVariants} variants`,
|
||||
g.allowedRuntimeIds.length ? `${g.allowedRuntimeIds.length} allowed runtime(s)` : "any pulled runtime",
|
||||
g.hostPortRange ? `host ports ${g.hostPortRange.from}–${g.hostPortRange.to}` : "no host ports",
|
||||
].join(" · ");
|
||||
}
|
||||
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user