Compare commits

...
4 Commits
Author SHA1 Message Date
Pascal LinxweilerandClaude Opus 5.5 716bd8f2f0 Release 0.13.0: agent API for deployments and benchmarks
Release / release (push) Successful in 3m0s
Scopes deployments:read/write and benchmarks:read/run; /api/v1 endpoints
for runtimes, deployments (create with dry run, edit, start, stop, delete
own ones), benchmark runs, A/B, sweeps and comparisons; ?wait= on all
status endpoints. Guardrails: approval, agent deployments at once, one
GPU job at a time, time limits, sweep variants, runtime and argument
allowlists, host port range, memory/CPU caps, protected deployments with
a VRAM check. Requested-by filters, approval bars, per-token activity log,
scope editing, docs/agent/SKILL-tuning.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:11:06 +02:00
Pascal LinxweilerandClaude Opus 5.5 e007a35143 Release 0.12.0: Intel GPU support
Release / release (push) Successful in 3m40s
Intel/AMD GPU telemetry in benchmark runs (hwmon power/temperature,
amdgpu sysfs, Intel VRAM/utilization from DRM fdinfo via a minimal
host-PID probe container), temperature for all GPUs, VRAM estimate for
NVIDIA and Intel/AMD in the deployment form, /dev/dri group IDs added to
Intel/AMD runtime containers, Intel llama.cpp presets seeded on first
detection, ZES_ENABLE_SYSMAN=1 for the SYCL preset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 14:47:00 +02:00
Pascal LinxweilerandClaude Opus 5.5 ee6c623e2a Release 0.11.0: benchmark metadata and system info
Release / release (push) Successful in 3m25s
Every run records GPUs (PCIe link under load and maximum, ReBAR, P2P),
runtime image/tag/digest and the engine version the server reports,
model, quant, KV cache, context and concurrency, plus a whitelisted
system summary and a description. Shown on the run page, compare and
sweep views; passed to BetterBench as notes and to the launch80 preview
as sections. Settings -> Hardware for manual values.

Also: scripts/intel-probe.sh (read-only diagnostics for Intel hosts),
and --quick is no longer passed together with --passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:07:04 +02:00
Pascal LinxweilerandClaude Opus 5.5 981c4170fc Agent skill: kaname helper script, declared env vars, less polling
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:24:51 +02:00
103 changed files with 11505 additions and 355 deletions

No files matched your search

+137 -1
View File
@@ -4,7 +4,143 @@ 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.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 &lt;token&gt;**, 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
+4 -1
View File
@@ -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.
+5 -3
View File
@@ -87,9 +87,11 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
[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`, within guardrails you set (approval, max
size, free space, jobs at once, allowed authors). See [docs/api.md](docs/api.md) (also how to let
`/api/v1/` past a forward-auth proxy) and the agent skill [docs/agent/SKILL.md](docs/agent/SKILL.md).
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
+179
View File
@@ -0,0 +1,179 @@
---
name: kaname-tuning
description: Deploy local LLMs on the user's Kaname server and benchmark them 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.
## 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 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,
"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 | VRAM peak | Notes |
| --- | --- | --- | --- | --- | --- |
| f16 | 58.1 | 1910 | 88 | 11.2 GB | baseline |
| q8_0 | 57.6 | 1880 | 90 | 9.4 GB | −1 %, 1.8 GB less VRAM |
Name the winner and why (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. |
+43 -19
View File
@@ -1,29 +1,45 @@
---
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: tell the user when they need one of those.
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
k() { curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" "$@"; }
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
k "$KANAME_URL/api/v1"
kaname "$KANAME_URL/api/v1"
```
Shows your token name, scopes and the guardrails. The defaults:
@@ -37,8 +53,8 @@ Shows your token name, scopes and the guardrails. The defaults:
## 1. Is it already here?
```bash
k "$KANAME_URL/api/v1/models?q=qwen3%208b"
k "$KANAME_URL/api/v1/models?author=unsloth&quant=Q4_K_M&status=ready"
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).
@@ -47,14 +63,14 @@ If the model is there with `status: ready`, you're done. Don't request it again.
## 2. Look up the repo
```bash
k "$KANAME_URL/api/v1/hub/lookup?repo=unsloth/Qwen3-8B-GGUF"
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
k "$KANAME_URL/api/v1/disk" # availableForRequests = what a request may still use
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.
@@ -62,7 +78,7 @@ If `gated` is not `false`, the download only works if the user's Hugging Face ac
## 3. Request the download
```bash
k -X POST "$KANAME_URL/api/v1/downloads" \
kaname -X POST "$KANAME_URL/api/v1/downloads" \
-d '{"repoId":"unsloth/Qwen3-8B-GGUF","sha":"<sha from lookup>","quant":"Q4_K_M"}'
```
@@ -80,17 +96,25 @@ Answer:
## 4. Follow it
```bash
k "$KANAME_URL/api/v1/jobs/<jobId>"
kaname -m 660 "$KANAME_URL/api/v1/jobs/<jobId>?wait=600"
```
`state`: `pending_approval` → `queued` → `downloading` → `verifying` → `completed`. `progress.percent`
and `etaSeconds` show how far it is; `next` says what to do. Poll gently: every few minutes while
pending, about once a minute while downloading. Add `?log=20` only when you need to explain a
failure.
`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:
- `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.
- **`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
@@ -98,12 +122,12 @@ failure.
| --- | --- |
| `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` | Wait until one of your downloads has finished, then try again. Don't spin. |
| `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; wait for it. |
| `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; try again later or tell the user. |
| `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).
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
exec curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" "$@"
+162 -12
View File
@@ -1,16 +1,17 @@
# Kaname API (`/api/v1`)
A small JSON API for programs and AI agents: look up Hugging Face repos, list the local library,
request downloads and follow them. Everything an agent can do here is bounded by
[guardrails](#guardrails); it can't delete models or files, change settings, or manage runtimes or
tokens.
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)
- [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)
@@ -27,6 +28,13 @@ Authorization: Bearer kn_…
| --- | --- |
| `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.
@@ -44,12 +52,12 @@ Errors are JSON with a message meant to be read and acted on:
| Status | Codes |
| --- | --- |
| 400 | `invalid_request`, `invalid_json`, `empty_selection` (quant or globs match nothing), `invalid_repo_id` |
| 401 / 403 | `unauthorized`, `forbidden` (scope), `author_not_allowed`, `gated_no_token`, `gated_no_access` |
| 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` (the model has an open job) |
| 422 | `too_large` |
| 429 | `too_many_jobs`, `rate_limited` (Hugging Face) |
| 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).
@@ -136,7 +144,7 @@ curl -s -X POST -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: appli
```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: check GET /api/v1/jobs/01M… every few minutes." }
"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`).
@@ -149,7 +157,7 @@ curl -s -X POST -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: appli
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}[?log=N]`
### `GET /api/v1/jobs/{id}[?wait=S][&log=N]`
`models:read`. Compact job state:
@@ -166,7 +174,8 @@ that commit; the client's list isn't trusted).
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).
`?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`
@@ -181,8 +190,117 @@ States: `pending_approval`, `queued`, `downloading`, `verifying`, `completed`, `
`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) or `ab` (paired A/B with `deploymentBId`, same model; needs 2 agent deployments) |
| `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 |
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).
`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}`.
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.
## 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.
@@ -197,6 +315,38 @@ downloads started in the UI aren't affected.
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
+7
View File
@@ -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;
+25
View File
@@ -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;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+14
View File
@@ -127,6 +127,20 @@
"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
}
]
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "kaname",
"version": "0.10.0",
"version": "0.13.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kaname",
"version": "0.10.0",
"version": "0.13.0",
"dependencies": {
"@base-ui/react": "^1.8.0",
"@libsql/client": "^0.18.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "kaname",
"version": "0.10.0",
"version": "0.13.0",
"private": true,
"scripts": {
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
+86
View File
@@ -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
@@ -33,7 +33,10 @@ 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 { BenchmarkReport } from "./benchmark-report";
import { PublishCard } from "./publish-card";
@@ -58,7 +61,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;
@@ -81,6 +85,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
deploymentId: r.deploymentId,
deploymentBId: r.kind === "ab" ? r.deploymentBId : null,
label: r.label,
description: r.description,
...r.settings,
}),
});
@@ -117,6 +122,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 ? (
@@ -262,6 +268,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" : "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" />
@@ -318,6 +331,30 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
/>
</CardContent>
</Card>
<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 === "run" && (
<Card size="sm">
<CardHeader>
@@ -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>
+1
View File
@@ -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 });
+138 -33
View File
@@ -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,64 @@ 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">
{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>
);
+28
View File
@@ -4,6 +4,7 @@ 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 { CONFIG_ROWS, deltaPct, describeSettings, headline } from "@/lib/benchmark-view";
import type { BenchmarkSummary } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
@@ -62,6 +63,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 },
],
@@ -87,6 +89,10 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
];
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 +128,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 &amp; 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
@@ -9,13 +9,16 @@ 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, 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 };
export type SweepData = { sweep: Sweep; runs: Run[] };
const VARIANT_STATE: Record<SweepVariant["state"], string> = {
@@ -37,6 +40,8 @@ type Row = {
cpu: number | null;
ram: number | null;
vram: number | null;
power: number | null;
temp: number | null;
};
function rowsOf(data: SweepData): Row[] {
@@ -54,11 +59,27 @@ 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,
};
});
}
/**
* 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 +92,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 +116,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,6 +127,8 @@ 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),
};
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 +155,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 +182,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 +215,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,6 +230,11 @@ 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>
<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>
@@ -197,10 +242,12 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
<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,6 +263,11 @@ 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))}
{cell(r.ttft, bestOf.ttft, (x) => x.toFixed(0))}
{cell(r.prefill, bestOf.prefill, (x) => x.toFixed(0))}
@@ -223,6 +275,8 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
{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>
@@ -34,6 +34,7 @@ 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);
@@ -73,7 +74,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}`);
@@ -138,6 +139,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 +197,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"}
@@ -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
@@ -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
+161 -58
View File
@@ -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>
);
}
+35 -4
View File
@@ -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,
};
}
+12 -3
View File
@@ -1,18 +1,27 @@
import type { Metadata } from "next";
import { listActivity } from "@/lib/agent-activity";
import { listTokens } from "@/lib/api-tokens";
import { getGuardrails } from "@/lib/settings";
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] = await Promise.all([listTokens(), getGuardrails()]);
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} />
<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>
);
}
@@ -1,6 +1,7 @@
"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";
@@ -19,7 +20,13 @@ import {
} 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 {
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";
@@ -27,25 +34,43 @@ 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 }: { tokens: ApiTokenRow[] }) {
const [created, setCreated] = useState<{ name: string; token: string } | null>(null);
export function TokenSettings({
tokens,
activity,
}: {
tokens: ApiTokenRow[];
activity: Record<string, ActivityItem[]>;
}) {
const [created, setCreated] = useState<{
name: string;
token: string;
} | null>(null);
return (
<Card>
<CardHeader>
<CardTitle>API tokens</CardTitle>
<CardDescription>
For programs and agents calling Kaname&apos;s API at <code className="font-mono text-xs">/api/v1</code> with{" "}
<code className="font-mono text-xs">Authorization: Bearer &lt;token&gt;</code>. No token can delete models or files, change settings, or manage runtimes and
tokens.
For programs and agents calling Kaname&apos;s API at{" "}
<code className="font-mono text-xs">/api/v1</code> with{" "}
<code className="font-mono text-xs">
Authorization: Bearer &lt;token&gt;
</code>
. No token can delete models or files, change settings, or manage
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 &ldquo;{created.name}&rdquo; created. Copy it now: it is not shown again.</p>
<p className="text-sm font-medium">
Token &ldquo;{created.name}&rdquo; created. Copy it now: it is not
shown again.
</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 rounded-md bg-muted px-2 py-1 font-mono text-xs break-all">{created.token}</code>
<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>
@@ -55,7 +80,7 @@ export function TokenSettings({ tokens }: { tokens: ApiTokenRow[] }) {
) : (
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{tokens.map((t) => (
<TokenRow key={t.id} token={t} />
<TokenRow key={t.id} token={t} activity={activity[t.id] ?? []} />
))}
</div>
)}
@@ -64,7 +89,11 @@ export function TokenSettings({ tokens }: { tokens: ApiTokenRow[] }) {
);
}
function NewTokenForm({ onCreated }: { onCreated: (t: { name: string; token: string }) => void }) {
function NewTokenForm({
onCreated,
}: {
onCreated: (t: { name: string; token: string }) => void;
}) {
const router = useRouter();
const [name, setName] = useState("");
const [scopes, setScopes] = useState<TokenScope[]>(["models:read"]);
@@ -74,9 +103,16 @@ function NewTokenForm({ onCreated }: { onCreated: (t: { name: string; token: str
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 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})`);
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();
@@ -86,93 +122,269 @@ function NewTokenForm({ onCreated }: { onCreated: (t: { name: string; token: str
}
return (
<form onSubmit={create} className="flex flex-col gap-3 rounded-lg border border-dashed px-4 py-3">
<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, ""))}
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}>
<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" />
<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 className="text-xs text-muted-foreground">
{SCOPE_LABEL[s]}
</span>
</span>
</label>
))}
</div>
<p className="text-xs text-muted-foreground">The name is shown as &ldquo;requested by&rdquo; on everything the token asks for.</p>
<p className="text-xs text-muted-foreground">
The name is shown as &ldquo;requested by&rdquo; on everything the token
asks for.
</p>
</form>
);
}
function TokenRow({ token }: { token: ApiTokenRow }) {
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`);
else
toast.success(
method === "POST"
? `Token "${token.name}" revoked`
: `Token "${token.name}" deleted`,
);
router.refresh();
}
return (
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-2.5">
<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"
<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>
)}
</span>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="ghost" size="sm" />}>{revoked ? <Trash2Icon /> : "Revoke"}</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{revoked ? "Delete" : "Revoke"} token &ldquo;{token.name}&rdquo;?
</AlertDialogTitle>
<AlertDialogDescription>
{revoked
? "The entry goes away and the name can be used again. Models it requested keep their “requested by” label."
: "It stops working immediately. Downloads it already requested are not affected."}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={() => act(revoked ? "DELETE" : "POST")}>
{revoked ? "Delete" : "Revoke"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{!revoked && (
<Button
variant="ghost"
size="sm"
onClick={() => setEditing((v) => !v)}
>
Scopes
</Button>
)}
<AlertDialog>
<AlertDialogTrigger render={<Button variant="ghost" size="sm" />}>
{revoked ? <Trash2Icon /> : "Revoke"}
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{revoked ? "Delete" : "Revoke"} token &ldquo;{token.name}
&rdquo;?
</AlertDialogTitle>
<AlertDialogDescription>
{revoked
? "The entry goes away and the name can be used again. Models it requested keep their “requested by” label."
: "It stops working immediately. Downloads it already requested are not affected."}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={() => act(revoked ? "DELETE" : "POST")}
>
{revoked ? "Delete" : "Revoke"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
{editing && (
<div className="flex flex-col gap-2 rounded-lg border p-3">
{TOKEN_SCOPES.map((s) => (
<label
key={s}
className="flex cursor-pointer items-start gap-2 text-sm"
>
<Checkbox
checked={scopes.includes(s)}
onCheckedChange={(v) =>
setScopes((cur) =>
v ? [...cur, s] : cur.filter((x) => x !== s),
)
}
className="mt-0.5"
/>
<span className="flex flex-col">
<span className="font-mono text-xs">{s}</span>
<span className="text-xs text-muted-foreground">
{SCOPE_LABEL[s]}
</span>
</span>
</label>
))}
<Button
size="sm"
className="self-start"
disabled={scopes.length === 0}
onClick={saveScopes}
>
Save scopes
</Button>
</div>
)}
{showActivity && <ActivityList items={activity} />}
</div>
);
}
export type ActivityItem = {
id: string;
action: string;
targetType: string | null;
targetId: string | null;
outcome: string;
code: string | null;
message: string | null;
createdAt: string;
};
const TARGET_HREF: Record<string, (id: string) => string> = {
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&apos;s page), and can&apos;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 &ldquo;deployments at once&rdquo; 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>
);
}
+23
View File
@@ -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}
/>
);
}
+2 -1
View File
@@ -1,4 +1,4 @@
import { BotIcon, 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,6 +6,7 @@ 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/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" /> },
];
@@ -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>
);
}
+15 -1
View File
@@ -1,7 +1,8 @@
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 } from "@/lib/api-tokens";
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 }) => {
@@ -14,6 +15,19 @@ export const POST = withAuth<RouteContext<"/api/api-tokens/[id]">>(async (_req,
}
});
/** 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 {
@@ -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);
}
});
+4 -4
View File
@@ -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);
}
});
+18
View File
@@ -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);
}
});
+35
View File
@@ -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);
}
});
+16
View File
@@ -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);
}
});
+16
View File
@@ -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);
}
});
+23
View File
@@ -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, { token }) => {
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, token));
} catch (err) {
return v1Catch(err);
}
});
+38
View File
@@ -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 benchmark run (kind "run") or a paired A/B (kind "ab") 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);
}
});
+59
View File
@@ -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);
}
});
+44
View File
@@ -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);
}
});
+5 -1
View File
@@ -1,4 +1,5 @@
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";
@@ -25,7 +26,10 @@ const Body = z
export const POST = withToken("downloads:create", async (req, { token }) => {
try {
const body = Body.parse(await req.json());
const r = await requestDownload(token, body);
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,
+14 -6
View File
@@ -1,15 +1,16 @@
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; check again in a few minutes.",
queued: "Waiting for a free download slot.",
downloading: "Downloading; check again in a minute.",
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.",
@@ -17,13 +18,19 @@ const NEXT: Record<string, string> = {
interrupted: "Interrupted by a Kaname restart; the user can resume it.",
};
/** Job state with per-file progress. The hf log only with ?log=N (last N lines, max 200). */
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 job = await getJob(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(new URL(req.url).searchParams.get("log")) || 0));
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({
@@ -50,6 +57,7 @@ export const GET = withToken<RouteContext<"/api/v1/jobs/[id]">>("models:read", a
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) {
+32 -3
View File
@@ -1,12 +1,12 @@
import { withToken } from "@/lib/api-tokens";
import { size, v1Json } from "@/lib/api-v1";
import { getGuardrails } from "@/lib/settings";
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 = await getGuardrails();
const [g, t] = await Promise.all([getGuardrails(), getTuning()]);
return v1Json({
token: { name: token.name, scopes: token.scopes },
guardrails: {
@@ -18,13 +18,42 @@ export const GET = withToken(null, async (_req, { token }) => {
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}[?log=50]",
"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",
],
});
});
+33
View File
@@ -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);
}
});
+19
View File
@@ -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);
}
});
+29
View File
@@ -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);
}
});
+44
View File
@@ -5,6 +5,7 @@ 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. */
@@ -54,3 +55,46 @@ export function ApprovalBar({ job, onRemoved }: { job: { id: string; requestedBy
</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>
);
}
+7 -4
View File
@@ -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 -1
View File
@@ -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" />}
+52
View File
@@ -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 &amp; 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>
);
}
+5 -1
View File
@@ -1,6 +1,6 @@
"use client";
import { BotIcon, 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,6 +71,10 @@ 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 />
Runtime API keys
+66
View File
@@ -0,0 +1,66 @@
import "server-only";
import { desc, eq } from "drizzle-orm";
import type { TokenIdentity } from "@/lib/api-tokens";
import { db } from "@/lib/db/client";
import { agentActivity } from "@/lib/db/schema";
export type ActivityOutcome = "ok" | "pending_approval" | "refused";
/** Record what a token did (or was refused); never fails the request it belongs to. */
export async function logActivity(
token: TokenIdentity,
action: string,
x: { targetType?: string; targetId?: string | null; outcome: ActivityOutcome; code?: string | null; message?: string | null },
): Promise<void> {
try {
await db()
.insert(agentActivity)
.values({
tokenId: token.id,
tokenName: token.name,
action,
targetType: x.targetType ?? null,
targetId: x.targetId ?? null,
outcome: x.outcome,
code: x.code ?? null,
message: x.message?.slice(0, 500) ?? null,
});
} catch (err) {
console.error("[agent-activity]", err);
}
}
export type ActivityRow = typeof agentActivity.$inferSelect;
export async function listActivity(tokenId: string, limit = 100): Promise<ActivityRow[]> {
return db().select().from(agentActivity).where(eq(agentActivity.tokenId, tokenId)).orderBy(desc(agentActivity.createdAt)).limit(limit);
}
/** An error with a code and an HTTP status below 500: a refusal the agent caused, worth logging. */
function refusal(err: unknown): { code: string; message: string } | null {
const e = err as { code?: unknown; status?: unknown; message?: unknown };
if (typeof e?.code === "string" && typeof e.status === "number" && e.status < 500) return { code: e.code, message: String(e.message ?? "") };
if (err instanceof Error && err.name === "ZodError") return { code: "invalid_request", message: err.message.slice(0, 300) };
return null;
}
/**
* Run an agent action and record it: ok, pending approval (when the result's state says so) or
* refused with the error code. The error is rethrown for the route to answer.
*/
export async function act<T extends object>(token: TokenIdentity, action: string, target: { type: string; id?: string | null }, fn: () => Promise<T>): Promise<T> {
try {
const r = await fn();
const { id, state } = r as { id?: unknown; state?: unknown };
await logActivity(token, action, {
targetType: target.type,
targetId: target.id ?? (typeof id === "string" ? id : null),
outcome: state === "pending_approval" ? "pending_approval" : "ok",
});
return r;
} catch (err) {
const why = refusal(err);
if (why) await logActivity(token, action, { targetType: target.type, targetId: target.id ?? null, outcome: "refused", code: why.code, message: why.message });
throw err;
}
}
+293
View File
@@ -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;
}
+2 -2
View File
@@ -55,9 +55,9 @@ export async function openAgentJobs(): Promise<number> {
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: check GET /api/v1/jobs/{jobId} every few minutes.`;
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"}; poll GET /api/v1/jobs/{jobId} for progress.`;
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.`;
}
+258
View File
@@ -0,0 +1,258 @@
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, 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({
kind: z.enum(["run", "ab"]).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(),
})
.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([]),
})
.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,
}),
{ 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 },
{
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);
/** Headline numbers + the setup (section 1 metadata) as key/value. */
function compact(summary: BenchmarkSummary | null, meta: RunMeta | null) {
const h = headline(summary);
return {
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.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);
return { label: v.label, overrides: v.overrides, state: v.state, runId: v.runId ?? null, error: v.error ?? null, ...compact(run?.summary ?? null, run?.meta ?? 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[], token: TokenIdentity) {
const runs = await getBenchmarks(ids);
const rows = runs.map((r) => ({ id: r.id, label: r.label ?? r.snapshot.deploymentName, state: r.state, ...compact(r.summary, r.meta) }));
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. Differences under ~2 % between separate runs are noise; use an A/B for small effects.",
tokenName: token.name,
};
}
/** 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));
}
+155
View File
@@ -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);
});
});
+351
View File
@@ -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(" · ");
}
+12
View File
@@ -54,6 +54,18 @@ export async function revokeToken(id: string): Promise<void> {
if (res.length === 0) throw new TokenError("not_found", "Token not found or already revoked.", 404);
}
/** Change what an active token may do (takes effect on its next request). */
export async function updateTokenScopes(id: string, scopes: string[]): Promise<void> {
const s = [...new Set(scopes)];
if (s.length === 0 || !s.every(isScope)) throw new TokenError("invalid", "Pick at least one valid scope.");
const res = await db()
.update(apiTokens)
.set({ scopes: s as TokenScope[] })
.where(and(eq(apiTokens.id, id), isNull(apiTokens.revokedAt)))
.returning({ id: apiTokens.id });
if (res.length === 0) throw new TokenError("not_found", "Token not found or revoked.", 404);
}
/** Only revoked tokens can be deleted (frees the name; "requested by" labels keep it). */
export async function deleteToken(id: string): Promise<void> {
const res = await db().delete(apiTokens).where(and(eq(apiTokens.id, id), isNotNull(apiTokens.revokedAt))).returning({ id: apiTokens.id });
+535
View File
@@ -0,0 +1,535 @@
// /api/v1 deployments and benchmarks end to end against a temporary SQLite database (no worker, no
// Docker: deployment states are set directly). Scopes, ownership, protected deployments, every
// guardrail rejection, approval, the activity log and ?wait=.
// Runs with `--conditions=react-server` (see package.json) so "server-only" modules load.
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, beforeEach, describe, it } from "node:test";
import { eq, isNotNull } from "drizzle-orm";
const dir = mkdtempSync(join(tmpdir(), "kaname-agent-"));
process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
process.env.MODELS_DIR = join(dir, "models");
const GiB = 2 ** 30;
type Mods = {
db: typeof import("./db/client");
schema: typeof import("./db/schema");
tokens: typeof import("./api-tokens");
settings: typeof import("./settings");
deployments: typeof import("./deployments");
v1: typeof import("../app/api/v1/route");
runtimes: typeof import("../app/api/v1/runtimes/route");
deps: typeof import("../app/api/v1/deployments/route");
dep: typeof import("../app/api/v1/deployments/[id]/route");
start: typeof import("../app/api/v1/deployments/[id]/start/route");
stop: typeof import("../app/api/v1/deployments/[id]/stop/route");
runs: typeof import("../app/api/v1/benchmarks/route");
run: typeof import("../app/api/v1/benchmarks/[id]/route");
cancel: typeof import("../app/api/v1/benchmarks/[id]/cancel/route");
compare: typeof import("../app/api/v1/benchmarks/compare/route");
sweeps: typeof import("../app/api/v1/sweeps/route");
};
let M: Mods;
let hermes: string; // all scopes
let other: string; // all scopes, another agent
let downloadsOnly: string; // the 0.10 scopes
let modelId: string;
let sycl: string; // llama.cpp on /dev/dri, pulled
let notPulled: string;
let userProtected: string; // the user's own, protected, running on the GPU
type Res = { status: number; body: Record<string, any> }; // eslint-disable-line @typescript-eslint/no-explicit-any
const call = async (handler: (req: Request, ctx: never) => Promise<Response>, path: string, opts: { token?: string; method?: string; body?: unknown; params?: Record<string, string> } = {}): Promise<Res> => {
const req = new Request(`http://kaname.test${path}`, {
method: opts.method ?? (opts.body ? "POST" : "GET"),
headers: { ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}), "Content-Type": "application/json" },
body: opts.body ? JSON.stringify(opts.body) : undefined,
});
const res = await handler(req, { params: Promise.resolve(opts.params ?? {}) } as never);
return { status: res.status, body: (await res.json()) as Res["body"] };
};
const deployBody = (o: Record<string, unknown> = {}) => ({
runtimeId: sycl,
modelId,
options: { modelFile: "Small-Q4_K_M.gguf", contextSize: 8192, extraArgs: [] as string[], ...((o.options as object) ?? {}) },
...Object.fromEntries(Object.entries(o).filter(([k]) => k !== "options")),
});
const create = (o: Record<string, unknown> = {}, token = hermes) => call(M.deps.POST, "/api/v1/deployments", { token, body: deployBody(o) });
const setState = async (id: string, state: "running" | "stopped" | "starting", desired: "running" | "stopped" = state === "stopped" ? "stopped" : "running") => {
await M.db
.db()
.update(M.schema.deployments)
.set({ state, desiredState: desired, startRequestedAt: null, containerName: state === "running" ? `kaname-test-${id.slice(-6)}` : null })
.where(eq(M.schema.deployments.id, id));
};
const tuning = (t: Record<string, unknown>) => M.settings.saveTuning(t);
before(async () => {
const { runMigrations } = await import("./db/migrate");
await runMigrations();
M = {
db: await import("./db/client"),
schema: await import("./db/schema"),
tokens: await import("./api-tokens"),
settings: await import("./settings"),
deployments: await import("./deployments"),
v1: await import("../app/api/v1/route"),
runtimes: await import("../app/api/v1/runtimes/route"),
deps: await import("../app/api/v1/deployments/route"),
dep: await import("../app/api/v1/deployments/[id]/route"),
start: await import("../app/api/v1/deployments/[id]/start/route"),
stop: await import("../app/api/v1/deployments/[id]/stop/route"),
runs: await import("../app/api/v1/benchmarks/route"),
run: await import("../app/api/v1/benchmarks/[id]/route"),
cancel: await import("../app/api/v1/benchmarks/[id]/cancel/route"),
compare: await import("../app/api/v1/benchmarks/compare/route"),
sweeps: await import("../app/api/v1/sweeps/route"),
} as Mods;
const scopes = ["models:read", "downloads:create", "deployments:read", "deployments:write", "benchmarks:read", "benchmarks:run"];
hermes = (await M.tokens.createToken("hermes", scopes)).token;
other = (await M.tokens.createToken("other", scopes)).token;
downloadsOnly = (await M.tokens.createToken("old", ["models:read", "downloads:create"])).token;
const d = M.db.db();
const s = M.schema;
const now = new Date();
await d.insert(s.workerState).values({
id: "worker",
startedAt: now,
heartbeatAt: now,
docker: {
connected: true,
error: null,
serverVersion: "29",
os: "Debian",
architecture: "x86_64",
cpus: 32,
memoryBytes: 64 * GiB,
cpuModel: null,
cpuFeatures: [],
network: "kaname_default",
modelsSource: { type: "bind", source: "/srv/models" },
hardware: {
gpus: [{ vendor: "intel", pciAddress: "0000:03:00.0", name: "Intel Arc Pro B65", vramMb: 32768, driver: "xe", driverVersion: null, linkCurrent: null, linkMax: null, barMb: 32768, rebar: true }],
p2p: null,
cpu: { model: null, cores: 16, threads: 32 },
memoryBytes: 64 * GiB,
kernel: null,
virtualization: { vm: true, hypervisor: "KVM/QEMU" },
storage: null,
checkedAt: now.toISOString(),
},
checkedAt: now.toISOString(),
},
});
const [model] = await d.insert(s.models).values({ repoId: "unsloth/Test-GGUF", pinnedSha: "a".repeat(40), localPath: "unsloth/Test-GGUF", status: "ready" }).returning();
modelId = model.id;
await d.insert(s.modelFiles).values([
{ modelId, path: "Small-Q4_K_M.gguf", size: 4 * GiB, selected: true, state: "present" },
{ modelId, path: "Big-Q8_0.gguf", size: 20 * GiB, selected: true, state: "present" },
]);
const [rt] = await d.insert(s.runtimes).values({ name: "llama.cpp (Intel SYCL)", engine: "llama.cpp", accelerator: "dri", image: "ghcr.io/ggml-org/llama.cpp:server-intel", imageState: "present" }).returning();
sycl = rt.id;
const [missing] = await d.insert(s.runtimes).values({ name: "vLLM (XPU)", engine: "vllm", accelerator: "dri", image: "vllm/vllm-openai-xpu:v0.31.0", imageState: "missing" }).returning();
notPulled = missing.id;
// The user's production deployment: 4 GiB model + KV at 32k ≈ 10 GiB of VRAM.
const [prod] = await d
.insert(s.deployments)
.values({ name: "prod", runtimeId: sycl, modelId, options: { modelFile: "Small-Q4_K_M.gguf", contextSize: 32768, extraArgs: [] }, state: "running", desiredState: "running", protected: true })
.returning();
userProtected = prod.id;
});
after(() => {
(globalThis as { __kanameDb?: { client?: { close(): void } } }).__kanameDb?.client?.close();
try {
rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
} catch {
// Windows may still hold the WAL file for a moment.
}
});
/** Each test starts from: approval "approve", default limits, no agent deployments or runs. */
beforeEach(async () => {
if (!M) return;
const d = M.db.db();
const s = M.schema;
await M.settings.saveTuning({ ...(await import("./agent-tuning")).DEFAULT_TUNING });
await d.delete(s.deployments).where(isNotNull(s.deployments.requestedByTokenId));
await d.delete(s.benchmarkRuns);
await d.delete(s.benchmarkSweeps);
});
describe("scopes", () => {
it("tokens from before 0.13 can't touch deployments or benchmarks", async () => {
assert.equal((await call(M.deps.GET, "/api/v1/deployments", { token: downloadsOnly })).status, 403);
assert.equal((await call(M.runtimes.GET, "/api/v1/runtimes", { token: downloadsOnly })).status, 403);
const r = await call(M.deps.POST, "/api/v1/deployments", { token: downloadsOnly, body: deployBody() });
assert.equal(r.status, 403);
assert.match(r.body.error.message, /deployments:write/);
assert.equal((await call(M.runs.GET, "/api/v1/benchmarks", { token: downloadsOnly })).status, 403);
assert.equal((await call(M.runs.POST, "/api/v1/benchmarks", { token: downloadsOnly, body: { deploymentId: "x" } })).status, 403);
assert.equal((await call(M.sweeps.POST, "/api/v1/sweeps", { token: downloadsOnly, body: {} })).status, 403);
});
it("read scopes don't allow writing", async () => {
const reader = (await M.tokens.createToken("reader", ["deployments:read", "benchmarks:read"])).token;
assert.equal((await call(M.deps.GET, "/api/v1/deployments", { token: reader })).status, 200);
assert.equal((await call(M.deps.POST, "/api/v1/deployments", { token: reader, body: deployBody() })).status, 403);
assert.equal((await call(M.start.POST, "/x", { token: reader, params: { id: userProtected } })).status, 403);
assert.equal((await call(M.runs.POST, "/api/v1/benchmarks", { token: reader, body: { deploymentId: userProtected } })).status, 403);
});
it("lists pulled runtimes with what agents may use", async () => {
const r = await call(M.runtimes.GET, "/api/v1/runtimes", { token: hermes });
assert.equal(r.status, 200);
assert.deepEqual(r.body.runtimes.map((x: { id: string }) => x.id), [sycl]);
assert.ok(r.body.runtimes[0].allowedExtraArgs.includes("--no-mmap"));
assert.equal(r.body.gpus[0].name, "Intel Arc Pro B65");
});
});
describe("creating deployments", () => {
it("dry run: the command and estimates, nothing created", async () => {
const r = await create({ dryRun: true, options: { cacheTypeK: "q8_0", cacheTypeV: "q8_0" } });
assert.equal(r.status, 200);
assert.equal(r.body.dryRun, true);
assert.match(r.body.command, /docker run .*llama\.cpp:server-intel .*-c 8192 .*-ctk q8_0/);
assert.ok(r.body.estimates.vramMb > 4096 && r.body.estimates.vramMb < 32768);
assert.equal(r.body.estimates.gpuVramMb, 32768);
assert.ok(r.body.limits.memoryMb > 0);
assert.equal((await call(M.deps.GET, "/api/v1/deployments?mine=1", { token: hermes })).body.count, 0);
});
it("waits for approval by default and records who asked", async () => {
const r = await create();
assert.equal(r.status, 201);
assert.equal(r.body.state, "pending_approval");
assert.match(r.body.message, /approval/);
const d = await M.deployments.getDeployment(r.body.id);
assert.equal(d?.desiredState, "stopped");
assert.ok(d?.startRequestedAt);
assert.equal(d?.requestedBy, "hermes");
assert.ok(d?.memoryMb, "agent deployments always get a memory limit");
const view = await call(M.dep.GET, "/x", { token: hermes, params: { id: r.body.id } });
assert.equal(view.body.state, "pending_approval");
assert.equal(view.body.mine, true);
// The user approves (Start in the UI): it starts.
await M.deployments.setDesiredState(r.body.id, "running");
assert.equal((await M.deployments.getDeployment(r.body.id))?.desiredState, "running");
});
it("starts right away in automatic mode", async () => {
await tuning({ approvalMode: "auto" });
const r = await create();
assert.equal(r.body.state, "starting");
assert.equal((await M.deployments.getDeployment(r.body.id))?.desiredState, "running");
});
it("can be created stopped", async () => {
const r = await create({ start: false });
assert.equal(r.body.state, "stopped");
});
it("rejects unknown fields instead of ignoring them", async () => {
const r = await create({ options: { gpuLayerz: "all" } });
assert.equal(r.status, 400);
assert.equal(r.body.error.code, "invalid_request");
assert.match(r.body.error.message, /gpuLayerz/);
});
});
describe("deployment guardrails", () => {
it("runtime not pulled / not on the allowlist", async () => {
const r = await create({ runtimeId: notPulled, options: { modelFile: "" } });
assert.equal(r.body.error.code, "runtime_not_pulled");
await tuning({ allowedRuntimeIds: ["something-else"] });
const a = await create();
assert.equal(a.status, 403);
assert.equal(a.body.error.code, "runtime_not_allowed");
});
it("extra arguments outside the allowlist, naming the argument", async () => {
const r = await create({ options: { extraArgs: ["--host", "0.0.0.0"] } });
assert.equal(r.status, 403);
assert.equal(r.body.error.code, "arg_not_allowed");
assert.match(r.body.error.message, /"--host"/);
const p = await create({ options: { extraArgs: ["--chat-template", "/models/../etc/passwd"] } });
assert.equal(p.body.error.code, "arg_not_allowed");
assert.equal((await create({ dryRun: true, options: { extraArgs: ["--no-mmap", "-ctk", "q8_0"] } })).status, 200);
});
it("host ports outside the configured range", async () => {
const r = await create({ hostPort: 18080 });
assert.equal(r.status, 403);
assert.equal(r.body.error.code, "port_not_allowed");
await tuning({ hostPortRange: { from: 18000, to: 18099 } });
assert.equal((await create({ hostPort: 18080, dryRun: true })).status, 200);
assert.equal((await create({ hostPort: 18100, dryRun: true })).body.error.code, "port_not_allowed");
});
it("memory and CPU caps", async () => {
await tuning({ maxMemoryMb: 4096, maxCpus: 4 });
const big = await create({ options: { modelFile: "Big-Q8_0.gguf" } });
assert.equal(big.body.error.code, "limit_exceeded");
assert.match(big.body.error.message, /the estimate/);
assert.equal((await create({ memoryMb: 8192 })).body.error.code, "limit_exceeded");
assert.equal((await create({ cpus: 8 })).body.error.code, "limit_exceeded");
});
it("one agent deployment at a time (pending ones count)", async () => {
assert.equal((await create()).status, 201);
const second = await create();
assert.equal(second.status, 429);
assert.equal(second.body.error.code, "too_many_deployments");
// Creating a stopped one is fine; starting it isn't.
const stopped = await create({ start: false });
assert.equal(stopped.status, 201);
const s = await call(M.start.POST, "/x", { token: hermes, params: { id: stopped.body.id } });
assert.equal(s.body.error.code, "too_many_deployments");
});
it("no start while an agent deployment is still loading or an agent run is open", async () => {
await tuning({ maxAgentDeployments: 3 });
const a = await create();
await setState(a.body.id, "starting");
assert.equal((await create()).body.error.code, "gpu_busy");
await setState(a.body.id, "running");
await M.db.db().insert(M.schema.benchmarkRuns).values({
deploymentId: a.body.id,
modelId,
settings: { quick: true, passes: null, warmup: null, phases: [] },
snapshot: { deploymentName: "x", repoId: "x", runtimeName: "x", engine: "llama.cpp", image: "x", imageId: null, options: { modelFile: "", contextSize: 1, extraArgs: [] }, cpus: null, memoryMb: null, command: "" },
state: "running",
requestedByTokenId: "someone",
requestedBy: "other",
});
const r = await create();
assert.equal(r.body.error.code, "gpu_busy");
assert.match(r.body.error.message, /benchmark or sweep/);
});
it("can't crowd a running protected deployment out of VRAM", async () => {
await tuning({ approvalMode: "auto" });
// prod ≈ 10 GiB; the 20 GB Q8_0 at 8k context needs ~22 GiB more: over 32 GiB.
const big = await create({ options: { modelFile: "Big-Q8_0.gguf" } });
assert.equal(big.status, 409);
assert.equal(big.body.error.code, "vram_protected");
assert.match(big.body.error.message, /prod/);
// Partial offload can't be estimated next to a protected deployment.
assert.equal((await create({ options: { gpuLayers: "20" } })).body.error.code, "vram_protected");
// The small one fits.
assert.equal((await create()).status, 201);
});
});
describe("ownership and protection", () => {
it("agents can't change, start, stop or delete the user's or another token's deployments", async () => {
for (const [handler, method] of [
[M.start.POST, "POST"],
[M.stop.POST, "POST"],
[M.dep.DELETE, "DELETE"],
] as const) {
const r = await call(handler, "/x", { token: hermes, method, params: { id: userProtected } });
assert.equal(r.status, 403);
assert.equal(r.body.error.code, "protected");
}
const theirs = await create({ start: false }, other);
const r = await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 4096 } }, params: { id: theirs.body.id } });
assert.equal(r.body.error.code, "not_owner");
assert.equal((await call(M.stop.POST, "/x", { token: hermes, params: { id: theirs.body.id } })).body.error.code, "not_owner");
});
it("not even their own once the user protects it", async () => {
const mine = await create({ start: false });
await M.deployments.setProtected(mine.body.id, true);
const r = await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 4096 } }, params: { id: mine.body.id } });
assert.equal(r.body.error.code, "protected");
});
it("edits, stops and deletes their own deployments", async () => {
const mine = await create({ start: false });
const p = await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 16384, extraArgs: ["--no-mmap"] } }, params: { id: mine.body.id } });
assert.equal(p.status, 200);
assert.equal(p.body.deployment.options.contextSize, 16384);
assert.match(p.body.command, /-c 16384 .*--no-mmap/);
// Changing a running deployment needs a stop first.
await setState(mine.body.id, "running");
assert.equal((await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 4096 } }, params: { id: mine.body.id } })).body.error.code, "busy");
assert.equal((await call(M.stop.POST, "/x", { token: hermes, params: { id: mine.body.id } })).status, 200);
assert.equal((await M.deployments.getDeployment(mine.body.id))?.desiredState, "stopped");
assert.equal((await call(M.dep.DELETE, "/x", { token: hermes, method: "DELETE", params: { id: mine.body.id } })).status, 200);
assert.equal(await M.deployments.getDeployment(mine.body.id), null);
});
});
describe("benchmark runs and sweeps", () => {
async function runningOwn(token = hermes) {
const d = await create({ start: false }, token);
await setState(d.body.id, "running");
return d.body.id as string;
}
it("only on the token's own, unprotected deployments", async () => {
const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: userProtected } });
assert.equal(r.body.error.code, "protected");
const theirs = await runningOwn(other);
assert.equal((await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: theirs } })).body.error.code, "not_owner");
});
it("waits for approval, with the time limit, and one at a time", async () => {
const id = await runningOwn();
const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: id, quick: true, description: "baseline" } });
assert.equal(r.status, 201);
assert.equal(r.body.state, "pending_approval");
const row = await M.db.db().query.benchmarkRuns.findFirst({ where: eq(M.schema.benchmarkRuns.id, r.body.id) });
assert.equal(row?.timeLimitS, 30 * 60);
assert.equal(row?.requestedBy, "hermes");
const second = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: id } });
assert.equal(second.status, 429);
assert.equal(second.body.error.code, "gpu_busy");
// Cancelling is for the token that started it.
assert.equal((await call(M.cancel.POST, "/x", { token: other, params: { id: r.body.id } })).body.error.code, "not_owner");
assert.equal((await call(M.cancel.POST, "/x", { token: hermes, params: { id: r.body.id } })).status, 200);
const view = await call(M.run.GET, "/x", { token: hermes, params: { id: r.body.id } });
assert.equal(view.body.state, "cancelled");
});
it("a stopped deployment can't be benchmarked", async () => {
const d = await create({ start: false });
const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: d.body.id } });
assert.equal(r.status, 409);
assert.match(r.body.error.message, /running server/);
});
it("sweeps: within the variant limit, with no agent deployment running", async () => {
const base = await create({ start: false });
const many = await call(M.sweeps.POST, "/api/v1/sweeps", {
token: hermes,
body: { baseDeploymentId: base.body.id, params: [{ key: "contextSize", values: ["1024", "2048", "4096"] }, { key: "kvCache", values: ["f16", "q8_0", "q4_0"] }] },
});
assert.equal(many.body.error.code, "too_many_variants");
const running = await runningOwn();
const busy = await call(M.sweeps.POST, "/api/v1/sweeps", { token: hermes, body: { baseDeploymentId: base.body.id, params: [{ key: "kvCache", values: ["f16", "q8_0"] }] } });
assert.equal(busy.body.error.code, "gpu_busy");
await setState(running, "stopped");
const ok = await call(M.sweeps.POST, "/api/v1/sweeps", { token: hermes, body: { baseDeploymentId: base.body.id, params: [{ key: "kvCache", values: ["f16", "q8_0"] }] } });
assert.equal(ok.status, 201);
assert.equal(ok.body.state, "pending_approval");
assert.equal(ok.body.variants, 2);
const row = await M.db.db().query.benchmarkSweeps.findFirst({ where: eq(M.schema.benchmarkSweeps.id, ok.body.id) });
assert.equal(row?.timeLimitS, 180 * 60);
assert.equal(row?.runTimeLimitS, 30 * 60);
});
it("compares runs: headline numbers and what differs", async () => {
const id = await runningOwn();
const ids: string[] = [];
for (const decode of [100, 120]) {
const [r] = await M.db
.db()
.insert(M.schema.benchmarkRuns)
.values({
deploymentId: id,
modelId,
settings: { quick: false, passes: null, warmup: null, phases: [] },
snapshot: { deploymentName: "x", repoId: "x", runtimeName: "x", engine: "llama.cpp", image: "x", imageId: null, options: { modelFile: "", contextSize: 1, extraArgs: [] }, cpus: null, memoryMb: null, command: "" },
state: "completed",
summary: { combined: { decode, ttft_p50: 50, itl_low1: null, update_p50: null, update_p99: null }, single: [], prefill: [], concurrency: [], phases: [], cacheHits: 0, betterbenchVersion: "0.6.1", corpusVersion: "1", passes: 20, quick: false },
meta: {
v: 1,
gpus: [],
p2p: "n/a",
rebar: null,
runtime: { image: "x", tag: null, digest: null, engine: "llama.cpp", engineName: "llama.cpp", engineVersion: "b1" },
model: { repoId: "a/b", file: null, quant: "Q4_K_M", kvCache: decode === 100 ? "f16" : "q8_0" },
contextSize: 8192,
concurrency: 4,
overridden: [],
},
})
.returning();
ids.push(r.id);
}
const c = await call(M.compare.GET, `/api/v1/benchmarks/compare?ids=${ids.join(",")}`, { token: hermes });
assert.equal(c.status, 200);
assert.deepEqual(c.body.runs.map((r: { headline: { decodeTps: number } }) => r.headline.decodeTps), [100, 120]);
assert.deepEqual(Object.keys(c.body.runs[0].differs), ["model"]);
assert.equal(c.body.same.ctx, "8,192");
});
});
describe("?wait=", () => {
it("returns as soon as a starting deployment is running", async () => {
await tuning({ approvalMode: "auto" });
const d = await create();
await setState(d.body.id, "starting");
setTimeout(() => void setState(d.body.id, "running"), 300);
const t0 = Date.now();
const r = await call(M.dep.GET, `/api/v1/deployments/${d.body.id}?wait=10`, { token: hermes, params: { id: d.body.id } });
assert.equal(r.body.state, "running");
assert.equal(r.body.timedOut, false);
assert.ok(Date.now() - t0 < 5000);
});
it("gives up after the wait and says so", async () => {
const d = await create({ start: false });
await setState(d.body.id, "starting");
const r = await call(M.dep.GET, `/api/v1/deployments/${d.body.id}?wait=1`, { token: hermes, params: { id: d.body.id } });
assert.equal(r.body.state, "starting");
assert.equal(r.body.timedOut, true);
assert.equal(r.body.waitedSeconds, 1);
});
it("doesn't wait on something that waits for approval", async () => {
const d = await create();
const t0 = Date.now();
const r = await call(M.dep.GET, `/api/v1/deployments/${d.body.id}?wait=60`, { token: hermes, params: { id: d.body.id } });
assert.equal(r.body.state, "pending_approval");
assert.ok(Date.now() - t0 < 2000);
});
it("waits on a run until it finishes", async () => {
const dep = await create({ start: false });
await setState(dep.body.id, "running");
await tuning({ approvalMode: "auto" });
const run = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: dep.body.id } });
assert.equal(run.body.state, "queued");
setTimeout(
// A drizzle query only runs once it is awaited.
async () => await M.db.db().update(M.schema.benchmarkRuns).set({ state: "completed", finishedAt: new Date() }).where(eq(M.schema.benchmarkRuns.id, run.body.id)),
300,
);
const r = await call(M.run.GET, `/api/v1/benchmarks/${run.body.id}?wait=10`, { token: hermes, params: { id: run.body.id } });
assert.equal(r.body.state, "completed");
});
});
describe("activity log", () => {
it("records requests and refusals with the error code", async () => {
await create();
await create({ options: { extraArgs: ["--host", "x"] } });
const tokenId = (await M.tokens.listTokens()).find((t) => t.name === "hermes")!.id;
const rows = await (await import("./agent-activity")).listActivity(tokenId, 10);
assert.equal(rows[0].outcome, "refused");
assert.equal(rows[0].code, "arg_not_allowed");
assert.equal(rows[1].action, "deployment.create");
assert.equal(rows[1].outcome, "pending_approval");
assert.equal(rows[1].targetType, "deployment");
});
});
describe("the index", () => {
it("shows the deployment guardrails and the new endpoints", async () => {
const r = await call(M.v1.GET, "/api/v1", { token: hermes });
assert.equal(r.body.deploymentGuardrails.maxAgentDeployments, 1);
assert.equal(r.body.deploymentGuardrails.maxRunMinutes, 30);
assert.ok(r.body.endpoints.some((e: string) => e.includes("/api/v1/deployments/{id}[?wait=600]")));
});
});
+6 -1
View File
@@ -3,6 +3,10 @@ import { NextResponse } from "next/server";
import { z } from "zod";
import { GuardrailError } from "@/lib/agent-guardrails";
import { SelectionError } from "@/lib/agent-selection";
import { TuningError } from "@/lib/agent-tuning";
import { BenchmarkError } from "@/lib/benchmarks";
import { DeploymentError } from "@/lib/deployments";
import { SweepRequestError } from "@/lib/sweeps";
import { HubError } from "@/lib/hub/client";
import { JobError } from "@/lib/jobs";
import { ModelError } from "@/lib/models";
@@ -31,7 +35,8 @@ const HUB_STATUS: Partial<Record<HubError["code"], number>> = {
/** Known errors → JSON; anything else is logged and becomes a generic 500 (no stack traces). */
export function v1Catch(err: unknown) {
if (err instanceof GuardrailError) return v1Error(err.status, err.code, err.message);
if (err instanceof GuardrailError || err instanceof TuningError) return v1Error(err.status, err.code, err.message);
if (err instanceof DeploymentError || err instanceof BenchmarkError || err instanceof SweepRequestError) return v1Error(err.status, err.code, err.message);
if (err instanceof SelectionError) return v1Error(err.status, err.code, err.message);
if (err instanceof ModelError || err instanceof JobError || err instanceof TagError) return v1Error(err.status, err.code, err.message);
if (err instanceof HubError) return v1Error(HUB_STATUS[err.code] ?? 502, err.code, err.message);
+217
View File
@@ -0,0 +1,217 @@
import assert from "node:assert/strict";
import { hostname, userInfo } from "node:os";
import { describe, it } from "node:test";
import { argValue, buildRunMeta, gpuLabel, gpusUsed, imageTag, kvCacheOf, metaNotes, metaRows, modelLabel, quantOf, withLoadLinks } from "./benchmark-meta";
import type { DeploymentOptions, HardwareGpu, HostHardware } from "./db/schema";
import { applyOverrides, formatLinkPair, linkGen, parseLinkText, rebarFrom, systemSummary, systemSummaryText, validateOverrides } from "./hardware";
const intel: HardwareGpu = {
vendor: "intel",
pciAddress: "0000:03:00.0",
name: "Intel Arc Pro B65",
vramMb: 32768,
driver: "xe",
driverVersion: "kernel 6.17.1",
linkCurrent: { gen: 4, width: 8 },
linkMax: { gen: 5, width: 16 },
barMb: 32768,
rebar: true,
};
const nvidia: HardwareGpu = { ...intel, vendor: "nvidia", pciAddress: "0000:05:00.0", name: "NVIDIA RTX 4090", vramMb: 24564, driver: "nvidia", driverVersion: "580.82.07", barMb: 256, rebar: false };
const hw: HostHardware = {
gpus: [intel, nvidia],
p2p: null,
cpu: { model: "AMD EPYC 9124 16-Core Processor", cores: 16, threads: 32 },
memoryBytes: 128e9,
kernel: "6.17.1-pve",
virtualization: { vm: true, hypervisor: "KVM/QEMU" },
storage: { model: "Samsung SSD 990 PRO 2TB", kind: "nvme", sizeBytes: 2e12 },
checkedAt: "2026-10-20T00:00:00.000Z",
};
const opts: DeploymentOptions = { modelFile: "Qwen3-8B-Q4_K_M.gguf", contextSize: 8192, extraArgs: [], cacheTypeK: "q8_0", cacheTypeV: "q8_0", parallel: 2 };
describe("PCIe links and ReBAR", () => {
it("maps link speeds to generations and formats current vs maximum", () => {
assert.equal(linkGen("16.0 GT/s PCIe"), 4);
assert.equal(linkGen("2.5 GT/s"), 1);
assert.equal(linkGen("Unknown"), null);
assert.equal(formatLinkPair({ gen: 4, width: 8 }, { gen: 5, width: 16 }), "Gen4 x8 of Gen5 x16");
assert.equal(formatLinkPair({ gen: 5, width: 16 }, { gen: 5, width: 16 }), "Gen5 x16");
assert.equal(formatLinkPair(null, null), null);
});
it("parses typed links", () => {
assert.deepEqual(parseLinkText("Gen4 x8"), { gen: 4, width: 8 });
assert.deepEqual(parseLinkText("gen 5"), { gen: 5, width: null });
assert.deepEqual(parseLinkText("x16"), { gen: null, width: 16 });
assert.equal(parseLinkText("fast"), null);
assert.equal(parseLinkText(""), null);
});
it("calls ReBAR on when a BAR covers the VRAM", () => {
assert.equal(rebarFrom(32768, 32768), true);
assert.equal(rebarFrom(256, 24564), false);
assert.equal(rebarFrom(8192, null), true);
assert.equal(rebarFrom(256, null), null);
assert.equal(rebarFrom(null, 1024), null);
});
});
describe("hardware overrides", () => {
it("replace detected values and are listed", () => {
const e = applyOverrides(hw, { gpus: { "0000:05:00.0": { linkCurrent: "Gen3 x16", rebar: true } }, storage: "Proxmox ZFS mirror", gpuPassthrough: true })!;
assert.deepEqual(e.gpus[1].linkCurrent, { gen: 3, width: 16 });
assert.equal(e.gpus[1].rebar, true);
assert.deepEqual(e.gpus[0], intel);
assert.equal(e.storage?.model, "Proxmox ZFS mirror");
assert.equal(e.gpuPassthrough, true);
assert.deepEqual(e.overridden, ["pcie link", "rebar", "storage", "gpu passthrough"]);
});
it("derive passthrough from a VM with GPUs", () => {
assert.equal(applyOverrides(hw)!.gpuPassthrough, true);
assert.equal(applyOverrides({ ...hw, virtualization: { vm: false, hypervisor: null } })!.gpuPassthrough, false);
});
it("are validated, empty fields dropped", () => {
assert.deepEqual(validateOverrides({ gpus: { "0000:03:00.0": { name: "", linkMax: "Gen5 x16" } }, p2p: "", storage: " " }), { gpus: { "0000:03:00.0": { linkMax: "Gen5 x16" } } });
assert.throws(() => validateOverrides({ gpus: { "0000:03:00.0": { linkCurrent: "fast" } } }), /isn't a PCIe link/);
assert.throws(() => validateOverrides({ gpus: { "../etc": {} } }), /isn't a PCI address/);
assert.throws(() => validateOverrides({ p2p: "maybe" }), /P2P/);
assert.throws(() => validateOverrides({ gpus: { "0000:03:00.0": { vramMb: 1.5 } } }), /VRAM/);
assert.throws(() => validateOverrides({ storage: "a\nb" }), /one line/);
});
});
describe("system summary", () => {
it("lists the whitelisted facts", () => {
const text = systemSummaryText(systemSummary(applyOverrides(hw), "Debian GNU/Linux 13 (trixie)", "0.11.0"));
assert.match(text, /CPU: AMD EPYC 9124 16-Core Processor \(16 cores, 32 threads\)/);
assert.match(text, /Models disk: Samsung SSD 990 PRO 2TB, NVMe/);
assert.match(text, /OS: Debian GNU\/Linux 13 \(trixie\), kernel 6\.17\.1-pve/);
assert.match(text, /GPU driver: xe kernel 6\.17\.1, nvidia 580\.82\.07/);
assert.match(text, /Virtualization: VM \(KVM\/QEMU\) with GPU passthrough/);
assert.match(text, /Kaname 0\.11\.0/);
});
it("never contains the hostname, user, addresses or paths", () => {
const s = systemSummary(applyOverrides(hw), "Debian GNU/Linux 13", "0.11.0");
const meta = buildRunMeta({
hardware: applyOverrides(hw),
gpus: [intel],
runtime: { image: "ghcr.io/ggml-org/llama.cpp:server-intel", digest: "sha256:abc", engine: "llama.cpp", engineName: null, extraArgs: [] },
repoId: "unsloth/Qwen3-8B-GGUF",
options: opts,
engineInfo: null,
});
const published = JSON.stringify([s, metaNotes(meta, s, "testing q8 KV")]);
for (const secret of [hostname(), userInfo().username].filter((x) => x.length > 2)) assert.ok(!published.includes(secret), `contains ${secret}`);
assert.doesNotMatch(published, /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/);
assert.doesNotMatch(published, /\/(models|data|home|srv|mnt|var)\//);
assert.doesNotMatch(published, /0000:0[35]:00\.0/);
// Only these keys exist; a new field must be added here on purpose.
assert.deepEqual(Object.keys(s).sort(), ["cpu", "gpuDrivers", "kaname", "kernel", "memoryBytes", "os", "storage", "virtualization"]);
});
});
describe("run metadata", () => {
it("reads image tags and flags", () => {
assert.equal(imageTag("ghcr.io/ggml-org/llama.cpp:server-b11429"), "server-b11429");
assert.equal(imageTag("registry:5000/vllm/vllm-openai@sha256:abc"), null);
assert.equal(imageTag("vllm/vllm-openai:v0.31.0@sha256:abc"), "v0.31.0");
assert.equal(argValue(["--kv-cache-dtype", "fp8", "--x"], "--kv-cache-dtype"), "fp8");
assert.equal(argValue(["--quantization=awq"], "--quantization", "-q"), "awq");
});
it("finds quant and KV cache type per engine", () => {
assert.equal(quantOf("llama.cpp", "Qwen3-8B-Q4_K_M.gguf", "unsloth/Qwen3-8B-GGUF", []), "Q4_K_M");
assert.equal(quantOf("vllm", null, "Qwen/Qwen3.8-27B-FP8", []), "FP8");
assert.equal(quantOf("vllm", null, "org/model", ["--quantization", "awq"]), "awq");
assert.equal(quantOf("vllm", null, "Qwen/Qwen3-8B", []), null);
assert.equal(kvCacheOf("llama.cpp", {}, []), "f16");
assert.equal(kvCacheOf("llama.cpp", { cacheTypeK: "q8_0", cacheTypeV: "q4_0" }, []), "K q8_0 / V q4_0");
assert.equal(kvCacheOf("vllm", {}, ["--kv-cache-dtype=fp8"]), "fp8");
assert.equal(kvCacheOf("vllm", {}, []), "auto");
});
it("knows which GPUs a deployment gets", () => {
const e = applyOverrides(hw);
const nv = [{ vendor: "nvidia" as const, index: 0, uuid: "GPU-1", name: "x", memoryMb: 1, driver: "d", pciAddress: "0000:05:00.0" }];
assert.deepEqual(gpusUsed(e, "dri", {}, nv).map((g) => g.pciAddress), ["0000:03:00.0"]);
assert.deepEqual(gpusUsed(e, "nvidia", { gpus: ["GPU-1"] }, nv).map((g) => g.pciAddress), ["0000:05:00.0"]);
assert.deepEqual(gpusUsed(e, "nvidia", { gpus: ["GPU-other"] }, nv), []);
assert.deepEqual(gpusUsed(e, "cpu", {}, nv), []);
});
it("records what the server reported over the launch options", () => {
const m = buildRunMeta({
hardware: applyOverrides(hw),
gpus: [intel],
runtime: { image: "ghcr.io/ggml-org/llama.cpp:server-intel", digest: "sha256:abc", engine: "llama.cpp", engineName: "", extraArgs: [] },
repoId: "unsloth/Qwen3-8B-GGUF",
options: opts,
engineInfo: { version: "b11429-d81235049", slots: 4, contextSize: 8192, at: "" },
});
assert.equal(m.p2p, "n/a");
assert.equal(m.rebar, true);
assert.equal(m.concurrency, 4);
assert.deepEqual(m.runtime, { image: "ghcr.io/ggml-org/llama.cpp:server-intel", tag: "server-intel", digest: "sha256:abc", engine: "llama.cpp", engineName: "llama.cpp", engineVersion: "b11429-d81235049" });
assert.equal(modelLabel(m), "Qwen3-8B-GGUF Q4_K_M with q8_0 KV cache");
assert.equal(gpuLabel(m), "1× Intel Arc Pro B65 (32 GiB)");
const rows = Object.fromEntries(metaRows(m).map((r) => [r.key, r.value]));
assert.equal(rows.pcie, "Gen4 x8 of Gen5 x16 (at idle)");
assert.equal(rows.engine, "llama.cpp b11429-d81235049");
});
it("falls back to the options, and to unknown, when the server didn't say", () => {
const m = buildRunMeta({
hardware: null,
gpus: [nvidia, nvidia],
runtime: { image: "vllm/vllm-openai:v0.31.0", digest: null, engine: "vllm", engineName: "vllm-radiance", extraArgs: ["--kv-cache-dtype", "fp8"] },
repoId: "Qwen/Qwen3.8-27B-FP8",
options: { modelFile: "", contextSize: 32768, extraArgs: [], maxNumSeqs: 8 },
engineInfo: null,
});
assert.equal(m.p2p, null);
assert.equal(m.rebar, false);
assert.equal(m.concurrency, 8);
assert.equal(m.runtime.engineName, "vllm-radiance");
assert.equal(modelLabel(m), "Qwen3.8-27B-FP8 FP8 with fp8 KV cache");
assert.equal(gpuLabel(m), "2× NVIDIA RTX 4090 (24 GiB)");
const notes = metaNotes(m, null, " two\n lines ");
assert.equal(notes.engine, "vllm-radiance");
assert.equal(notes.p2p, "unknown");
assert.equal(notes.description, "two lines");
assert.equal(notes.gpus, "2× NVIDIA RTX 4090 (24 GiB)");
});
});
describe("links under load", () => {
const base = () =>
buildRunMeta({
hardware: applyOverrides(hw),
gpus: [{ ...intel, linkCurrent: { gen: 1, width: 8 } }],
runtime: { image: "x:y", digest: null, engine: "llama.cpp", engineName: null, extraArgs: [] },
repoId: "a/b",
options: opts,
engineInfo: null,
});
it("marks an idle link and uses the fastest one seen under load", () => {
const m = base();
assert.equal(Object.fromEntries(metaRows(m).map((r) => [r.key, r.value])).pcie, "Gen1 x8 of Gen5 x16 (at idle)");
const loaded = withLoadLinks(m, { "0000:03:00.0": { gen: 4, width: 8 } }, false)!;
assert.equal(loaded.linkUnderLoad, true);
assert.equal(Object.fromEntries(metaRows(loaded).map((r) => [r.key, r.value])).pcie, "Gen4 x8 of Gen5 x16");
assert.equal(withLoadLinks(m, { "0000:03:00.0": { gen: 4, width: 8 } }, true), m);
assert.equal(withLoadLinks(m, {}, false), m);
});
it("puts only the maximum link in the notes (known before the run)", () => {
const n = metaNotes(base(), null, null);
assert.equal(n.pcie_max, "Gen5 x16");
assert.equal(n.pcie, undefined);
});
});
+181
View File
@@ -0,0 +1,181 @@
// What a benchmark run records about its setup (RunMeta) and the BetterBench notes made from it.
// Pure; shared by the worker, the web app and tests.
import type { DeploymentOptions, EngineInfo, HardwareGpu, HostGpu, PcieLink, RunMeta, RuntimeAccelerator, RuntimeEngine, SystemSummary } from "@/lib/db/schema";
import { type EffectiveHardware, formatLink, formatLinkPair, onOff, systemSummaryText } from "@/lib/hardware";
import { quantGroup } from "@/lib/selection";
/** "ghcr.io/org/img:tag@sha256:…" → "tag" (null: no tag, i.e. "latest" or digest only). */
export function imageTag(ref: string): string | null {
const noDigest = ref.split("@")[0];
const last = noDigest.slice(noDigest.lastIndexOf("/") + 1);
const i = last.indexOf(":");
return i >= 0 ? last.slice(i + 1) : null;
}
/** Value of `--flag v` or `--flag=v` in an argument list (last one wins). */
export function argValue(args: string[], ...flags: string[]): string | null {
let v: string | null = null;
for (let i = 0; i < args.length; i++) {
for (const f of flags) {
if (args[i] === f && i + 1 < args.length) v = args[i + 1];
else if (args[i].startsWith(`${f}=`)) v = args[i].slice(f.length + 1);
}
}
return v;
}
const REPO_QUANT = /(?:^|[-_.])(nvfp4|mxfp4|fp8(?:[-_]dynamic)?|int8|int4|w8a8|w4a16|awq|gptq|bnb[-_]?4bit|bf16|fp16)(?=$|[-_.])/i;
/** Quant: the GGUF's quant tag, vLLM's --quantization, or one named in the repo (FP8, AWQ, …). */
export function quantOf(engine: RuntimeEngine, file: string | null, repoId: string, args: string[]): string | null {
if (engine === "llama.cpp" && file) return quantGroup(file);
const q = argValue(args, "--quantization", "-q");
if (q) return q;
const m = repoId.split("/").pop()?.match(REPO_QUANT);
return m ? m[1].toUpperCase().replace("_", "-") : null;
}
/** KV cache type: llama.cpp -ctk/-ctv (f16 default), vLLM --kv-cache-dtype ("auto": the model's dtype). */
export function kvCacheOf(engine: RuntimeEngine, o: Pick<DeploymentOptions, "cacheTypeK" | "cacheTypeV">, args: string[]): string {
if (engine === "vllm") return argValue(args, "--kv-cache-dtype") ?? "auto";
const k = argValue(args, "-ctk", "--cache-type-k") ?? o.cacheTypeK ?? "f16";
const v = argValue(args, "-ctv", "--cache-type-v") ?? o.cacheTypeV ?? "f16";
return k === v ? k : `K ${k} / V ${v}`;
}
/** The GPUs a deployment gets: NVIDIA by UUID (all when none picked), /dev/dri ones by vendor. */
export function gpusUsed(hw: EffectiveHardware | null, accelerator: RuntimeAccelerator | undefined, options: Pick<DeploymentOptions, "gpus">, nvidia: HostGpu[]): HardwareGpu[] {
const all = hw?.gpus ?? [];
if (accelerator === "nvidia") {
const picked = options.gpus?.length ? nvidia.filter((g) => options.gpus!.includes(g.uuid)).map((g) => g.pciAddress) : null;
return all.filter((g) => g.vendor === "nvidia" && (!picked || picked.includes(g.pciAddress)));
}
if (accelerator === "dri") return all.filter((g) => g.vendor === "intel" || g.vendor === "amd");
if (accelerator === "rocm") return all.filter((g) => g.vendor === "amd");
return [];
}
export function buildRunMeta(x: {
hardware: EffectiveHardware | null;
gpus: HardwareGpu[];
runtime: { image: string; digest: string | null; engine: RuntimeEngine; engineName: string | null; extraArgs: string[] };
repoId: string;
options: DeploymentOptions;
engineInfo: EngineInfo | null;
}): RunMeta {
const args = [...x.runtime.extraArgs, ...x.options.extraArgs];
const llama = x.runtime.engine === "llama.cpp";
return {
v: 1,
gpus: x.gpus.map((g) => ({ pciAddress: g.pciAddress, name: g.name, vramMb: g.vramMb, linkCurrent: g.linkCurrent, linkMax: g.linkMax, rebar: g.rebar })),
linkUnderLoad: false,
p2p: x.gpus.length < 2 ? "n/a" : (x.hardware?.p2p ?? null),
rebar: x.gpus.length === 0 ? null : x.gpus.every((g) => g.rebar === true) ? true : x.gpus.some((g) => g.rebar === false) ? false : null,
runtime: {
image: x.runtime.image,
tag: imageTag(x.runtime.image),
digest: x.runtime.digest,
engine: x.runtime.engine,
engineName: x.runtime.engineName?.trim() || x.runtime.engine,
engineVersion: x.engineInfo?.version ?? null,
},
model: {
repoId: x.repoId,
file: x.options.modelFile || null,
quant: quantOf(x.runtime.engine, x.options.modelFile || null, x.repoId, args),
kvCache: kvCacheOf(x.runtime.engine, x.options, args),
},
contextSize: x.engineInfo?.contextSize ?? x.options.contextSize ?? null,
concurrency: x.engineInfo?.slots ?? (llama ? x.options.parallel : x.options.maxNumSeqs) ?? null,
overridden: x.hardware?.overridden ?? [],
};
}
/** "2× NVIDIA RTX 4090 (24 GiB)", "1× Intel Arc Pro B65 (32 GiB) + 1× …"; null without GPUs. */
export function gpuLabel(m: RunMeta): string | null {
if (m.gpus.length === 0) return null;
const counts = new Map<string, number>();
for (const g of m.gpus) {
const name = `${g.name ?? "unknown GPU"}${g.vramMb ? ` (${Math.round(g.vramMb / 1024)} GiB)` : ""}`;
counts.set(name, (counts.get(name) ?? 0) + 1);
}
return [...counts].map(([name, n]) => `${n}× ${name}`).join(" + ");
}
/** The PCIe links of the GPUs used, deduplicated; "(idle)" when not measured under load. */
export function pcieLabel(m: RunMeta): string | null {
const links = [...new Set(m.gpus.map((g) => formatLinkPair(g.linkCurrent, g.linkMax) ?? "unknown"))];
if (!links.length) return null;
const idle = !m.linkUnderLoad && m.gpus.some((g) => g.linkCurrent);
return `${links.join(", ")}${idle ? " (at idle)" : ""}`;
}
/** Maximum links only ("Gen5 x16"): known before the run, unlike the link under load. */
export function pcieMaxLabel(m: RunMeta): string | null {
const links = [...new Set(m.gpus.map((g) => formatLink(g.linkMax) ?? "unknown"))];
return links.length ? links.join(", ") : null;
}
/** The run's meta with the fastest links seen during the run as the current links (when sampled). */
export function withLoadLinks(m: RunMeta | null, links: Record<string, PcieLink> | null | undefined, overridden: boolean): RunMeta | null {
if (!m || !links || overridden) return m;
let hit = false;
const gpus = m.gpus.map((g) => {
const l = g.pciAddress ? links[g.pciAddress] : undefined;
if (!l) return g;
hit = true;
return { ...g, linkCurrent: l };
});
return hit ? { ...m, gpus, linkUnderLoad: true } : m;
}
export const engineLabel = (m: RunMeta) => [m.runtime.engineName, m.runtime.engineVersion].filter(Boolean).join(" ");
/** "Qwen3-8B-GGUF Q4_K_M with q8_0 KV cache" */
export function modelLabel(m: RunMeta): string {
const name = m.model.repoId.split("/").pop() ?? m.model.repoId;
return `${name}${m.model.quant ? ` ${m.model.quant}` : ""}${m.model.kvCache ? ` with ${m.model.kvCache} KV cache` : ""}`;
}
/** Rows for the run page, compare views and sweeps (label → value, "unknown" where not known). */
export function metaRows(m: RunMeta): { key: string; label: string; value: string }[] {
return [
{ key: "gpus", label: "GPUs", value: gpuLabel(m) ?? "none (CPU)" },
...(m.gpus.length ? [{ key: "pcie", label: "PCIe", value: pcieLabel(m) ?? "unknown" }] : []),
...(m.gpus.length ? [{ key: "p2p", label: "P2P", value: m.p2p ?? "unknown" }] : []),
...(m.gpus.length ? [{ key: "rebar", label: "ReBAR", value: onOff(m.rebar) }] : []),
{ key: "engine", label: "Engine", value: engineLabel(m) || "unknown" },
{ key: "image", label: "Image", value: m.runtime.image },
{ key: "digest", label: "Digest", value: m.runtime.digest ?? "unknown" },
{ key: "model", label: "Model", value: modelLabel(m) },
{ key: "ctx", label: "Context", value: m.contextSize != null ? m.contextSize.toLocaleString("en-US") : "unknown" },
{ key: "concurrency", label: "Concurrency", value: m.concurrency != null ? String(m.concurrency) : "server default" },
];
}
/**
* BetterBench --note values (recorded in results.json, shown in its report and published to
* launch80). `engine` is the key launch80 uses to name the stack.
*/
export function metaNotes(m: RunMeta, system: SystemSummary | null, description: string | null): Record<string, string> {
const notes: Record<string, string> = {
engine: engineLabel(m) || m.runtime.engine,
image: m.runtime.image,
...(m.runtime.digest ? { digest: m.runtime.digest } : {}),
...(m.model.quant ? { quant: m.model.quant } : {}),
...(m.model.kvCache ? { kv_cache: m.model.kvCache } : {}),
...(m.contextSize != null ? { ctx: String(m.contextSize) } : {}),
...(m.concurrency != null ? { concurrency: String(m.concurrency) } : {}),
gpus: gpuLabel(m) ?? "none",
};
if (m.gpus.length) {
// The link under load is only known after the run (idle GPUs drop to a slower link).
notes.pcie_max = pcieMaxLabel(m) ?? "unknown";
notes.p2p = m.p2p ?? "unknown";
notes.rebar = onOff(m.rebar);
}
if (system) notes.system = systemSummaryText(system);
if (description?.trim()) notes.description = description.trim().replace(/\s+/g, " ").slice(0, 2000);
return notes;
}
+167
View File
@@ -0,0 +1,167 @@
// What a run records about its setup, against a temporary database: detected hardware from the
// worker, Settings → Hardware overrides, the runtime's digest and the server's reported version.
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, it } from "node:test";
import type { HostHardware } from "./db/schema";
const dir = mkdtempSync(join(tmpdir(), "kaname-setup-"));
process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
process.env.APP_VERSION = "0.11.0-test";
type Mods = {
db: typeof import("./db/client");
schema: typeof import("./db/schema");
snapshot: typeof import("./benchmark-snapshot");
settings: typeof import("./settings");
benchmarks: typeof import("./benchmarks");
};
let M: Mods;
let deploymentId: string;
const hardware: HostHardware = {
gpus: [
{
vendor: "intel",
pciAddress: "0000:03:00.0",
name: "Intel Arc Pro B65",
vramMb: 32768,
driver: "xe",
driverVersion: "kernel 6.17.1",
linkCurrent: { gen: 1, width: 1 },
linkMax: { gen: 5, width: 16 },
barMb: 256,
rebar: false,
},
],
p2p: null,
cpu: { model: "AMD EPYC 9124 16-Core Processor", cores: 16, threads: 32 },
memoryBytes: 128e9,
kernel: "6.17.1",
virtualization: { vm: true, hypervisor: "KVM/QEMU" },
storage: { model: "QEMU HARDDISK", kind: "virtual", sizeBytes: 2e12 },
checkedAt: new Date().toISOString(),
};
before(async () => {
const { runMigrations } = await import("./db/migrate");
await runMigrations();
M = {
db: await import("./db/client"),
schema: await import("./db/schema"),
snapshot: await import("./benchmark-snapshot"),
settings: await import("./settings"),
benchmarks: await import("./benchmarks"),
};
const d = M.db.db();
const s = M.schema;
const now = new Date();
await d.insert(s.workerState).values({
id: "worker",
startedAt: now,
heartbeatAt: now,
docker: {
connected: true,
error: null,
serverVersion: "29.0",
os: "Debian GNU/Linux 13 (trixie)",
architecture: "x86_64",
cpus: 32,
memoryBytes: 128e9,
cpuModel: null,
cpuFeatures: [],
network: "kaname_default",
modelsSource: { type: "bind", source: "/srv/models" },
hardware,
checkedAt: now.toISOString(),
},
});
const [model] = await d.insert(s.models).values({ repoId: "unsloth/Qwen3-8B-GGUF", pinnedSha: "a".repeat(40), localPath: "unsloth/Qwen3-8B-GGUF" }).returning();
const [rt] = await d
.insert(s.runtimes)
.values({ name: "llama.cpp (Intel SYCL)", engine: "llama.cpp", accelerator: "dri", image: "ghcr.io/ggml-org/llama.cpp:server-intel", imageDigest: "sha256:feed" })
.returning();
const [dep] = await d
.insert(s.deployments)
.values({
name: "qwen3 b65",
runtimeId: rt.id,
modelId: model.id,
options: { modelFile: "Qwen3-8B-Q4_K_M.gguf", contextSize: 16384, cacheTypeK: "q8_0", cacheTypeV: "q8_0", extraArgs: [] },
state: "running",
engineInfo: { version: "b11429-d81235049", slots: 4, contextSize: 16384, at: now.toISOString() },
})
.returning();
deploymentId = dep.id;
});
after(() => {
(globalThis as { __kanameDb?: { client?: { close(): void } } }).__kanameDb?.client?.close();
try {
rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
} catch {
// Windows may still hold the WAL file for a moment.
}
});
describe("run setup", () => {
it("records GPU, link, ReBAR, engine version, quant, KV cache, context and slots", async () => {
const { metas, system } = await M.snapshot.runSetup([deploymentId, null]);
const m = metas[0]!;
assert.equal(metas[1], null);
assert.equal(m.gpus.length, 1);
assert.equal(m.gpus[0].name, "Intel Arc Pro B65");
assert.deepEqual(m.gpus[0].linkCurrent, { gen: 1, width: 1 });
assert.equal(m.rebar, false);
assert.equal(m.p2p, "n/a");
assert.deepEqual(m.runtime, {
image: "ghcr.io/ggml-org/llama.cpp:server-intel",
tag: "server-intel",
digest: "sha256:feed",
engine: "llama.cpp",
engineName: "llama.cpp",
engineVersion: "b11429-d81235049",
});
assert.deepEqual(m.model, { repoId: "unsloth/Qwen3-8B-GGUF", file: "Qwen3-8B-Q4_K_M.gguf", quant: "Q4_K_M", kvCache: "q8_0" });
assert.equal(m.contextSize, 16384);
assert.equal(m.concurrency, 4);
assert.deepEqual(m.overridden, []);
assert.equal(system.kaname, "0.11.0-test");
assert.equal(system.os, "Debian GNU/Linux 13 (trixie)");
assert.equal(system.virtualization.gpuPassthrough, true);
});
it("applies Settings → Hardware to new runs", async () => {
await M.settings.saveHardwareOverrides({
gpus: { "0000:03:00.0": { linkCurrent: "Gen5 x8", rebar: true } },
storage: "Samsung 990 PRO 2TB (passed through as a virtual disk)",
hypervisor: "Proxmox VE 9 (KVM)",
});
const { metas, system } = await M.snapshot.runSetup([deploymentId]);
assert.deepEqual(metas[0]!.gpus[0].linkCurrent, { gen: 5, width: 8 });
assert.equal(metas[0]!.rebar, true);
assert.deepEqual(metas[0]!.overridden, ["pcie link", "rebar", "storage", "virtualization"]);
assert.equal(system.storage?.model, "Samsung 990 PRO 2TB (passed through as a virtual disk)");
assert.equal(system.virtualization.hypervisor, "Proxmox VE 9 (KVM)");
});
it("rejects invalid overrides and clears them when empty", async () => {
await assert.rejects(M.settings.saveHardwareOverrides({ gpus: { "0000:03:00.0": { linkMax: "Gen9" } } }), (e: Error) => e instanceof M.settings.SettingsError && /PCIe link/.test(e.message));
assert.deepEqual(await M.settings.saveHardwareOverrides({}), {});
assert.deepEqual(await M.settings.getHardwareOverrides(), {});
});
it("keeps a description with the run, editable later", async () => {
const run = await M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ deploymentId, description: " q8_0 KV to fit 16k " }));
assert.equal((await M.benchmarks.getBenchmark(run.id))?.description, "q8_0 KV to fit 16k");
await M.benchmarks.updateBenchmark(run.id, { label: "q8 KV" });
assert.equal((await M.benchmarks.getBenchmark(run.id))?.description, "q8_0 KV to fit 16k");
await M.benchmarks.updateBenchmark(run.id, { description: "" });
const row = await M.benchmarks.getBenchmark(run.id);
assert.equal(row?.description, null);
assert.equal(row?.label, "q8 KV");
});
});
+42 -1
View File
@@ -3,7 +3,9 @@
import { and, eq, isNull } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { type BenchmarkSnapshot, deployments, models, runtimes, workerState } from "@/lib/db/schema";
import { buildRunMeta, gpusUsed } from "@/lib/benchmark-meta";
import { type BenchmarkSnapshot, deployments, models, type RunMeta, runtimes, settings, type SystemSummary, workerState } from "@/lib/db/schema";
import { applyOverrides, HARDWARE_OVERRIDES_KEY, parseOverrides, systemSummary } from "@/lib/hardware";
/** Host CPU/RAM and the names of the GPUs a deployment uses (all detected ones when none are picked). */
async function hostFacts(uuids: string[] | null, nvidia: boolean) {
@@ -60,3 +62,42 @@ export async function deploymentSnapshot(deploymentId: string): Promise<{ id: st
},
};
}
/** Kaname's version (the image sets APP_VERSION). */
export const kanameVersion = () => process.env.APP_VERSION ?? "dev";
/** The detected hardware with Settings → Hardware applied, and the host's OS. */
export async function effectiveHardware() {
const [ws, ov] = await Promise.all([
db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") }),
db().query.settings.findFirst({ where: eq(settings.key, HARDWARE_OVERRIDES_KEY) }),
]);
const docker = ws?.docker ?? null;
return { hardware: applyOverrides(docker?.hardware, parseOverrides(ov?.value)), nvidia: docker?.gpus ?? [], os: docker?.os ?? null };
}
/** Hardware, runtime and model facts of a deployment as it runs now, plus the system summary. */
export async function runSetup(deploymentIds: (string | null)[]): Promise<{ metas: (RunMeta | null)[]; system: SystemSummary }> {
const { hardware, nvidia, os } = await effectiveHardware();
const metas = await Promise.all(
deploymentIds.map(async (id) => {
if (!id) return null;
const [d] = await db()
.select({ options: deployments.options, engineInfo: deployments.engineInfo, repoId: models.repoId, runtime: runtimes })
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.innerJoin(models, eq(models.id, deployments.modelId))
.where(eq(deployments.id, id));
if (!d) return null;
return buildRunMeta({
hardware,
gpus: gpusUsed(hardware, d.runtime.accelerator, d.options, nvidia),
runtime: { image: d.runtime.image, digest: d.runtime.imageDigest, engine: d.runtime.engine, engineName: d.runtime.engineName, extraArgs: d.runtime.extraArgs },
repoId: d.repoId,
options: d.options,
engineInfo: d.engineInfo,
});
}),
);
return { metas, system: systemSummary(hardware, os, kanameVersion()) };
}
+54 -6
View File
@@ -17,9 +17,13 @@ export class BenchmarkError extends Error {
}
}
export const DESCRIPTION_MAX = 4000;
export const BenchmarkBody = z.object({
deploymentId: z.string().min(1),
label: z.string().trim().max(120).nullable().optional(),
/** Free text: what this run tries out. Passed to BetterBench and launch80 with the system summary. */
description: z.string().trim().max(DESCRIPTION_MAX).nullable().optional(),
quick: z.boolean().default(false),
passes: z.number().int().min(1).max(200).nullable().optional(),
warmup: z.number().int().min(0).max(50).nullable().optional(),
@@ -46,7 +50,10 @@ async function snapshotOf(deploymentId: string, role: string) {
* Queue a run against a running deployment, or a paired A/B between two running deployments of the
* same model (BetterBench sends one model name to both). The worker runs one benchmark at a time.
*/
export async function createBenchmark(input: BenchmarkInput) {
/** Requested through the API: who asked, whether it waits for approval, and its time limit. */
export type AgentRequest = { requestedBy: { tokenId: string; name: string }; pendingApproval: boolean; timeLimitS: number };
export async function createBenchmark(input: BenchmarkInput, agent?: AgentRequest) {
const ab = !!input.deploymentBId;
const a = await snapshotOf(input.deploymentId, ab ? "Deployment A" : "The deployment");
const b = ab ? await snapshotOf(input.deploymentBId!, "Deployment B") : null;
@@ -64,6 +71,7 @@ export async function createBenchmark(input: BenchmarkInput) {
deploymentBId: b?.id ?? null,
modelId: a.modelId,
label: input.label || null,
description: input.description || null,
settings: {
quick: input.quick,
passes: input.passes ?? null,
@@ -74,6 +82,14 @@ export async function createBenchmark(input: BenchmarkInput) {
snapshot: a.snapshot,
snapshotB: b?.snapshot ?? null,
sweepId: input.sweepId ?? null,
...(agent
? {
requestedByTokenId: agent.requestedBy.tokenId,
requestedBy: agent.requestedBy.name,
timeLimitS: agent.timeLimitS,
state: agent.pendingApproval ? ("pending_approval" as const) : ("queued" as const),
}
: {}),
})
.returning({ id: benchmarkRuns.id });
return row;
@@ -101,6 +117,13 @@ const listColumns = {
ab: benchmarkRuns.ab,
resources: benchmarkRuns.resources,
sweepId: benchmarkRuns.sweepId,
requestedBy: benchmarkRuns.requestedBy,
requestedByTokenId: benchmarkRuns.requestedByTokenId,
timeLimitS: benchmarkRuns.timeLimitS,
meta: benchmarkRuns.meta,
metaB: benchmarkRuns.metaB,
system: benchmarkRuns.system,
description: benchmarkRuns.description,
createdAt: benchmarkRuns.createdAt,
};
@@ -130,19 +153,44 @@ export async function getBenchmarks(ids: string[]) {
return ids.map((id) => rows.find((r) => r.id === id)).filter((r) => r != null);
}
/** Queued runs are cancelled right away; a running one is stopped by the worker. */
/** Queued (or still unapproved) runs are cancelled right away; a running one is stopped by the worker. */
export async function cancelBenchmark(id: string) {
const run = await getBenchmark(id);
if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
if (run.state === "queued") {
await db().update(benchmarkRuns).set({ state: "cancelled", finishedAt: new Date() }).where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, "queued")));
if (run.state === "queued" || run.state === "pending_approval") {
await db().update(benchmarkRuns).set({ state: "cancelled", finishedAt: new Date() }).where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, run.state)));
} else if (run.state === "running") {
await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, id));
}
}
export async function updateBenchmarkLabel(id: string, label: string | null) {
const res = await db().update(benchmarkRuns).set({ label: label?.trim() || null }).where(eq(benchmarkRuns.id, id)).returning({ id: benchmarkRuns.id });
/** Let a run an agent asked for start (it joins the queue). */
export async function approveBenchmark(id: string) {
const res = await db()
.update(benchmarkRuns)
.set({ state: "queued" })
.where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, "pending_approval")))
.returning({ id: benchmarkRuns.id });
if (res.length === 0) throw new BenchmarkError("invalid", "This run doesn't wait for approval.", 409);
}
/** Turn down a run an agent asked for. */
export async function rejectBenchmark(id: string) {
const res = await db()
.update(benchmarkRuns)
.set({ state: "cancelled", finishedAt: new Date(), error: "Rejected by the user." })
.where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, "pending_approval")))
.returning({ id: benchmarkRuns.id });
if (res.length === 0) throw new BenchmarkError("invalid", "This run doesn't wait for approval.", 409);
}
/** Rename a run (label) and/or change its description; fields left out stay as they are. */
export async function updateBenchmark(id: string, patch: { label?: string | null; description?: string | null }) {
const set: Partial<typeof benchmarkRuns.$inferInsert> = {};
if (patch.label !== undefined) set.label = patch.label?.trim() || null;
if (patch.description !== undefined) set.description = patch.description?.trim() || null;
if (Object.keys(set).length === 0) return;
const res = await db().update(benchmarkRuns).set(set).where(eq(benchmarkRuns.id, id)).returning({ id: benchmarkRuns.id });
if (res.length === 0) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
}
+170 -6
View File
@@ -377,10 +377,69 @@ export type DockerHostInfo = {
gpus?: HostGpu[];
gpuError?: string | null;
gpuCheckedAt?: string | null;
/** Group IDs owning /dev/dri on the host (render, video); given to Intel/AMD runtime containers. */
driGroups?: number[];
/** PCIe, ReBAR, system facts from sysfs/procfs (what the worker's container sees of the host). */
hardware?: HostHardware | null;
checkedAt: string;
};
export type HostGpu = { vendor: "nvidia"; index: number; uuid: string; name: string; memoryMb: number; driver: string };
export type HostGpu = {
vendor: "nvidia";
index: number;
uuid: string;
name: string;
memoryMb: number;
driver: string;
pciAddress?: string | null;
/** PCIe link as nvidia-smi reports it (also where sysfs isn't visible, e.g. WSL2). */
linkCurrent?: PcieLink | null;
linkMax?: PcieLink | null;
};
/** A PCIe link: generation (1 = 2.5 GT/s … 6 = 64 GT/s) and lanes. */
export type PcieLink = { gen: number | null; width: number | null };
export type GpuVendor = "nvidia" | "intel" | "amd";
/** A GPU as found on the PCI bus. The link is the card's upstream link (behind on-card switches). */
export type HardwareGpu = {
vendor: GpuVendor;
pciAddress: string;
name: string | null;
vramMb: number | null;
/** Kernel driver (nvidia, xe, i915, amdgpu) and its version (the kernel's for in-tree drivers). */
driver: string | null;
driverVersion: string | null;
linkCurrent: PcieLink | null;
linkMax: PcieLink | null;
/** Largest memory BAR in MiB; Resizable BAR is on when it covers the VRAM. */
barMb: number | null;
rebar: boolean | null;
};
export type HostHardware = {
gpus: HardwareGpu[];
/** Peer-to-peer between GPUs (NVIDIA: nvidia-smi topo); null = unknown or a single GPU. */
p2p: "on" | "off" | "partial" | null;
cpu: { model: string | null; cores: number | null; threads: number | null };
memoryBytes: number | null;
kernel: string | null;
virtualization: { vm: boolean | null; hypervisor: string | null };
/** The disk holding the models folder. */
storage: { model: string | null; kind: "nvme" | "ssd" | "hdd" | "virtual" | null; sizeBytes: number | null } | null;
checkedAt: string;
};
/** Settings → Hardware: manual values where detection can't see the truth (VMs, new GPUs). */
export type HardwareOverrides = {
gpus?: Record<string, { name?: string; vramMb?: number; linkCurrent?: string; linkMax?: string; rebar?: boolean }>;
p2p?: "on" | "off" | "partial";
storage?: string;
hypervisor?: string;
gpuPassthrough?: boolean;
gpuDriver?: string;
};
// ---------------------------------------------------------------------------
// Runtimes: container images that serve models (llama.cpp, vLLM, forks, …)
@@ -429,6 +488,10 @@ export const runtimes = sqliteTable("runtimes", {
pullProgress: text("pull_progress", { mode: "json" }).$type<{ doneBytes: number; totalBytes: number; status: string }>(),
pullError: text("pull_error"),
imageCheckedAt: ts("image_checked_at"),
/** Registry digest of the pulled image (sha256:…), from its RepoDigests. */
imageDigest: text("image_digest"),
/** Shown instead of the engine type for forks, e.g. "vllm-radiance". */
engineName: text("engine_name"),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
@@ -534,8 +597,17 @@ export const deployments = sqliteTable("deployments", {
exitCode: integer("exit_code"),
error: text("error"),
stats: text("stats", { mode: "json" }).$type<DeploymentStats>(),
/** Version, slots and context the server reported once ready. */
engineInfo: text("engine_info", { mode: "json" }).$type<EngineInfo>(),
/** Temporary deployment created by a benchmark sweep (removed when its variant is done). */
sweepId: text("sweep_id"),
/** Created through the API: the token and its name at the time. */
requestedByTokenId: text("requested_by_token_id"),
requestedBy: text("requested_by"),
/** Agents can't edit, stop, delete or benchmark it, nor start anything that would crowd it out of VRAM. */
protected: integer("protected", { mode: "boolean" }).notNull().default(false),
/** An agent asked to start it; it starts once someone approves (approval mode "approve"). */
startRequestedAt: ts("start_requested_at"),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
@@ -572,7 +644,7 @@ export const apiKeys = sqliteTable("api_keys", {
// ---------------------------------------------------------------------------
/** What a token may do. Nothing can delete, change settings or manage runtimes/tokens. */
export const TOKEN_SCOPES = ["models:read", "downloads:create"] as const;
export const TOKEN_SCOPES = ["models:read", "downloads:create", "deployments:read", "deployments:write", "benchmarks:read", "benchmarks:run"] as const;
export type TokenScope = (typeof TOKEN_SCOPES)[number];
export const apiTokens = sqliteTable(
@@ -592,11 +664,31 @@ export const apiTokens = sqliteTable(
(t) => [uniqueIndex("api_tokens_name_uq").on(t.name)],
);
/** What tokens did: every request that creates or changes something, and refusals by a guardrail. */
export const agentActivity = sqliteTable(
"agent_activity",
{
id: id(),
tokenId: text("token_id").notNull(),
tokenName: text("token_name").notNull(),
/** e.g. "deployment.create", "deployment.start", "benchmark.run", "sweep.create", "download.request". */
action: text("action").notNull(),
targetType: text("target_type"),
targetId: text("target_id"),
/** ok, pending_approval or refused (then `code` is the error code). */
outcome: text("outcome", { enum: ["ok", "pending_approval", "refused"] }).notNull(),
code: text("code"),
message: text("message"),
createdAt: createdAt(),
},
(t) => [index("agent_activity_token_idx").on(t.tokenId, t.createdAt)],
);
// ---------------------------------------------------------------------------
// Benchmarks (BetterBench runs against a running deployment)
// ---------------------------------------------------------------------------
export const BENCHMARK_STATES = ["queued", "running", "completed", "failed", "cancelled"] as const;
export const BENCHMARK_STATES = ["pending_approval", "queued", "running", "completed", "failed", "cancelled"] as const;
export type BenchmarkState = (typeof BENCHMARK_STATES)[number];
export const BENCHMARK_PHASES = ["decode", "prefill", "concurrency"] as const;
@@ -661,8 +753,26 @@ export type ResourceStats = {
memPeakBytes: number | null;
memLimitBytes: number | null;
}[];
/** Whole-GPU figures (nvidia-smi), not per process. */
gpus: { index: number; name: string; vramTotalMb: number; vramPeakMb: number; vramAvgMb: number; utilAvg: number; utilPeak: number; powerAvgW: number | null; powerPeakW: number | null }[];
/** Fastest PCIe link seen per GPU (PCI address) during the run. */
links?: Record<string, PcieLink>;
/**
* Whole-GPU figures, not per process: nvidia-smi; hwmon/sysfs for AMD; hwmon plus the DRM fdinfo
* of all processes for Intel. null where a source doesn't report it.
*/
gpus: {
index: number;
name: string;
pciAddress?: string;
vramTotalMb: number | null;
vramPeakMb: number | null;
vramAvgMb: number | null;
utilAvg: number | null;
utilPeak: number | null;
powerAvgW: number | null;
powerPeakW: number | null;
tempAvgC?: number | null;
tempPeakC?: number | null;
}[];
};
/** The deployment as it was when the run started, so results stay comparable after edits. */
@@ -685,6 +795,43 @@ export type BenchmarkSnapshot = {
command: string;
};
/** What was measured on what, recorded when a run starts (Settings → Hardware overrides applied). */
export type RunMeta = {
v: 1;
gpus: { pciAddress?: string; name: string | null; vramMb: number | null; linkCurrent: PcieLink | null; linkMax: PcieLink | null; rebar: boolean | null }[];
/**
* GPUs lower their link speed when idle: true once linkCurrent is the fastest link seen while the run
* was under load (otherwise it is what detection saw, possibly idle).
*/
linkUnderLoad?: boolean;
/** "n/a" with fewer than two GPUs; null = unknown. */
p2p: "on" | "off" | "partial" | "n/a" | null;
/** On for every GPU used; null = unknown. */
rebar: boolean | null;
runtime: { image: string; tag: string | null; digest: string | null; engine: RuntimeEngine; engineName: string; engineVersion: string | null };
model: { repoId: string; file: string | null; quant: string | null; kvCache: string | null };
contextSize: number | null;
/** Parallel slots (llama.cpp) or max sequences (vLLM); reported by the server where it can. */
concurrency: number | null;
/** Fields taken from Settings → Hardware instead of detection. */
overridden: string[];
};
/** The host, as published: nothing that identifies it (no hostname, IP, user or path). */
export type SystemSummary = {
cpu: { model: string | null; cores: number | null; threads: number | null };
memoryBytes: number | null;
storage: { model: string | null; kind: "nvme" | "ssd" | "hdd" | "virtual" | null; sizeBytes: number | null } | null;
os: string | null;
kernel: string | null;
gpuDrivers: string[];
virtualization: { vm: boolean | null; hypervisor: string | null; gpuPassthrough: boolean | null };
kaname: string;
};
/** What the server reported about itself once ready (llama.cpp /props, vLLM /version and /v1/models). */
export type EngineInfo = { version: string | null; slots: number | null; contextSize: number | null; at: string };
/**
* BetterBench's own report rows for a run (betterbench.report: single_rows, prefill_rows,
* concurrency_rows, combined_score, sample_gate, …), copied as computed. Nothing in Kaname derives
@@ -800,6 +947,17 @@ export const benchmarkRuns = sqliteTable(
resources: text("resources", { mode: "json" }).$type<ResourceStats>(),
/** Run of a sweep variant. */
sweepId: text("sweep_id"),
/** Requested through the API: the token and its name at the time. */
requestedByTokenId: text("requested_by_token_id"),
requestedBy: text("requested_by"),
/** Agent runs: cancelled after this many seconds of running. */
timeLimitS: integer("time_limit_s"),
/** Hardware, runtime and model facts (A, and B of an A/B), recorded at the start. */
meta: text("meta", { mode: "json" }).$type<RunMeta>(),
metaB: text("meta_b", { mode: "json" }).$type<RunMeta>(),
system: text("system", { mode: "json" }).$type<SystemSummary>(),
/** Free text by the user; passed to BetterBench and launch80 with the system summary. */
description: text("description"),
createdAt: createdAt(),
},
(t) => [index("benchmark_runs_created_idx").on(t.createdAt)],
@@ -857,7 +1015,7 @@ export const benchmarkPublications = sqliteTable(
// Benchmark sweeps: one base deployment, one or two settings varied, a run per variant
// ---------------------------------------------------------------------------
export const SWEEP_STATES = ["queued", "running", "completed", "failed", "cancelled"] as const;
export const SWEEP_STATES = ["pending_approval", "queued", "running", "completed", "failed", "cancelled"] as const;
export type SweepState = (typeof SWEEP_STATES)[number];
/** A setting a sweep varies; values are strings as entered (parsed per key). */
@@ -890,5 +1048,11 @@ export const benchmarkSweeps = sqliteTable("benchmark_sweeps", {
startedAt: ts("started_at"),
finishedAt: ts("finished_at"),
error: text("error"),
/** Requested through the API: the token and its name at the time. */
requestedByTokenId: text("requested_by_token_id"),
requestedBy: text("requested_by"),
/** Agent sweeps: the sweep is stopped after this many seconds, each of its runs after runTimeLimitS. */
timeLimitS: integer("time_limit_s"),
runTimeLimitS: integer("run_time_limit_s"),
createdAt: createdAt(),
});
+32 -3
View File
@@ -128,6 +128,37 @@ export const LLAMA_DEFAULT_CACHE_RAM_MB = 8192;
const KV_TYPE_FACTOR: Record<string, number> = { f32: 2, f16: 1, bf16: 1, q8_0: 0.53, q5_0: 0.34, q5_1: 0.38, q4_0: 0.28, q4_1: 0.31, iq4_nl: 0.28 };
/** llama.cpp KV cache in MiB for a model of `modelMb`: the per-token heuristic below, scaled by the cache type. */
function kvCacheMb(modelMb: number, contextSize: number, o: Pick<DeploymentOptions, "cacheTypeK" | "cacheTypeV">): number {
const perTokenKiB = 96 + 24 * Math.sqrt(modelMb / 1024);
const kvFactor = ((KV_TYPE_FACTOR[o.cacheTypeK ?? "f16"] ?? 1) + (KV_TYPE_FACTOR[o.cacheTypeV ?? "f16"] ?? 1)) / 2;
return (contextSize * perTokenKiB * kvFactor) / 1024;
}
/** llama.cpp compute buffers and runtime state on the GPU (measured order of magnitude, not exact). */
const GPU_OVERHEAD_MB = 1024;
/**
* Rough VRAM need of a GPU deployment in MiB, for NVIDIA and Intel/AMD (/dev/dri) alike; null when it
* can't be told without reading the model (only some layers or the MoE experts offloaded).
* - vLLM reserves --gpu-memory-utilization (default 0.9) of each GPU's VRAM up front.
* - llama.cpp with all layers on the GPU ("auto" fits as many as there is room for): weights + KV
* cache + compute buffers.
*/
export function estimateVramMb(
fileBytes: number,
contextSize: number,
engine: RuntimeEngine,
o: Pick<DeploymentOptions, "gpuLayers" | "cacheTypeK" | "cacheTypeV" | "cpuMoe" | "nCpuMoe" | "gpuMemoryUtilization">,
vramTotalMb: number | null,
): number | null {
if (engine === "vllm") return vramTotalMb ? Math.ceil(vramTotalMb * (o.gpuMemoryUtilization ?? 0.9)) : null;
const layers = o.gpuLayers ?? "auto";
if ((layers !== "auto" && layers !== "all") || o.cpuMoe || (o.nCpuMoe ?? 0) > 0) return null;
const model = fileBytes / 2 ** 20;
return Math.ceil(model + kvCacheMb(model, contextSize, o) + GPU_OVERHEAD_MB);
}
/**
* Rough RAM need of a deployment in MiB, for the memory limit. Without the GGUF header the KV size
* per token is a heuristic: ~110 KiB (f16) for sub-1B models up to ~250 KiB around 70B with GQA.
@@ -144,9 +175,7 @@ export function estimateMemoryMb(
// vLLM CPU: API server, engine core and worker each load torch (~3 GiB measured with v0.31.0).
// On a GPU the weights and KV cache live in VRAM; RAM holds the processes.
if (engine === "vllm") return Math.ceil(gpu ? 6144 : model + (o.kvCacheGb ?? 4) * 1024 + 3072);
const perTokenKiB = 96 + 24 * Math.sqrt(model / 1024);
const kvFactor = ((KV_TYPE_FACTOR[o.cacheTypeK ?? "f16"] ?? 1) + (KV_TYPE_FACTOR[o.cacheTypeV ?? "f16"] ?? 1)) / 2;
const kv = (contextSize * perTokenKiB * kvFactor) / 1024;
const kv = kvCacheMb(model, contextSize, o);
const cache = o.cacheRamMb == null ? LLAMA_DEFAULT_CACHE_RAM_MB : o.cacheRamMb < 0 ? LLAMA_DEFAULT_CACHE_RAM_MB : o.cacheRamMb;
// The memory-mapped model counts against the container's limit (page cache), even when offloaded.
return Math.ceil(model + (gpu ? 0 : kv) + cache + 768);
+46 -7
View File
@@ -89,8 +89,21 @@ export async function listDeployableModels(): Promise<DeployableModel[]> {
.filter((m) => m.candidates.gguf.length > 0 || m.candidates.vllm);
}
/** Bytes of the files a deployment loads (llama.cpp: the GGUF, mmproj and draft; vLLM: the repo's files). */
export async function deploymentFileBytes(modelId: string, options: Pick<DeploymentOptions, "modelFile" | "mmproj" | "draftFile">, engine: "llama.cpp" | "vllm"): Promise<number> {
const files = await localFiles(modelId);
if (engine === "vllm") return modelCandidates(files).vllm?.size ?? files.reduce((s, f) => s + f.size, 0);
const want = [options.modelFile, options.mmproj, options.draftFile].filter(Boolean);
// A split GGUF is named by its first part; the other parts belong to it.
const first = files.find((f) => f.path === options.modelFile);
const group = first ? quantGroup(first.path) : null;
return files
.filter((f) => want.includes(f.path) || (group != null && f.path !== options.modelFile && quantGroup(f.path) === group && f.path.toLowerCase().endsWith(".gguf") && !f.path.toLowerCase().includes("mmproj")))
.reduce((s, f) => s + f.size, 0);
}
/** Check that runtime, model and files fit together; returns normalized options. */
async function validate(input: DeploymentInput, selfId?: string): Promise<DeploymentOptions> {
export async function validateDeployment(input: DeploymentInput, selfId?: string): Promise<DeploymentOptions> {
const runtime = await db().query.runtimes.findFirst({ where: eq(runtimes.id, input.runtimeId) });
if (!runtime) throw new DeploymentError("invalid", "Runtime not found.", 400);
const model = await db().query.models.findFirst({ where: eq(models.id, input.modelId) });
@@ -148,8 +161,12 @@ async function validate(input: DeploymentInput, selfId?: string): Promise<Deploy
return options;
}
export async function createDeployment(input: DeploymentInput, startNow: boolean) {
const options = await validate(input);
export async function createDeployment(
input: DeploymentInput,
startNow: boolean,
agent?: { requestedBy: { tokenId: string; name: string }; startPendingApproval: boolean },
) {
const options = await validateDeployment(input);
const [row] = await db()
.insert(deployments)
.values({
@@ -160,7 +177,10 @@ export async function createDeployment(input: DeploymentInput, startNow: boolean
cpus: input.cpus ?? null,
memoryMb: input.memoryMb ?? null,
hostPort: input.hostPort ?? null,
desiredState: startNow ? "running" : "stopped",
desiredState: startNow && !agent?.startPendingApproval ? "running" : "stopped",
...(agent
? { requestedByTokenId: agent.requestedBy.tokenId, requestedBy: agent.requestedBy.name, startRequestedAt: startNow && agent.startPendingApproval ? new Date() : null }
: {}),
})
.returning({ id: deployments.id });
return row;
@@ -176,7 +196,7 @@ async function get(id: string) {
export async function updateDeployment(id: string, input: DeploymentInput) {
const d = await get(id);
if (d.state !== "stopped" && d.state !== "failed") throw new DeploymentError("busy", "Stop the deployment before changing it.", 409);
const options = await validate(input, id);
const options = await validateDeployment(input, id);
await db()
.update(deployments)
.set({
@@ -193,13 +213,27 @@ export async function updateDeployment(id: string, input: DeploymentInput) {
export async function setDesiredState(id: string, desired: "running" | "stopped") {
const d = await get(id);
if (d.desiredState === desired) return;
if (d.desiredState === desired && !d.startRequestedAt) return;
await db()
.update(deployments)
.set({ desiredState: desired, ...(desired === "running" ? { error: null } : {}) })
// Starting or stopping it by hand settles a start an agent asked for.
.set({ desiredState: desired, startRequestedAt: null, ...(desired === "running" ? { error: null } : {}) })
.where(eq(deployments.id, id));
}
/** Mark a deployment as protected: agents can't touch it or crowd it out of VRAM. */
export async function setProtected(id: string, value: boolean) {
await get(id);
await db().update(deployments).set({ protected: value }).where(eq(deployments.id, id));
}
/** Turn down a start an agent asked for (the deployment stays stopped). */
export async function rejectStart(id: string) {
const d = await get(id);
if (!d.startRequestedAt) throw new DeploymentError("invalid", "This deployment doesn't wait for a start approval.", 409);
await db().update(deployments).set({ startRequestedAt: null }).where(eq(deployments.id, id));
}
/** The worker stops the container and deletes the row. */
export async function requestDelete(id: string) {
await get(id);
@@ -229,6 +263,11 @@ const listColumns = {
runtimeImage: runtimes.image,
accelerator: runtimes.accelerator,
sweepId: deployments.sweepId,
protected: deployments.protected,
requestedBy: deployments.requestedBy,
requestedByTokenId: deployments.requestedByTokenId,
startRequestedAt: deployments.startRequestedAt,
engineInfo: deployments.engineInfo,
engine: runtimes.engine,
modelId: deployments.modelId,
repoId: models.repoId,
+210
View File
@@ -0,0 +1,210 @@
// Host hardware as Kaname reports it: PCIe links, ReBAR, the system summary, and the manual
// overrides from Settings → Hardware. Pure; shared by the web app, the worker and tests.
import type { HardwareGpu, HardwareOverrides, HostHardware, PcieLink, SystemSummary } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
const GT_PER_GEN: [number, number][] = [
[2.5, 1],
[5, 2],
[8, 3],
[16, 4],
[32, 5],
[64, 6],
];
/** sysfs "16.0 GT/s PCIe" → 4; unknown speeds → null. */
export function linkGen(speed: string | null | undefined): number | null {
const gt = Number(speed?.match(/([\d.]+)\s*GT\/s/)?.[1]);
return GT_PER_GEN.find(([s]) => Math.abs(s - gt) < 0.01)?.[1] ?? null;
}
export function formatLink(l: PcieLink | null | undefined): string | null {
if (!l || (l.gen == null && l.width == null)) return null;
return [l.gen != null ? `Gen${l.gen}` : null, l.width != null ? `x${l.width}` : null].filter(Boolean).join(" ");
}
/** "Gen4 x8 of Gen5 x16", or just "Gen5 x16" when the link runs at its maximum. */
export function formatLinkPair(current: PcieLink | null | undefined, max: PcieLink | null | undefined): string | null {
const c = formatLink(current);
const m = formatLink(max);
if (!c) return m ? `? of ${m}` : null;
return !m || c === m ? c : `${c} of ${m}`;
}
/** "Gen4 x8", "gen 4 x8", "x16" → a link; null when it isn't one. */
export function parseLinkText(text: string): PcieLink | null {
const t = text.trim();
const m = t.match(/^(?:gen\s*([1-6]))?\s*(?:x\s*(\d{1,2}))?$/i);
if (!t || !m || (!m[1] && !m[2])) return null;
return { gen: m[1] ? Number(m[1]) : null, width: m[2] ? Number(m[2]) : null };
}
/** ReBAR is on when the largest BAR maps (nearly) all of the VRAM; without it BARs are 256 MiB. */
export function rebarFrom(barMb: number | null, vramMb: number | null): boolean | null {
if (barMb == null) return null;
if (vramMb) return barMb >= vramMb * 0.9;
return barMb >= 2048 ? true : null;
}
export const onOff = (v: boolean | null | undefined) => (v == null ? "unknown" : v ? "on" : "off");
export type EffectiveHardware = HostHardware & {
gpuPassthrough: boolean | null;
gpuDriver: string | null;
/** Which values came from Settings → Hardware (e.g. "gpu 0000:03:00.0 link", "storage"). */
overridden: string[];
};
/** Detected hardware with the overrides applied. */
export function applyOverrides(hw: HostHardware | null | undefined, o: HardwareOverrides = {}): EffectiveHardware | null {
if (!hw) return null;
const overridden: string[] = [];
const gpus: HardwareGpu[] = hw.gpus.map((g) => {
const x = o.gpus?.[g.pciAddress];
if (!x) return g;
const cur = x.linkCurrent ? parseLinkText(x.linkCurrent) : null;
const max = x.linkMax ? parseLinkText(x.linkMax) : null;
const set = <K extends keyof HardwareGpu>(key: K, v: HardwareGpu[K] | null | undefined, label: string) => {
if (v == null || v === "") return;
out[key] = v;
overridden.push(label);
};
const out = { ...g };
set("name", x.name, "gpu name");
set("vramMb", x.vramMb, "vram");
set("linkCurrent", cur, "pcie link");
set("linkMax", max, "pcie max link");
set("rebar", x.rebar, "rebar");
if (x.rebar == null && x.vramMb) out.rebar = rebarFrom(g.barMb, x.vramMb);
return out;
});
const passthroughDetected = hw.virtualization.vm ? hw.gpus.length > 0 : hw.virtualization.vm === false ? false : null;
if (o.p2p) overridden.push("p2p");
if (o.storage) overridden.push("storage");
if (o.hypervisor) overridden.push("virtualization");
if (o.gpuPassthrough != null) overridden.push("gpu passthrough");
if (o.gpuDriver) overridden.push("gpu driver");
return {
...hw,
gpus,
p2p: o.p2p ?? hw.p2p,
storage: o.storage ? { model: o.storage, kind: hw.storage?.kind ?? null, sizeBytes: hw.storage?.sizeBytes ?? null } : hw.storage,
virtualization: o.hypervisor ? { vm: true, hypervisor: o.hypervisor } : hw.virtualization,
gpuPassthrough: o.gpuPassthrough ?? passthroughDetected,
gpuDriver: o.gpuDriver ?? null,
overridden: [...new Set(overridden)],
};
}
/** Driver labels, e.g. "nvidia 580.82.07", "xe (kernel 6.17.1)". */
export function driverLabels(gpus: HardwareGpu[]): string[] {
return [...new Set(gpus.filter((g) => g.driver).map((g) => (g.driverVersion ? `${g.driver} ${g.driverVersion}` : g.driver!)))];
}
/**
* The publishable system summary. Only whitelisted facts: CPU, RAM, disk model, OS, kernel, drivers,
* virtualization, Kaname version. Never the hostname, addresses, users or paths.
*/
export function systemSummary(hw: EffectiveHardware | null, os: string | null, kaname: string): SystemSummary {
return {
cpu: hw?.cpu ?? { model: null, cores: null, threads: null },
memoryBytes: hw?.memoryBytes ?? null,
storage: hw?.storage ?? null,
os,
kernel: hw?.kernel ?? null,
gpuDrivers: hw?.gpuDriver ? [hw.gpuDriver] : driverLabels(hw?.gpus ?? []),
virtualization: { vm: hw?.virtualization.vm ?? null, hypervisor: hw?.virtualization.hypervisor ?? null, gpuPassthrough: hw?.gpuPassthrough ?? null },
kaname,
};
}
const STORAGE_KIND: Record<string, string> = { nvme: "NVMe", ssd: "SSD", hdd: "HDD", virtual: "virtual disk" };
/** One line per fact, for notes, the run page and launch80. */
export function systemSummaryLines(s: SystemSummary): string[] {
const cpu = s.cpu.model
? `${s.cpu.model}${s.cpu.cores || s.cpu.threads ? ` (${[s.cpu.cores && `${s.cpu.cores} cores`, s.cpu.threads && `${s.cpu.threads} threads`].filter(Boolean).join(", ")})` : ""}`
: null;
const disk = s.storage ? [s.storage.model, s.storage.kind && STORAGE_KIND[s.storage.kind], s.storage.sizeBytes && formatBytes(s.storage.sizeBytes)].filter(Boolean).join(", ") : null;
const v = s.virtualization;
const virt = v.vm == null ? null : v.vm ? `VM${v.hypervisor ? ` (${v.hypervisor})` : ""}${v.gpuPassthrough ? " with GPU passthrough" : ""}` : "bare metal";
return [
cpu && `CPU: ${cpu}`,
s.memoryBytes && `RAM: ${formatBytes(s.memoryBytes)}`,
disk && `Models disk: ${disk}`,
(s.os || s.kernel) && `OS: ${[s.os, s.kernel && `kernel ${s.kernel}`].filter(Boolean).join(", ")}`,
s.gpuDrivers.length > 0 && `GPU driver: ${s.gpuDrivers.join(", ")}`,
virt && `Virtualization: ${virt}`,
`Kaname ${s.kaname}`,
].filter((x): x is string => !!x);
}
export const systemSummaryText = (s: SystemSummary) => systemSummaryLines(s).join(" · ");
export const HARDWARE_OVERRIDES_KEY = "hardware.overrides";
const TEXT_MAX = 120;
export class HardwareOverrideError extends Error {}
const text = (v: unknown, what: string): string | undefined => {
if (v == null || v === "") return undefined;
if (typeof v !== "string" || v.trim().length > TEXT_MAX || /[\r\n\0]/.test(v)) throw new HardwareOverrideError(`${what}: at most ${TEXT_MAX} characters on one line.`);
return v.trim() || undefined;
};
const bool = (v: unknown, what: string): boolean | undefined => {
if (v == null || v === "") return undefined;
if (typeof v !== "boolean") throw new HardwareOverrideError(`${what} must be on or off.`);
return v;
};
const linkText = (v: unknown, what: string): string | undefined => {
const t = text(v, what);
if (t && !parseLinkText(t)) throw new HardwareOverrideError(`${what}: "${t}" isn't a PCIe link (e.g. "Gen4 x8").`);
return t;
};
/** Validate overrides from the settings form; throws HardwareOverrideError. Empty fields are dropped. */
export function validateOverrides(input: unknown): HardwareOverrides {
const o = (input ?? {}) as Record<string, unknown>;
const out: HardwareOverrides = {};
const gpus: NonNullable<HardwareOverrides["gpus"]> = {};
for (const [addr, raw] of Object.entries((o.gpus ?? {}) as Record<string, Record<string, unknown>>)) {
if (!/^[0-9a-f]{4,}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$/i.test(addr)) throw new HardwareOverrideError(`"${addr}" isn't a PCI address.`);
const vram = raw?.vramMb;
if (vram != null && vram !== "" && (typeof vram !== "number" || !Number.isInteger(vram) || vram < 256 || vram > 4_194_304)) {
throw new HardwareOverrideError("VRAM must be a whole number of MiB (256 – 4194304).");
}
const g = {
name: text(raw?.name, "GPU name"),
vramMb: typeof vram === "number" ? vram : undefined,
linkCurrent: linkText(raw?.linkCurrent, "Current link"),
linkMax: linkText(raw?.linkMax, "Maximum link"),
rebar: bool(raw?.rebar, "ReBAR"),
};
const set = Object.fromEntries(Object.entries(g).filter(([, v]) => v !== undefined));
if (Object.keys(set).length) gpus[addr.toLowerCase()] = set;
}
if (Object.keys(gpus).length) out.gpus = gpus;
if (o.p2p != null && o.p2p !== "") {
if (o.p2p !== "on" && o.p2p !== "off" && o.p2p !== "partial") throw new HardwareOverrideError("P2P must be on, off or partial.");
out.p2p = o.p2p;
}
const storage = text(o.storage, "Models disk");
const hypervisor = text(o.hypervisor, "Virtualization");
const gpuDriver = text(o.gpuDriver, "GPU driver");
const passthrough = bool(o.gpuPassthrough, "GPU passthrough");
if (storage) out.storage = storage;
if (hypervisor) out.hypervisor = hypervisor;
if (gpuDriver) out.gpuDriver = gpuDriver;
if (passthrough != null) out.gpuPassthrough = passthrough;
return out;
}
/** Stored overrides; anything invalid is ignored rather than breaking a run. */
export function parseOverrides(stored: unknown): HardwareOverrides {
try {
return validateOverrides(stored);
} catch {
return {};
}
}
+4 -1
View File
@@ -89,6 +89,8 @@ export type PayloadPreview = {
summary: string | null;
model: string | null;
notes: Record<string, string>;
/** Page sections: the run's description, hardware/runtime facts and system summary. */
sections: { heading: string; body: string }[];
/** Top-level keys that will be sent, and env keys (endpoint/host must be absent). */
keys: string[];
envKeys: string[];
@@ -105,7 +107,7 @@ export async function readPayloadPreview(runId: string, pubId: string): Promise<
const data = JSON.parse(raw) as Record<string, unknown> & {
$template?: string;
env?: Record<string, unknown>;
l80?: { title?: string; summary?: string };
l80?: { title?: string; summary?: string; sections?: { heading?: string; body?: string }[] };
single_stream?: Record<string, unknown>;
prefill?: unknown[];
concurrency?: unknown[];
@@ -118,6 +120,7 @@ export async function readPayloadPreview(runId: string, pubId: string): Promise<
summary: data.l80?.summary ?? null,
model: typeof env.model === "string" ? env.model : null,
notes: (env.notes as Record<string, string>) ?? {},
sections: (data.l80?.sections ?? []).map((s) => ({ heading: String(s.heading ?? ""), body: String(s.body ?? "") })),
keys: Object.keys(data),
envKeys: Object.keys(env),
hostRemoved: !("endpoint" in env) && !("host" in env),
+12 -6
View File
@@ -18,6 +18,8 @@ export type RuntimeInput = {
accelerator?: RuntimeAccelerator;
image: string;
description?: string | null;
/** Shown instead of the engine type in benchmarks, for forks (e.g. "vllm-radiance"). */
engineName?: string | null;
env?: Record<string, string>;
extraArgs?: string[];
devices?: string[];
@@ -73,8 +75,8 @@ export const RUNTIME_PRESETS: RuntimePreset[] = [
engine: "llama.cpp",
accelerator: "dri",
image: "ghcr.io/ggml-org/llama.cpp:server-vulkan",
summary: "llama-server over Vulkan: Intel Arc and AMD GPUs via /dev/dri.",
description: "Official llama.cpp server, Vulkan build. Works with Intel and AMD GPUs passed through as /dev/dri.",
summary: "llama-server over Vulkan: Intel Arc (incl. B-series) and AMD GPUs via /dev/dri.",
description: "Official llama.cpp server, Vulkan build. Works with Intel and AMD GPUs passed through as /dev/dri; compare it with the SYCL build on Intel.",
devices: ["/dev/dri"],
},
{
@@ -83,8 +85,9 @@ export const RUNTIME_PRESETS: RuntimePreset[] = [
engine: "llama.cpp",
accelerator: "dri",
image: "ghcr.io/ggml-org/llama.cpp:server-intel",
summary: "llama-server with Intel oneAPI/SYCL, for Intel Arc GPUs.",
description: "Official llama.cpp server, SYCL build for Intel GPUs (/dev/dri).",
summary: "llama-server with Intel oneAPI/SYCL, for Intel Arc GPUs (A- and B-series, Arc Pro).",
description: "Official llama.cpp server, SYCL build for Intel GPUs (/dev/dri). ZES_ENABLE_SYSMAN=1 lets it see free VRAM, which -ngl auto needs.",
env: { ZES_ENABLE_SYSMAN: "1" },
devices: ["/dev/dri"],
},
{
@@ -103,8 +106,8 @@ export const RUNTIME_PRESETS: RuntimePreset[] = [
engine: "vllm",
accelerator: "dri",
image: "vllm/vllm-openai-xpu:v0.31.0",
summary: "Official vLLM image for Intel GPUs (Arc, Data Center GPU Max) via /dev/dri.",
description: "Official vLLM, XPU build for Intel GPUs.",
summary: "Official vLLM image for Intel GPUs (Arc incl. B-series, Data Center GPU Max) via /dev/dri.",
description: "Official vLLM, XPU build for Intel GPUs. vLLM reserves --gpu-memory-utilization (default 0.9) of the VRAM up front.",
devices: ["/dev/dri"],
shmSizeMb: 8192,
},
@@ -147,6 +150,8 @@ export function validateRuntime(input: RuntimeInput): Required<RuntimeInput> {
if (/[\r\n\0]/.test(v)) throw new RuntimeValidationError(`Value of ${k} must be a single line.`);
env[k] = v;
}
const engineName = input.engineName?.trim() || null;
if (engineName && !/^[\w][\w.+-]{0,59}$/.test(engineName)) throw new RuntimeValidationError("Engine name: letters, digits and . _ + - (up to 60), e.g. vllm-radiance.");
const extraArgs = (input.extraArgs ?? []).map((a) => a.trim()).filter(Boolean);
for (const a of extraArgs) if (/[\r\n\0]/.test(a)) throw new RuntimeValidationError("Arguments must be single lines.");
const devices = (input.devices ?? []).map((d) => d.trim()).filter(Boolean);
@@ -163,6 +168,7 @@ export function validateRuntime(input: RuntimeInput): Required<RuntimeInput> {
accelerator,
image,
description: input.description?.trim() || null,
engineName,
env,
extraArgs,
devices,
+2 -1
View File
@@ -15,6 +15,7 @@ export const RuntimeBody = z.object({
accelerator: z.enum(RUNTIME_ACCELERATORS).optional(),
image: z.string().max(512),
description: z.string().max(2000).nullable().optional(),
engineName: z.string().max(60).nullable().optional(),
env: z.record(z.string(), z.string().max(4000)).optional(),
extraArgs: z.array(z.string().max(4000)).max(200).optional(),
devices: z.array(z.string().max(200)).max(20).optional(),
@@ -70,7 +71,7 @@ export async function updateRuntime(id: string, input: RuntimeInput): Promise<Ru
.set({
...v,
// A different image has to be looked up (and maybe pulled) again.
...(imageChanged ? { imageState: "unknown", imageId: null, imageSize: null, imageCreated: null, pullError: null } : {}),
...(imageChanged ? { imageState: "unknown", imageId: null, imageSize: null, imageCreated: null, imageDigest: null, pullError: null } : {}),
})
.where(eq(runtimes.id, id))
.returning();
+50 -1
View File
@@ -1,9 +1,11 @@
import "server-only";
import { eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { settings } from "@/lib/db/schema";
import { type HardwareOverrides, settings } from "@/lib/db/schema";
import { APPROVAL_MODES, type Guardrails, parseGuardrails } from "@/lib/agent-guardrails";
import { parseTuning, TUNING_KEY, type TuningGuardrails } from "@/lib/agent-tuning";
import { isLabelColor } from "@/lib/colors";
import { HARDWARE_OVERRIDES_KEY, HardwareOverrideError, parseOverrides, validateOverrides } from "@/lib/hardware";
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles";
import { MIN_SPEED_LIMIT, parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit";
import { DEFAULT_RECOMMENDED_ROLES, RECOMMENDABLE_ROLES } from "@/lib/recommend";
@@ -119,3 +121,50 @@ export async function saveGuardrails(input: Partial<Guardrails>): Promise<Guardr
await write(GUARDRAILS_KEY, parsed);
return parsed;
}
/** Manual hardware values (Settings → Hardware) that replace what detection reports. */
export async function getHardwareOverrides(): Promise<HardwareOverrides> {
return parseOverrides(await read<unknown>(HARDWARE_OVERRIDES_KEY));
}
export async function saveHardwareOverrides(input: unknown): Promise<HardwareOverrides> {
let next: HardwareOverrides;
try {
next = validateOverrides(input);
} catch (err) {
if (err instanceof HardwareOverrideError) throw new SettingsError(err.message);
throw err;
}
if (Object.keys(next).length === 0) await db().delete(settings).where(eq(settings.key, HARDWARE_OVERRIDES_KEY));
else await write(HARDWARE_OVERRIDES_KEY, next);
return next;
}
/** Limits for deployments and benchmarks requested through the API (Settings → API tokens). */
export async function getTuning(): Promise<TuningGuardrails> {
return parseTuning(await read<unknown>(TUNING_KEY));
}
export async function saveTuning(input: Partial<TuningGuardrails>): Promise<TuningGuardrails> {
const next = { ...(await getTuning()), ...input };
if (!APPROVAL_MODES.includes(next.approvalMode)) throw new SettingsError(`Approval mode must be one of: ${APPROVAL_MODES.join(", ")}.`);
const intIn = (v: number, min: number, max: number, what: string) => {
if (!Number.isInteger(v) || v < min || v > max) throw new SettingsError(`${what} must be ${min}–${max}.`);
};
intIn(next.maxAgentDeployments, 1, 16, "Agent deployments at once");
intIn(next.maxRunMinutes, 1, 24 * 60, "Max minutes per run");
intIn(next.maxSweepMinutes, 1, 7 * 24 * 60, "Max minutes per sweep");
intIn(next.maxSweepVariants, 2, 16, "Max sweep variants");
const r = next.hostPortRange;
if (r && (!Number.isInteger(r.from) || !Number.isInteger(r.to) || r.from < 1024 || r.to > 65_535 || r.from > r.to)) {
throw new SettingsError("Host port range must be within 1024–65535, from ≤ to.");
}
if (next.maxMemoryMb != null && !(next.maxMemoryMb >= 256)) throw new SettingsError("Memory cap must be at least 256 MiB, or empty.");
if (next.maxCpus != null && !(next.maxCpus >= 0.1)) throw new SettingsError("CPU cap must be at least 0.1 cores, or empty.");
const parsed = parseTuning(next);
for (const engine of ["llama.cpp", "vllm"] as const) {
if (parsed.allowedArgs[engine].length !== new Set(next.allowedArgs[engine]).size) throw new SettingsError(`The ${engine} argument allowlist contains something that isn't a flag.`);
}
await write(TUNING_KEY, parsed);
return parsed;
}
+29 -4
View File
@@ -10,7 +10,7 @@ import { expandSweep, MAX_SWEEP_PARAMS, SweepError } from "@/lib/sweep";
export class SweepRequestError extends Error {
constructor(
public code: "invalid" | "not_found" | "busy",
public code: "invalid" | "not_found" | "busy" | "too_many_variants",
message: string,
public status: number,
) {
@@ -31,7 +31,10 @@ export const SweepBody = z.object({
});
/** Validate against the base deployment's runtime and model files, then queue the sweep. */
export async function createSweep(input: z.infer<typeof SweepBody>) {
/** Requested through the API: who asked, approval, and the limits for the sweep and each of its runs. */
export type AgentSweepRequest = { requestedBy: { tokenId: string; name: string }; pendingApproval: boolean; timeLimitS: number; runTimeLimitS: number; maxVariants: number };
export async function createSweep(input: z.infer<typeof SweepBody>, agent?: AgentSweepRequest) {
const [base] = await db()
.select({
id: deployments.id,
@@ -62,6 +65,9 @@ export async function createSweep(input: z.infer<typeof SweepBody>) {
if (err instanceof SweepError) throw new SweepRequestError("invalid", err.message, 400);
throw err;
}
if (agent && variants.length > agent.maxVariants) {
throw new SweepRequestError("too_many_variants", `That's ${variants.length} variants; agents may run at most ${agent.maxVariants} per sweep. Vary fewer values.`, 422);
}
const [row] = await db()
.insert(benchmarkSweeps)
.values({
@@ -72,6 +78,15 @@ export async function createSweep(input: z.infer<typeof SweepBody>) {
params: input.params,
settings: { quick: input.quick, passes: input.passes ?? null, warmup: null, phases: input.phases },
variants: variants.map((v): SweepVariant => ({ ...v, state: "pending" })),
...(agent
? {
requestedByTokenId: agent.requestedBy.tokenId,
requestedBy: agent.requestedBy.name,
timeLimitS: agent.timeLimitS,
runTimeLimitS: agent.runTimeLimitS,
state: agent.pendingApproval ? ("pending_approval" as const) : ("queued" as const),
}
: {}),
})
.returning({ id: benchmarkSweeps.id });
return row;
@@ -89,7 +104,7 @@ export async function getSweep(id: string) {
const runIds = sweep.variants.map((v) => v.runId).filter((x): x is string => !!x);
const runs = runIds.length
? await db()
.select({ id: benchmarkRuns.id, state: benchmarkRuns.state, summary: benchmarkRuns.summary, resources: benchmarkRuns.resources, phase: benchmarkRuns.phase, error: benchmarkRuns.error })
.select({ id: benchmarkRuns.id, state: benchmarkRuns.state, summary: benchmarkRuns.summary, resources: benchmarkRuns.resources, phase: benchmarkRuns.phase, error: benchmarkRuns.error, meta: benchmarkRuns.meta })
.from(benchmarkRuns)
.where(inArray(benchmarkRuns.id, runIds))
: [];
@@ -99,13 +114,23 @@ export async function getSweep(id: string) {
export async function cancelSweep(id: string) {
const s = await db().query.benchmarkSweeps.findFirst({ columns: { state: true }, where: eq(benchmarkSweeps.id, id) });
if (!s) throw new SweepRequestError("not_found", "Sweep not found.", 404);
if (s.state === "queued") {
if (s.state === "queued" || s.state === "pending_approval") {
await db().update(benchmarkSweeps).set({ state: "cancelled", finishedAt: new Date() }).where(eq(benchmarkSweeps.id, id));
} else if (s.state === "running") {
await db().update(benchmarkSweeps).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkSweeps.id, id));
}
}
/** Let a sweep an agent asked for start, or turn it down. */
export async function decideSweep(id: string, approve: boolean) {
const res = await db()
.update(benchmarkSweeps)
.set(approve ? { state: "queued" } : { state: "cancelled", finishedAt: new Date(), error: "Rejected by the user." })
.where(and(eq(benchmarkSweeps.id, id), eq(benchmarkSweeps.state, "pending_approval")))
.returning({ id: benchmarkSweeps.id });
if (res.length === 0) throw new SweepRequestError("invalid", "This sweep doesn't wait for approval.", 409);
}
/** Delete a finished sweep with its runs (and their files). */
export async function deleteSweep(id: string) {
const s = await db().query.benchmarkSweeps.findFirst({ where: eq(benchmarkSweeps.id, id) });
+4
View File
@@ -5,4 +5,8 @@ import type { TokenScope } from "@/lib/db/schema";
export const SCOPE_LABEL: Record<TokenScope, string> = {
"models:read": "Look up Hub repos, list models, read jobs and disk space",
"downloads:create": "Request downloads (within the guardrails)",
"deployments:read": "List runtimes and deployments, read their state and logs",
"deployments:write": "Create deployments and edit, start, stop or delete its own ones (within the guardrails)",
"benchmarks:read": "Read benchmark runs, sweeps and comparisons",
"benchmarks:run": "Start benchmark runs, A/B runs and sweeps on its own deployments (within the guardrails)",
};
+34
View File
@@ -0,0 +1,34 @@
// `?wait=<seconds>` on /api/v1 status endpoints: instead of an agent polling (each call costs it a
// round of context), the request blocks until the state is settled or the time is up. Pure apart
// from the timers.
export const MAX_WAIT_S = 900;
const POLL_MS = 1_000;
/** `?wait=` as seconds, clamped to 0–900 (absent or invalid: 0, answer right away). */
export function parseWait(params: URLSearchParams): number {
const n = Number(params.get("wait"));
return Number.isFinite(n) && n > 0 ? Math.min(MAX_WAIT_S, Math.floor(n)) : 0;
}
/**
* Loads `load()` until `settled` holds, `seconds` pass or the client goes away; returns the last
* value and how long it waited. Re-reads the database once a second (cheap with SQLite).
*/
export async function waitFor<T>(
load: () => Promise<T>,
settled: (v: T) => boolean,
seconds: number,
opts: { signal?: AbortSignal; pollMs?: number; now?: () => number } = {},
): Promise<{ value: T; waitedS: number; timedOut: boolean }> {
const now = opts.now ?? Date.now;
const start = now();
const deadline = start + seconds * 1000;
let value = await load();
while (!settled(value) && now() < deadline && !opts.signal?.aborted) {
await new Promise((r) => setTimeout(r, Math.min(opts.pollMs ?? POLL_MS, Math.max(0, deadline - now()))));
value = await load();
}
const waitedS = Math.round((now() - start) / 1000);
return { value, waitedS, timedOut: !settled(value) && seconds > 0 };
}
+83 -8
View File
@@ -6,17 +6,21 @@ import { access, mkdir, readFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { asc, eq } from "drizzle-orm";
import { overTime } from "@/lib/agent-tuning";
import { engineLabel, metaNotes, modelLabel, withLoadLinks } from "@/lib/benchmark-meta";
import { REPORT_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
import { effectiveHardware, runSetup } from "@/lib/benchmark-snapshot";
import { db } from "@/lib/db/client";
import { apiKeys, benchmarkLogs, benchmarkRuns, type BenchmarkSummary, deployments, type LogStream, runtimes } from "@/lib/db/schema";
import { apiKeys, benchmarkLogs, benchmarkRuns, type BenchmarkSummary, deployments, type LogStream, type RunMeta, runtimes } from "@/lib/db/schema";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { coreEnv } from "@/lib/env";
import { abSummary } from "./ab-summary";
import { AB_DEFAULT_MAX_PAIRS, AB_DEFAULT_MDE_PCT, AB_FILE, abArgs, betterbenchBin, betterbenchPython, runArgs, SUMMARY_SCRIPT, SUMMARY_VERSION } from "./betterbench";
import { sanitizeLine } from "./job-log";
import { log } from "./log";
import { normalizePciAddress } from "./hardware";
import { errorCauses } from "./log-causes";
import { ResourceSampler } from "./resources";
import { type GpuTargets, ResourceSampler } from "./resources";
import { docker, workerImage } from "./runtimes";
type Current = {
@@ -25,6 +29,9 @@ type Current = {
deploymentIds: string[];
child: ChildProcess;
sampler: ResourceSampler | null;
/** Recorded at the start; the PCIe links are replaced by the ones seen under load at the end. */
meta: RunMeta | null;
metaB: RunMeta | null;
maxPairs: number | null;
cancelled: boolean;
lost: string | null;
@@ -140,6 +147,43 @@ async function target(deploymentId: string | null): Promise<Target | null> {
return { id: deploymentId, containerId: d.containerId, containerName: d.containerName, engine: d.engine, accelerator: d.accelerator };
}
/**
* What the sampler watches for the GPUs a run uses: NVIDIA via nvidia-smi, Intel/AMD via sysfs (and
* the fdinfo probe for Intel), and every GPU's link where sysfs shows it. Probes run from our own image.
*/
async function gpuTargets(metas: (RunMeta | null)[]): Promise<GpuTargets> {
const addrs = [...new Set(metas.flatMap((m) => m?.gpus.map((g) => g.pciAddress) ?? []).filter((a): a is string => !!a))];
const { hardware, nvidia } = await effectiveHardware();
const image = workerImage();
const used = (hardware?.gpus ?? []).filter((g) => addrs.includes(g.pciAddress));
const pciByIndex: Record<number, string> = {};
for (const g of nvidia) {
const addr = g.pciAddress ? normalizePciAddress(g.pciAddress) : `nvidia-${g.index}`;
if (addrs.includes(addr)) pciByIndex[g.index] = addr;
}
const others = used.filter((g) => g.vendor !== "nvidia");
return {
nvidia: image && Object.keys(pciByIndex).length ? { image, pciByIndex } : null,
sysfs: others.map((g, i) => ({ index: i, pciAddress: g.pciAddress, name: g.name ?? `${g.vendor} GPU`, vendor: g.vendor, vramTotalMb: g.vramMb })),
intelProbeImage: image,
linkAddresses: addrs.filter((a) => !a.startsWith("nvidia-")),
};
}
/** A/B notes: the shared host facts once, the engine and model per side. */
function abNotes(a: RunMeta | null, b: RunMeta | null, shared: Record<string, string>): Record<string, string> {
const pick = ["gpus", "pcie_max", "p2p", "rebar", "system", "description"];
const out: Record<string, string> = Object.fromEntries(Object.entries(shared).filter(([k]) => pick.includes(k)));
for (const [side, m] of [["a", a], ["b", b]] as const) {
if (!m) continue;
out[`${side}_engine`] = engineLabel(m) || m.runtime.engine;
out[`${side}_model`] = modelLabel(m);
if (m.contextSize != null) out[`${side}_ctx`] = String(m.contextSize);
if (m.concurrency != null) out[`${side}_concurrency`] = String(m.concurrency);
}
return out;
}
const endpoint = (t: Target) => `http://${t.containerName}:${ENGINE_PORT[t.engine]}/v1`;
async function start(run: typeof benchmarkRuns.$inferSelect) {
@@ -156,6 +200,10 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
const keys = needsKey ? (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt)).limit(1)).map((k) => k.key) : [];
const s = run.snapshot;
const maxPairs = run.settings.maxPairs ?? AB_DEFAULT_MAX_PAIRS;
// What runs on what, recorded now (the deployments are up, so the server's version is known).
const setup = await runSetup([a.id, b?.id ?? null]);
const [meta, metaB] = setup.metas;
const metaNotesA = meta ? metaNotes(meta, setup.system, run.description) : {};
const args =
run.kind === "ab" && b
? abArgs({
@@ -165,7 +213,12 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
out: join(dir, AB_FILE),
mdePct: run.settings.mdePct ?? AB_DEFAULT_MDE_PCT,
maxPairs,
notes: { a: s.deploymentName, b: run.snapshotB?.deploymentName ?? "B", ...(run.label ? { label: run.label } : {}) },
notes: {
a: s.deploymentName,
b: run.snapshotB?.deploymentName ?? "B",
...(run.label ? { label: run.label } : {}),
...abNotes(meta, metaB, metaNotesA),
},
})
: runArgs({
endpoint: endpoint(a),
@@ -179,6 +232,7 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
image: s.image,
...(s.options.modelFile ? { file: s.options.modelFile } : {}),
ctx: String(s.options.contextSize),
...metaNotesA,
...(run.label ? { label: run.label } : {}),
},
});
@@ -202,16 +256,18 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
: `Benchmarking ${s.deploymentName} (${s.repoId} on ${s.runtimeName}) with BetterBench`,
);
addLog(run.id, "system", `$ betterbench ${args.join(" ")}`, keys);
await db().update(benchmarkRuns).set({ state: "running", startedAt: new Date(), error: null, phase: null }).where(eq(benchmarkRuns.id, run.id));
await db()
.update(benchmarkRuns)
.set({ state: "running", startedAt: new Date(), error: null, phase: null, meta, metaB, system: setup.system })
.where(eq(benchmarkRuns.id, run.id));
// Resource use of the server(s) under test; GPUs when any side runs on NVIDIA.
// Resource use of the server(s) under test, and of the GPUs they use.
const c = docker();
const nvidia = a.accelerator === "nvidia" || b?.accelerator === "nvidia";
const sampler = c
? new ResourceSampler(
c,
[{ side: "a" as const, containerId: a.containerId }, ...(b ? [{ side: "b" as const, containerId: b.containerId }] : [])],
nvidia ? workerImage() : null,
await gpuTargets([meta, metaB]),
)
: null;
await sampler?.start().catch((err) => log.warn(`resource sampling failed: ${message(err)}`));
@@ -223,6 +279,8 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
deploymentIds: [a.id, ...(b ? [b.id] : [])],
child,
sampler,
meta,
metaB,
maxPairs: run.kind === "ab" ? maxPairs : null,
cancelled: false,
lost: null,
@@ -247,6 +305,14 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
}
const resources = (await cur.sampler?.stop().catch(() => null)) ?? null;
if (current === cur) current = null;
if (resources?.links) {
const loaded = (m: RunMeta | null) => withLoadLinks(m, resources.links, !!m?.overridden.includes("pcie link"));
await db()
.update(benchmarkRuns)
.set({ meta: loaded(cur.meta), metaB: loaded(cur.metaB) })
.where(eq(benchmarkRuns.id, id))
.catch((err) => log.warn(`benchmark ${id}: link update failed: ${message(err)}`));
}
const dir = runDir(id);
const results = join(dir, cur.kind === "ab" ? AB_FILE : RESULTS_FILE);
const hasReport = cur.kind === "run" && (await exists(join(dir, REPORT_FILE)));
@@ -301,12 +367,21 @@ export async function tickBenchmarks(): Promise<void> {
if (starting) return;
if (current) {
const cur = current;
const [run] = await db().select({ cancel: benchmarkRuns.cancelRequestedAt }).from(benchmarkRuns).where(eq(benchmarkRuns.id, cur.runId));
const [run] = await db()
.select({ cancel: benchmarkRuns.cancelRequestedAt, startedAt: benchmarkRuns.startedAt, timeLimitS: benchmarkRuns.timeLimitS })
.from(benchmarkRuns)
.where(eq(benchmarkRuns.id, cur.runId));
if (!run || run.cancel) {
cur.cancelled = true;
stop(cur);
return;
}
// Agent runs have a time limit (Settings → API tokens).
if (overTime(run.startedAt, run.timeLimitS)) {
cur.lost = `Stopped: the run exceeded the time limit for agent runs (${Math.round((run.timeLimitS ?? 0) / 60)} min).`;
stop(cur);
return;
}
for (const depId of cur.deploymentIds) {
const [d] = await db().select({ state: deployments.state }).from(deployments).where(eq(deployments.id, depId));
if (!d || d.state !== "running") {
+18 -2
View File
@@ -29,6 +29,12 @@ describe("betterbench runArgs", () => {
]);
});
it("drops --quick when passes are given (BetterBench refuses both)", () => {
const args = runArgs({ ...base, settings: { quick: true, passes: 2, warmup: null, phases: [] }, notes: {} });
assert.ok(!args.includes("--quick"));
assert.deepEqual(args.slice(args.indexOf("--passes"), args.indexOf("--passes") + 2), ["--passes", "2"]);
});
it("passes explicit passes and warmup, and no phase flags for a full run", () => {
const args = runArgs({ ...base, maxModelLen: null, settings: { quick: false, passes: 10, warmup: 2, phases: [] }, notes: {} });
assert.ok(args.includes("--passes") && args[args.indexOf("--passes") + 1] === "10");
@@ -46,8 +52,18 @@ describe("betterbench runArgs", () => {
describe("parseNvidiaSmi", () => {
it("reads nvidia-smi CSV", async () => {
const { parseNvidiaSmi } = await import("./runtimes");
assert.deepEqual(parseNvidiaSmi("0, GPU-02d5eae7-e371-6b8f-adaf-2b18648bdb84, NVIDIA GeForce RTX 3080, 10240, 617.14\n"), [
{ vendor: "nvidia", index: 0, uuid: "GPU-02d5eae7-e371-6b8f-adaf-2b18648bdb84", name: "NVIDIA GeForce RTX 3080", memoryMb: 10240, driver: "617.14" },
assert.deepEqual(parseNvidiaSmi("0, GPU-02d5eae7-e371-6b8f-adaf-2b18648bdb84, NVIDIA GeForce RTX 3080, 10240, 617.14, 00000000:2B:00.0, 1, 4, 16, 16\n"), [
{
vendor: "nvidia",
index: 0,
uuid: "GPU-02d5eae7-e371-6b8f-adaf-2b18648bdb84",
name: "NVIDIA GeForce RTX 3080",
memoryMb: 10240,
driver: "617.14",
pciAddress: "0000:2b:00.0",
linkCurrent: { gen: 1, width: 16 },
linkMax: { gen: 4, width: 16 },
},
]);
assert.deepEqual(parseNvidiaSmi("NVIDIA-SMI has failed"), []);
});
+2 -1
View File
@@ -34,7 +34,8 @@ export function runArgs(o: {
o.out,
// Kaname knows the context window; llama-server's /v1/models doesn't report it.
...(o.maxModelLen ? ["--max-model-len", String(o.maxModelLen)] : []),
...(s.quick ? ["--quick"] : []),
// BetterBench refuses --quick together with --passes; explicit passes win.
...(s.quick && s.passes == null ? ["--quick"] : []),
...(s.passes != null ? ["--passes", String(s.passes)] : []),
...(s.warmup != null ? ["--warmup", String(s.warmup)] : []),
...s.phases.map((p) => `--${p}`),
+19 -2
View File
@@ -6,13 +6,14 @@ import { stat } from "node:fs/promises";
import { join } from "node:path";
import { and, asc, desc, eq, inArray, lt } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { apiKeys, deploymentLogs, deployments, type LogStream, models, runtimes, workerState } from "@/lib/db/schema";
import { apiKeys, deploymentLogs, deployments, type EngineInfo, type LogStream, models, type RuntimeEngine, runtimes, workerState } from "@/lib/db/schema";
import { buildCommand, CONTAINER_MODELS_DIR, ENGINE_PORT, redactCommand, renderCommand } from "@/lib/deploy-command";
import { ACCELERATOR_DEVICES } from "@/lib/runtimes-shared";
import { coreEnv } from "@/lib/env";
import { formatBytes } from "@/lib/format";
import { sanitizeLine } from "./job-log";
import { log } from "./log";
import { fetchEngineInfo, versionFromLog } from "./engine-info";
import { errorCauses } from "./log-causes";
import { docker } from "./runtimes";
import type { DockerClient } from "./docker/client";
@@ -168,6 +169,8 @@ async function start(c: DockerClient, d: Deployment) {
ShmSize: runtime.shmSizeMb ? runtime.shmSizeMb * 2 ** 20 : undefined,
Devices: devices.map((p) => ({ PathOnHost: p, PathInContainer: p, CgroupPermissions: "rwm" })),
DeviceRequests: deviceRequests,
// Images that don't run as root need the render/video group to open /dev/dri.
GroupAdd: devices.some((p) => p.startsWith("/dev/dri")) ? (host.driGroups ?? []).map(String) : [],
CapAdd: runtime.numaTuning ? ["SYS_NICE"] : [],
SecurityOpt: runtime.numaTuning ? ["seccomp=unconfined"] : [],
PortBindings: d.hostPort ? { [portKey]: [{ HostPort: String(d.hostPort) }] } : {},
@@ -196,6 +199,7 @@ async function start(c: DockerClient, d: Deployment) {
error: null,
exitCode: null,
stats: null,
engineInfo: null,
});
await c.startContainer(created.Id);
// A fresh container: everything it printed belongs to this run. (Following before the start
@@ -241,6 +245,19 @@ async function healthy(name: string, port: number): Promise<boolean> {
}
}
/** Version, slots and context from the server; the version from its startup log if it doesn't say. */
async function engineInfo(d: Deployment, engine: RuntimeEngine, base: string): Promise<EngineInfo> {
const key = d.options.requireApiKey ? ((await loadApiKeys())[0] ?? null) : null;
const info = await fetchEngineInfo(engine, base, key);
if (!info.version) {
await flushDeploymentLogs();
const lines = await db().select({ line: deploymentLogs.line }).from(deploymentLogs).where(eq(deploymentLogs.deploymentId, d.id)).orderBy(asc(deploymentLogs.id)).limit(500);
info.version = versionFromLog(engine, lines.map((l) => l.line));
}
if (info.version) addLog(d.id, "system", `Engine: ${engine} ${info.version}${info.slots ? `, ${info.slots} slots` : ""}${info.contextSize ? `, context ${info.contextSize}` : ""}`);
return { ...info, at: new Date().toISOString() };
}
// --- reconcile -----------------------------------------------------------------------------------
const lastStats = new Map<string, number>();
@@ -284,7 +301,7 @@ async function reconcileOne(c: DockerClient, d: Deployment) {
const now = new Date();
const secs = d.startedAt ? ((now.getTime() - d.startedAt.getTime()) / 1000).toFixed(1) : "?";
addLog(d.id, "system", `Ready after ${secs} s.`);
await update(d.id, { state: "running", readyAt: now });
await update(d.id, { state: "running", readyAt: now, engineInfo: await engineInfo(d, runtime?.engine ?? "llama.cpp", `http://${d.containerName}:${port}`) });
} else if (d.startedAt && Date.now() - d.startedAt.getTime() > START_TIMEOUT_MS) {
await c.stopContainer(d.containerId).catch(() => {});
await c.removeContainer(d.containerId).catch(() => {});
+45
View File
@@ -0,0 +1,45 @@
// What a ready inference server says about itself: version, slots and context. llama.cpp: GET /props
// (build_info "b11429-d81235049", total_slots, default_generation_settings.n_ctx; checked with build
// 11429). vLLM: GET /version and GET /v1/models (max_model_len). Startup log lines as a fallback.
import type { EngineInfo, RuntimeEngine } from "@/lib/db/schema";
type Json = Record<string, unknown>;
const int = (v: unknown) => (typeof v === "number" && Number.isInteger(v) && v > 0 ? v : null);
const str = (v: unknown) => (typeof v === "string" && v.trim() ? v.trim().slice(0, 100) : null);
export function parseLlamaProps(props: Json | null): Omit<EngineInfo, "at"> {
const gen = (props?.default_generation_settings ?? {}) as Json;
return { version: str(props?.build_info), slots: int(props?.total_slots), contextSize: int(gen.n_ctx) };
}
export function parseVllm(version: Json | null, models: Json | null): Omit<EngineInfo, "at"> {
const data = Array.isArray(models?.data) ? (models.data as Json[]) : [];
return { version: str(version?.version), slots: null, contextSize: int(data[0]?.max_model_len) };
}
/** "build: 11429 (d8123504)" (llama.cpp), "vLLM API server version 0.31.0" (vLLM and most forks). */
export function versionFromLog(engine: RuntimeEngine, lines: string[]): string | null {
const re = engine === "llama.cpp" ? /\bbuild[:=]\s*(\d+)\s*\(([0-9a-f]+)\)/ : /\bversion\s+v?(\d+\.\d+[\w.+-]*)/i;
for (const l of lines) {
const m = l.match(re);
if (m) return engine === "llama.cpp" ? `b${m[1]}-${m[2]}` : m[1];
}
return null;
}
async function getJson(url: string, key: string | null): Promise<Json | null> {
try {
const res = await fetch(url, { headers: key ? { Authorization: `Bearer ${key}` } : {}, signal: AbortSignal.timeout(3_000) });
return res.ok ? ((await res.json()) as Json) : null;
} catch {
return null;
}
}
/** Ask the server at http://name:port; `key` when the deployment requires an API key. */
export async function fetchEngineInfo(engine: RuntimeEngine, base: string, key: string | null): Promise<Omit<EngineInfo, "at">> {
if (engine === "llama.cpp") return parseLlamaProps(await getJson(`${base}/props`, key));
const [version, models] = await Promise.all([getJson(`${base}/version`, key), getJson(`${base}/v1/models`, key)]);
return parseVllm(version, models);
}
+169
View File
@@ -0,0 +1,169 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { estimateVramMb } from "@/lib/deploy-command";
import { aggregateFdinfo, drmUtilization, parseFdinfo, powerBetween, readAmdUsage, readHwmon } from "./gpu-sysfs";
import type { SysFs } from "./hardware";
import { parseGpuLine, summarizeSamples } from "./resources";
import { parseDriGroups } from "./runtimes";
/** An in-memory sysfs: files plus directory links. */
function memFs(files: Record<string, string>, links: Record<string, string> = {}): SysFs {
const resolve = (p: string) => {
const hit = Object.keys(links).find((l) => p === l || p.startsWith(`${l}/`));
return hit ? links[hit] + p.slice(hit.length) : p;
};
return {
read: async (p) => files[resolve(p)]?.trim() ?? null,
resolve: async (p) => resolve(p),
list: async (d) => {
const dir = `${resolve(d)}/`;
return [...new Set(Object.keys(files).filter((k) => k.startsWith(dir)).map((k) => k.slice(dir.length).split("/")[0]))];
},
};
}
const xe = (client: number, vramKiB: number, rcs: number, ccs: number, total: number) => `pos:\t0
flags:\t02100002
drm-driver:\txe
drm-client-id:\t${client}
drm-pdev:\t0000:03:00.0
drm-total-system:\t0
drm-resident-system:\t0
drm-total-gtt:\t12 KiB
drm-total-vram0:\t${vramKiB + 1024} KiB
drm-resident-vram0:\t${vramKiB} KiB
drm-cycles-rcs:\t${rcs}
drm-total-cycles-rcs:\t${total}
drm-cycles-ccs:\t${ccs}
drm-total-cycles-ccs:\t${total}
`;
describe("DRM fdinfo", () => {
it("parses xe: resident VRAM, cycles per engine class", () => {
const c = parseFdinfo(xe(42, 9_437_184, 1000, 30_000, 50_000))!;
assert.equal(c.pdev, "0000:03:00.0");
assert.equal(c.clientId, "42");
assert.equal(c.vramBytes, 9_437_184 * 1024);
assert.deepEqual(c.cycles, { rcs: 1000, ccs: 30_000 });
assert.deepEqual(c.totalCycles, { rcs: 50_000, ccs: 50_000 });
});
it("parses i915 (local memory, nanoseconds) and amdgpu's legacy keys", () => {
const i915 = parseFdinfo("drm-driver: i915\ndrm-pdev: 0000:00:02.0\ndrm-client-id: 7\ndrm-engine-render: 1000000 ns\ndrm-engine-capacity-video: 2\ndrm-total-local0: 1024 KiB\ndrm-resident-local0: 512 KiB\n")!;
assert.equal(i915.vramBytes, 512 * 1024);
assert.deepEqual(i915.ns, { render: 1_000_000 });
const amd = parseFdinfo("drm-driver:\tamdgpu\ndrm-pdev:\t0000:0a:00.0\ndrm-client-id:\t3\ndrm-memory-vram:\t2048 KiB\ndrm-memory-gtt:\t16 KiB\ndrm-engine-gfx:\t5000 ns\n")!;
assert.equal(amd.vramBytes, 2048 * 1024);
assert.deepEqual(amd.ns, { gfx: 5000 });
assert.equal(parseFdinfo("pos: 0\nflags: 02\n"), null);
});
it("counts each client once and takes the GPU clock as is", () => {
const s = aggregateFdinfo(1000, [xe(1, 1024, 10, 20, 100), xe(1, 1024, 10, 20, 100), xe(2, 2048, 5, 0, 110), "pos: 0\n"]);
const g = s.gpus["0000:03:00.0"];
assert.equal(g.vramBytes, 3072 * 1024);
assert.deepEqual(g.cycles, { rcs: 15, ccs: 20 });
assert.deepEqual(g.totalCycles, { rcs: 110, ccs: 110 });
});
it("reports the busiest engine class between two snapshots", () => {
const a = aggregateFdinfo(0, [xe(1, 1024, 0, 0, 1000)]).gpus["0000:03:00.0"];
const b = aggregateFdinfo(2000, [xe(1, 1024, 100, 800, 2000)]).gpus["0000:03:00.0"];
assert.equal(drmUtilization(a, b, 2), 80);
assert.equal(drmUtilization(undefined, b, 2), null);
// A client that exited makes the sum drop: idle, not negative.
const c = aggregateFdinfo(4000, [xe(2, 0, 0, 0, 3000)]).gpus["0000:03:00.0"];
assert.equal(drmUtilization(b, c, 2), 0);
// Nanosecond engines: busy time over wall time.
assert.equal(drmUtilization({ vramBytes: 0, cycles: {}, totalCycles: {}, ns: { gfx: 0 } }, { vramBytes: 0, cycles: {}, totalCycles: {}, ns: { gfx: 1e9 } }, 2), 50);
});
});
describe("hwmon and amdgpu sysfs", () => {
const dev = "/sys/devices/pci0000:00/0000:00:01.0/0000:03:00.0";
const fs = memFs(
{
[`${dev}/hwmon/hwmon3/name`]: "xe",
[`${dev}/hwmon/hwmon3/energy1_input`]: "5000000",
[`${dev}/hwmon/hwmon3/power1_max`]: "200000000",
[`${dev}/hwmon/hwmon3/temp2_input`]: "61000",
[`${dev}/hwmon/hwmon3/temp2_label`]: "pkg",
[`${dev}/hwmon/hwmon3/temp3_input`]: "70000",
[`${dev}/hwmon/hwmon3/temp3_label`]: "vram",
"/sys/devices/pci0000:00/0000:0a:00.0/hwmon/hwmon1/power1_average": "150000000",
"/sys/devices/pci0000:00/0000:0a:00.0/hwmon/hwmon1/temp1_input": "55000",
"/sys/devices/pci0000:00/0000:0a:00.0/mem_info_vram_used": String(4 * 2 ** 30),
"/sys/devices/pci0000:00/0000:0a:00.0/gpu_busy_percent": "87",
},
{ "/sys/bus/pci/devices/0000:03:00.0": dev, "/sys/bus/pci/devices/0000:0a:00.0": "/sys/devices/pci0000:00/0000:0a:00.0" },
);
it("reads xe's energy counter and package temperature", async () => {
assert.deepEqual(await readHwmon(fs, "0000:03:00.0"), { energyUj: 5_000_000, powerW: null, tempC: 61 });
});
it("reads amdgpu's power, temperature, VRAM in use and busy percent", async () => {
assert.deepEqual(await readHwmon(fs, "0000:0a:00.0"), { energyUj: null, powerW: 150, tempC: 55 });
assert.deepEqual(await readAmdUsage(fs, "0000:0a:00.0"), { vramUsedMb: 4096, util: 87 });
});
it("turns energy into power between readings", () => {
assert.equal(powerBetween({ energyUj: 1_000_000, powerW: null, tempC: null }, { energyUj: 401_000_000, powerW: null, tempC: null }, 2), 200);
assert.equal(powerBetween(null, { energyUj: 5, powerW: null, tempC: null }, 0), null);
assert.equal(powerBetween(null, { energyUj: null, powerW: 150, tempC: null }, 0), 150);
});
});
describe("GPU summaries", () => {
it("keeps unknown figures unknown and adds temperature", () => {
const s = summarizeSamples(
[],
[
{ index: 0, name: "Intel Arc Pro B65", pciAddress: "0000:03:00.0", vramTotalMb: 32768, vramUsedMb: null, util: null, powerW: 120, tempC: 60 },
{ index: 0, name: "Intel Arc Pro B65", pciAddress: "0000:03:00.0", vramTotalMb: 32768, vramUsedMb: null, util: null, powerW: 180, tempC: 70 },
],
4,
);
assert.deepEqual(s.gpus[0], {
index: 0,
name: "Intel Arc Pro B65",
pciAddress: "0000:03:00.0",
vramTotalMb: 32768,
vramPeakMb: null,
vramAvgMb: null,
utilAvg: null,
utilPeak: null,
powerAvgW: 150,
powerPeakW: 180,
tempAvgC: 65,
tempPeakC: 70,
});
assert.equal(parseGpuLine("0, NVIDIA GeForce RTX 3080, 10240, 812, 3, 21.5, 4, 16, 47")?.tempC, 47);
});
it("reads /dev/dri group IDs", () => {
assert.deepEqual(parseDriGroups(["/dev/dri/card0 44", "/dev/dri/renderD128 993", "/dev/dri/renderD129 993", "/dev/dri/by-path 0", "stat: error"]), [44, 993]);
});
});
describe("VRAM estimate", () => {
const GiB = 2 ** 30;
it("adds weights, KV cache and buffers for llama.cpp with all layers on the GPU", () => {
const f16 = estimateVramMb(5 * GiB, 32768, "llama.cpp", {}, 32768)!;
const q8 = estimateVramMb(5 * GiB, 32768, "llama.cpp", { cacheTypeK: "q8_0", cacheTypeV: "q8_0" }, 32768)!;
assert.ok(f16 > 5120 + 1024 && f16 < 5120 + 1024 + 8192, String(f16));
assert.ok(q8 < f16);
assert.equal(estimateVramMb(5 * GiB, 4096, "llama.cpp", { gpuLayers: "all" }, null), estimateVramMb(5 * GiB, 4096, "llama.cpp", {}, null));
});
it("can't tell partial offload", () => {
assert.equal(estimateVramMb(5 * GiB, 4096, "llama.cpp", { gpuLayers: "20" }, 32768), null);
assert.equal(estimateVramMb(5 * GiB, 4096, "llama.cpp", { cpuMoe: true }, 32768), null);
});
it("uses vLLM's memory share of the VRAM", () => {
assert.equal(estimateVramMb(5 * GiB, 4096, "vllm", {}, 32768), Math.ceil(32768 * 0.9));
assert.equal(estimateVramMb(5 * GiB, 4096, "vllm", { gpuMemoryUtilization: 0.5 }, 32768), 16384);
assert.equal(estimateVramMb(5 * GiB, 4096, "vllm", {}, null), null);
});
});
+175
View File
@@ -0,0 +1,175 @@
// GPU telemetry without nvidia-smi, for Intel and AMD GPUs.
// - hwmon (sysfs, readable unprivileged): power (energy counter or power reading) and temperature.
// - AMD (amdgpu): VRAM in use and busy percent are plain sysfs files.
// - Intel (xe, i915): the driver has no whole-GPU VRAM/utilization file; both are only reported per
// process in DRM fdinfo (/proc/<pid>/fdinfo, kernel "drm-usage-stats"). A probe container in the
// host's PID namespace dumps those (INTEL_PROBE_SCRIPT); parsing and aggregation happen here.
// Pure parsers for tests; the readers take a SysFs.
import { posix } from "node:path";
import type { SysFs } from "./hardware";
const { join } = posix;
export type HwmonReading = { energyUj: number | null; powerW: number | null; tempC: number | null };
const num = (s: string | null) => (s != null && /^-?\d+$/.test(s.trim()) ? Number(s.trim()) : null);
/**
* Power and temperature from the device's hwmon: an energy counter (µJ, xe: energy1_input) when there
* is one, else a power reading (µW, amdgpu: power1_average); the "pkg"/"edge" temperature, else the
* highest one.
*/
export async function readHwmon(fs: SysFs, pciAddress: string): Promise<HwmonReading> {
const dev = await fs.resolve(join("/sys/bus/pci/devices", pciAddress));
const dirs = (await fs.list(join(dev, "hwmon"))).filter((d) => d.startsWith("hwmon"));
const out: HwmonReading = { energyUj: null, powerW: null, tempC: null };
for (const d of dirs) {
const h = join(dev, "hwmon", d);
const files = await fs.list(h);
const energy = files.filter((f) => /^energy\d+_input$/.test(f)).sort()[0];
if (energy && out.energyUj == null) out.energyUj = num(await fs.read(join(h, energy)));
for (const f of ["power1_average", "power1_input"]) {
if (out.powerW != null || !files.includes(f)) continue;
const uw = num(await fs.read(join(h, f)));
if (uw != null) out.powerW = uw / 1e6;
}
const temps: { label: string; c: number }[] = [];
for (const f of files.filter((x) => /^temp\d+_input$/.test(x))) {
const v = num(await fs.read(join(h, f)));
if (v == null || v <= 0) continue;
const label = (await fs.read(join(h, f.replace("_input", "_label")))) ?? "";
temps.push({ label: label.toLowerCase(), c: v / 1000 });
}
const main = temps.find((t) => t.label === "pkg" || t.label === "edge") ?? temps.sort((a, b) => b.c - a.c)[0];
if (main && out.tempC == null) out.tempC = main.c;
}
return out;
}
/** amdgpu's own whole-GPU figures. */
export async function readAmdUsage(fs: SysFs, pciAddress: string): Promise<{ vramUsedMb: number | null; util: number | null }> {
const dev = await fs.resolve(join("/sys/bus/pci/devices", pciAddress));
const used = num(await fs.read(join(dev, "mem_info_vram_used")));
const busy = num(await fs.read(join(dev, "gpu_busy_percent")));
return { vramUsedMb: used != null ? Math.round(used / 2 ** 20) : null, util: busy };
}
/** Power between two readings: from the energy counter if both have one, else the instant reading. */
export function powerBetween(prev: HwmonReading | null, cur: HwmonReading, seconds: number): number | null {
if (prev?.energyUj != null && cur.energyUj != null && cur.energyUj >= prev.energyUj && seconds > 0) return (cur.energyUj - prev.energyUj) / 1e6 / seconds;
return cur.powerW;
}
// --- DRM fdinfo ---------------------------------------------------------------------------------
export type DrmClient = {
pdev: string;
clientId: string;
/** Bytes resident in device memory (regions named vram* / local*). */
vramBytes: number;
/** Per engine class: busy cycles and the GPU's total cycles (xe), or busy nanoseconds (i915, amdgpu). */
cycles: Record<string, number>;
totalCycles: Record<string, number>;
ns: Record<string, number>;
};
const UNIT: Record<string, number> = { "": 1, KiB: 1024, MiB: 2 ** 20, GiB: 2 ** 30 };
/** One /proc/<pid>/fdinfo/<fd> of a DRM client; null for other files. */
export function parseFdinfo(text: string): DrmClient | null {
const kv = new Map<string, string>();
for (const line of text.split("\n")) {
const i = line.indexOf(":");
if (i > 0) kv.set(line.slice(0, i).trim(), line.slice(i + 1).trim());
}
const pdev = kv.get("drm-pdev");
const clientId = kv.get("drm-client-id");
if (!pdev || !clientId) return null;
const c: DrmClient = { pdev: pdev.toLowerCase(), clientId, vramBytes: 0, cycles: {}, totalCycles: {}, ns: {} };
// Resident is what occupies VRAM now; older drivers only report total or the legacy drm-memory-*.
const mem: Record<"resident" | "total" | "memory", number> = { resident: 0, total: 0, memory: 0 };
const seen = { resident: false, total: false, memory: false };
for (const [k, v] of kv) {
let m = k.match(/^drm-(resident|total|memory)-(.+)$/);
if (m && /vram|local/i.test(m[2])) {
const [, n, unit = ""] = v.match(/^(\d+)\s*(KiB|MiB|GiB)?$/) ?? [];
if (n == null) continue;
const kind = m[1] as keyof typeof mem;
mem[kind] += Number(n) * (UNIT[unit] ?? 1);
seen[kind] = true;
continue;
}
if ((m = k.match(/^drm-total-cycles-(.+)$/))) c.totalCycles[m[1]] = Number(v) || 0;
else if ((m = k.match(/^drm-cycles-(.+)$/))) c.cycles[m[1]] = Number(v) || 0;
else if ((m = k.match(/^drm-engine-(.+)$/)) && !k.startsWith("drm-engine-capacity-")) c.ns[m[1]] = Number(v.replace(/\s*ns$/, "")) || 0;
}
c.vramBytes = seen.resident ? mem.resident : seen.total ? mem.total : mem.memory;
return c;
}
export type DrmSnapshot = { t: number; gpus: Record<string, { vramBytes: number; cycles: Record<string, number>; totalCycles: Record<string, number>; ns: Record<string, number> }> };
/**
* Sum the clients per GPU. One client shows up once per open file descriptor (and process), so
* duplicates by client id are counted once. The GPU's total cycles are a clock, not a sum: max.
*/
export function aggregateFdinfo(t: number, texts: string[]): DrmSnapshot {
const seen = new Set<string>();
const gpus: DrmSnapshot["gpus"] = {};
for (const text of texts) {
const c = parseFdinfo(text);
if (!c || seen.has(`${c.pdev}#${c.clientId}`)) continue;
seen.add(`${c.pdev}#${c.clientId}`);
const g = (gpus[c.pdev] ??= { vramBytes: 0, cycles: {}, totalCycles: {}, ns: {} });
g.vramBytes += c.vramBytes;
for (const [k, v] of Object.entries(c.cycles)) g.cycles[k] = (g.cycles[k] ?? 0) + v;
for (const [k, v] of Object.entries(c.totalCycles)) g.totalCycles[k] = Math.max(g.totalCycles[k] ?? 0, v);
for (const [k, v] of Object.entries(c.ns)) g.ns[k] = (g.ns[k] ?? 0) + v;
}
return { t, gpus };
}
/**
* Busy percent of the busiest engine class between two snapshots (like intel_gpu_top's headline).
* Clients that exit in between make a sum drop; those classes count as idle rather than negative.
*/
export function drmUtilization(prev: DrmSnapshot["gpus"][string] | undefined, cur: DrmSnapshot["gpus"][string], seconds: number): number | null {
if (!prev || seconds <= 0) return null;
const busy: number[] = [];
for (const cls of Object.keys(cur.cycles)) {
const dc = cur.cycles[cls] - (prev.cycles[cls] ?? 0);
const dt = (cur.totalCycles[cls] ?? 0) - (prev.totalCycles[cls] ?? 0);
if (dt > 0) busy.push(Math.max(0, dc) / dt);
}
for (const cls of Object.keys(cur.ns)) busy.push(Math.max(0, cur.ns[cls] - (prev.ns[cls] ?? 0)) / (seconds * 1e9));
if (busy.length === 0) return null;
return Math.min(100, Math.max(...busy) * 100);
}
/**
* Runs inside the probe container (Node from Kaname's own image): every interval, the fdinfo of every
* open DRM file on the host, one JSON line. Reads only; prints nothing else.
*/
export const INTEL_PROBE_SCRIPT = `
const fs = require("fs");
const every = Number(process.argv[1]) || 2000;
function tick() {
const f = [];
let pids = [];
try { pids = fs.readdirSync("/proc").filter((p) => /^\\d+$/.test(p)); } catch {}
for (const p of pids) {
let fds = [];
try { fds = fs.readdirSync("/proc/" + p + "/fdinfo"); } catch { continue; }
for (const d of fds) {
try {
const t = fs.readFileSync("/proc/" + p + "/fdinfo/" + d, "utf8");
if (t.includes("drm-client-id:")) f.push(t);
} catch {}
}
}
process.stdout.write(JSON.stringify({ t: Date.now(), f }) + "\\n");
}
tick();
setInterval(tick, every);
`;
+284
View File
@@ -0,0 +1,284 @@
import assert from "node:assert/strict";
import { before, describe, it } from "node:test";
import { fetchEngineInfo, parseLlamaProps, parseVllm, versionFromLog } from "./engine-info";
import { currentLinks, detectHardware, gpuDisplayName, type SysFs, largestBarMb, mountDevice, normalizePciAddress, parseCpu, parseP2p, pciName } from "./hardware";
import { fastestLinks, parseGpuLine, summarizeSamples } from "./resources";
import { parseNvidiaSmi, repoDigest } from "./runtimes";
const GiB = 2 ** 30;
const hex = (n: number) => `0x${n.toString(16).padStart(16, "0")}`;
/** A `resource` line: start, end, flags (0x0014220c = 64-bit prefetchable memory). */
const bar = (start: number, size: number) => `${hex(start)} ${hex(start + size - 1)} 0x000000000014220c`;
const EMPTY = `${hex(0)} ${hex(0)} 0x0000000000000000`;
const PCI_IDS = `# test pci.ids
10de NVIDIA Corporation
\t2684 AD102 [GeForce RTX 4090]
8086 Intel Corporation
\te211 Battlemage G31 [Arc Pro B65]
\t\t8086 1234 Arc Pro B65 32GB
\te20b Battlemage G21 [Arc B580]
1af4 Red Hat, Inc.
`;
const CPUINFO = [0, 1, 2, 3]
.map((p) => `processor\t: ${p}\nmodel name\t: AMD EPYC 9124 16-Core Processor\nphysical id\t: 0\ncore id\t\t: ${p % 2}\nflags\t\t: fpu avx2 hypervisor\n`)
.join("\n");
const files = new Map<string, string>();
const links = new Map<string, string>();
/** An in-memory sysfs: files plus directory symlinks (sysfs names contain ":", which Windows can't store). */
function memFs(): SysFs {
const resolve = (p: string): string => {
for (let i = 0; i < 10; i++) {
const hit = [...links.keys()].find((l) => p === l || p.startsWith(`${l}/`));
if (!hit) return p;
p = links.get(hit)! + p.slice(hit.length);
}
return p;
};
return {
read: async (p) => files.get(resolve(p))?.trim() ?? null,
resolve: async (p) => resolve(p),
list: async (d) => {
const dir = `${resolve(d)}/`;
const names = [...files.keys(), ...links.keys()].filter((k) => k.startsWith(dir)).map((k) => k.slice(dir.length).split("/")[0]);
return [...new Set(names)];
},
};
}
const file = (path: string, content: string) => files.set(`/${path}`, content);
const link = (path: string, target: string) => links.set(`/${path}`, `/${target}`);
before(() => {
// Intel Arc Pro B65: root port 00:01.0 → on-card switch (01:00.0 up, 02:01.0 down) → GPU 03:00.0.
const rp = "sys/devices/pci0000:00/0000:00:01.0";
const up = `${rp}/0000:01:00.0`;
const down = `${up}/0000:02:01.0`;
const gpu = `${down}/0000:03:00.0`;
file(`${rp}/vendor`, "0x1022");
file(`${up}/vendor`, "0x8086");
file(`${up}/current_link_speed`, "16.0 GT/s PCIe");
file(`${up}/current_link_width`, "8");
file(`${up}/max_link_speed`, "32.0 GT/s PCIe");
file(`${up}/max_link_width`, "16");
file(`${down}/vendor`, "0x8086");
file(`${gpu}/vendor`, "0x8086");
file(`${gpu}/device`, "0xe211");
file(`${gpu}/subsystem_vendor`, "0x8086");
file(`${gpu}/subsystem_device`, "0x1234");
file(`${gpu}/class`, "0x030000");
file(`${gpu}/uevent`, "DRIVER=xe\nPCI_CLASS=30000\nPCI_SLOT_NAME=0000:03:00.0");
// What the GPU function itself reports: the switch-internal link.
file(`${gpu}/current_link_speed`, "2.5 GT/s PCIe");
file(`${gpu}/current_link_width`, "1");
file(`${gpu}/resource`, [bar(0xa0000000, 16 * 2 ** 20), EMPTY, bar(0x4000000000, 32 * GiB)].join("\n"));
file(`${gpu}/tile0/physical_vram_size_bytes`, String(32 * GiB));
link("sys/bus/pci/devices/0000:03:00.0", gpu);
// NVIDIA card directly on a root port, 256 MiB BAR (no ReBAR).
const nv = "sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0";
file("sys/devices/pci0000:00/0000:00:03.0/vendor", "0x1022");
file(`${nv}/vendor`, "0x10de");
file(`${nv}/device`, "0x2684");
file(`${nv}/class`, "0x030000");
file(`${nv}/uevent`, "DRIVER=nvidia");
file(`${nv}/current_link_speed`, "16.0 GT/s PCIe");
file(`${nv}/current_link_width`, "16");
file(`${nv}/max_link_speed`, "16.0 GT/s PCIe");
file(`${nv}/max_link_width`, "16");
file(`${nv}/resource`, [bar(0xb0000000, 16 * 2 ** 20), bar(0x6000000000, 256 * 2 ** 20)].join("\n"));
link("sys/bus/pci/devices/0000:05:00.0", nv);
file("sys/module/nvidia/version", "580.82.07");
// A virtio NIC: not a GPU.
file("sys/devices/pci0000:00/0000:00:12.0/vendor", "0x1af4");
file("sys/devices/pci0000:00/0000:00:12.0/class", "0x020000");
link("sys/bus/pci/devices/0000:00:12.0", "sys/devices/pci0000:00/0000:00:12.0");
file("usr/share/misc/pci.ids", PCI_IDS);
file("proc/cpuinfo", CPUINFO);
file("proc/meminfo", "MemTotal: 65536000 kB\nMemFree: 1 kB\n");
file("sys/class/dmi/id/sys_vendor", "QEMU");
file("sys/class/dmi/id/product_name", "Standard PC (Q35 + ICH9, 2009)");
// Models on /dev/nvme0n1p2 (259:2).
file("proc/self/mountinfo", ["22 1 259:1 / / rw - ext4 /dev/nvme0n1p1 rw", "1521 1471 259:2 /srv/models /models rw,relatime - ext4 /dev/nvme0n1p2 rw"].join("\n"));
const disk = "sys/devices/pci0000:00/0000:00:06.0/nvme/nvme0/nvme0n1";
file(`${disk}/device/model`, "Samsung SSD 990 PRO 2TB ");
file(`${disk}/queue/rotational`, "0");
file(`${disk}/size`, String(3_907_029_168));
file(`${disk}/nvme0n1p2/partition`, "2");
link("sys/dev/block/259:2", `${disk}/nvme0n1p2`);
});
describe("hardware detection (sysfs fixture)", () => {
it("finds GPUs, the card's upstream link behind an on-card switch, ReBAR and names", async () => {
const hw = await detectHardware({
fs: memFs(),
modelsDir: "/models",
kernel: "6.17.1-pve",
nvidia: [{ vendor: "nvidia", index: 0, uuid: "GPU-x", name: "NVIDIA GeForce RTX 4090", memoryMb: 24564, driver: "580.82.07", pciAddress: "00000000:05:00.0" }],
});
assert.equal(hw.gpus.length, 2);
const [intel, nv] = hw.gpus;
assert.deepEqual(
{ ...intel },
{
vendor: "intel",
pciAddress: "0000:03:00.0",
name: "Intel Arc Pro B65 32GB",
vramMb: 32768,
driver: "xe",
driverVersion: "kernel 6.17.1-pve",
linkCurrent: { gen: 4, width: 8 },
linkMax: { gen: 5, width: 16 },
barMb: 32768,
rebar: true,
},
);
assert.equal(nv.name, "NVIDIA GeForce RTX 4090");
assert.equal(nv.vramMb, 24564);
assert.equal(nv.driverVersion, "580.82.07");
assert.deepEqual(nv.linkCurrent, { gen: 4, width: 16 });
assert.equal(nv.barMb, 256);
assert.equal(nv.rebar, false);
assert.equal(hw.p2p, null);
});
it("reads CPU, RAM, VM and the models disk", async () => {
const hw = await detectHardware({ fs: memFs(), modelsDir: "/models/", kernel: "6.17.1-pve" });
assert.deepEqual(hw.cpu, { model: "AMD EPYC 9124 16-Core Processor", cores: 2, threads: 4 });
assert.equal(hw.memoryBytes, 65536000 * 1024);
assert.deepEqual(hw.virtualization, { vm: true, hypervisor: "KVM/QEMU" });
assert.deepEqual(hw.storage, { model: "Samsung SSD 990 PRO 2TB", kind: "nvme", sizeBytes: 3_907_029_168 * 512 });
});
it("doesn't fail on a host without any of it", async () => {
const empty: SysFs = { read: async () => null, list: async () => [], resolve: async (p) => p };
const hw = await detectHardware({ fs: empty, modelsDir: "/models", kernel: null });
assert.deepEqual(hw.gpus, []);
assert.equal(hw.storage, null);
assert.deepEqual(hw.cpu, { model: null, cores: null, threads: null });
assert.deepEqual(hw.virtualization, { vm: null, hypervisor: null });
});
});
describe("hardware parsers", () => {
it("normalizes nvidia-smi bus IDs and reads them from the probe CSV", () => {
assert.equal(normalizePciAddress("00000000:0A:00.0"), "0000:0a:00.0");
assert.deepEqual(parseNvidiaSmi("0, GPU-abc, NVIDIA RTX A6000, 49140, 580.82.07, 00000000:01:00.0")[0].pciAddress, "0000:01:00.0");
assert.equal(parseNvidiaSmi("0, GPU-abc, NVIDIA RTX A6000, 49140, 580.82.07")[0].pciAddress, null);
});
it("takes the largest memory BAR", () => {
assert.equal(largestBarMb([bar(0x1000, 2 ** 20), bar(0x100000000, 8 * GiB), "0x0000000000001000 0x000000000000107f 0x0000000000040101"].join("\n")), 8192);
assert.equal(largestBarMb(EMPTY), null);
assert.equal(largestBarMb(null), null);
});
it("names GPUs from pci.ids, board name first", () => {
assert.equal(pciName(PCI_IDS, "0x8086", "0xe20b"), "Battlemage G21 [Arc B580]");
assert.equal(pciName(PCI_IDS, "0x8086", "0xe211", "0x8086", "0x1234"), "Arc Pro B65 32GB");
assert.equal(pciName(PCI_IDS, "0x8086", "0xffff"), null);
assert.equal(gpuDisplayName("intel", "Battlemage G21 [Arc B580]"), "Intel Arc B580");
assert.equal(gpuDisplayName("nvidia", "AD102 [GeForce RTX 4090]"), "NVIDIA GeForce RTX 4090");
});
it("reads nvidia-smi's P2P matrix", () => {
const m = (cells: string) => `\tGPU0\tGPU1\n GPU0\tX\t${cells}\n GPU1\t${cells}\tX\n\nLegend:\n X = Self\n OK = Status Ok`;
assert.equal(parseP2p(m("OK")), "on");
assert.equal(parseP2p(m("CNS")), "off");
assert.equal(parseP2p("\tGPU0\tGPU1\tGPU2\n GPU0\tX\tOK\tNS\n GPU1\tOK\tX\tNS\n GPU2\tNS\tNS\tX"), "partial");
assert.equal(parseP2p("garbage"), null);
});
it("counts cores per socket and sees the hypervisor flag", () => {
const c = parseCpu(CPUINFO);
assert.equal(c.cores, 2);
assert.equal(c.threads, 4);
assert.ok(c.hypervisor);
assert.equal(parseCpu(null).model, null);
});
it("finds the mount holding a folder", () => {
const mi = "1 0 8:1 / / rw - ext4 /dev/sda1 rw\n2 1 8:16 / /models rw - ext4 /dev/sdb rw\n3 1 8:32 / /models-old rw - ext4 /dev/sdc rw";
assert.equal(mountDevice(mi, "/models"), "8:16");
assert.equal(mountDevice(mi, "/models/unsloth"), "8:16");
assert.equal(mountDevice(mi, "/models-old"), "8:32");
assert.equal(mountDevice(mi, "/data"), "8:1");
});
it("picks the digest of the image's own repository", () => {
assert.equal(repoDigest("ghcr.io/ggml-org/llama.cpp:server", ["ghcr.io/ggml-org/llama.cpp@sha256:aaa", "mirror.local/llama.cpp@sha256:bbb"]), "sha256:aaa");
assert.equal(repoDigest("vllm/vllm-openai:v0.31.0", ["vllm/vllm-openai@sha256:ccc"]), "sha256:ccc");
assert.equal(repoDigest("local:dev", []), null);
});
});
describe("engine info", () => {
it("reads llama-server /props (build 11429)", () => {
assert.deepEqual(parseLlamaProps({ build_info: "b11429-d81235049", total_slots: 4, default_generation_settings: { n_ctx: 4096 } }), {
version: "b11429-d81235049",
slots: 4,
contextSize: 4096,
});
assert.deepEqual(parseLlamaProps(null), { version: null, slots: null, contextSize: null });
});
it("reads vLLM /version and /v1/models", () => {
assert.deepEqual(parseVllm({ version: "0.5.7" }, { data: [{ id: "x", max_model_len: 32768 }] }), { version: "0.5.7", slots: null, contextSize: 32768 });
});
it("falls back to startup log lines", () => {
assert.equal(versionFromLog("llama.cpp", ["main: build: 11429 (d8123504) with gcc"]), "b11429-d8123504");
assert.equal(versionFromLog("vllm", ["INFO 10-20 api_server.py:1 vLLM API server version 0.31.0"]), "0.31.0");
assert.equal(versionFromLog("vllm", ["nothing here"]), null);
});
it("returns nulls when the server can't be reached", async () => {
const info = await fetchEngineInfo("llama.cpp", "http://127.0.0.1:9", null);
assert.deepEqual(info, { version: null, slots: null, contextSize: null });
});
});
describe("PCIe link under load", () => {
it("reads each card's current link from sysfs", async () => {
assert.deepEqual(await currentLinks(memFs(), ["0000:03:00.0", "0000:05:00.0", "0000:09:00.0"]), {
"0000:03:00.0": { gen: 4, width: 8 },
"0000:05:00.0": { gen: 4, width: 16 },
});
});
it("keeps the fastest link seen and reads nvidia-smi's link columns", () => {
const l = (gen: number, width: number) => ({ gen, width });
assert.deepEqual(
fastestLinks([
{ pciAddress: "a", link: l(1, 16) },
{ pciAddress: "a", link: l(4, 16) },
{ pciAddress: "a", link: l(4, 8) },
{ pciAddress: "b", link: l(3, 4) },
]),
{ a: l(4, 16), b: l(3, 4) },
);
assert.deepEqual(parseGpuLine("0, NVIDIA GeForce RTX 3080, 10240, 812, 3, 21.5, 4, 16")?.link, l(4, 16));
assert.equal(parseGpuLine("0, NVIDIA GeForce RTX 3080, 10240, 812, 3, 21.5")?.link, null);
const stats = summarizeSamples([], [], 10, [{ pciAddress: "a", link: l(1, 16) }, { pciAddress: "a", link: l(4, 16) }]);
assert.deepEqual(stats.links, { a: l(4, 16) });
});
it("lists NVIDIA GPUs that aren't on the visible PCI bus (WSL2), with nvidia-smi's link", async () => {
const empty: SysFs = { read: async () => null, list: async () => [], resolve: async (p) => p };
const hw = await detectHardware({
fs: empty,
modelsDir: "/models",
kernel: null,
nvidia: [{ vendor: "nvidia", index: 0, uuid: "GPU-x", name: "NVIDIA GeForce RTX 3080", memoryMb: 10240, driver: "617.14", pciAddress: "00000000:01:00.0", linkMax: { gen: 4, width: 16 } }],
});
assert.equal(hw.gpus.length, 1);
assert.equal(hw.gpus[0].pciAddress, "0000:01:00.0");
assert.deepEqual(hw.gpus[0].linkMax, { gen: 4, width: 16 });
assert.equal(hw.gpus[0].rebar, null);
});
});
+316
View File
@@ -0,0 +1,316 @@
// Host hardware from sysfs and procfs, which a container sees unprivileged: GPUs on the PCI bus with
// their PCIe link and BAR size (for Resizable BAR), CPU, RAM, kernel, virtualization and the disk
// holding the models folder. Root-only sources (lspci's extended capabilities, DMI serials) and host
// tools (systemd-detect-virt) aren't available in the worker, so this reads the same facts from files.
// Everything reads through a SysFs, so tests run against an in-memory tree.
import { readdir, readFile, realpath } from "node:fs/promises";
import { release } from "node:os";
import { posix } from "node:path";
import type { GpuVendor, HardwareGpu, HostGpu, HostHardware, PcieLink } from "@/lib/db/schema";
import { linkGen, rebarFrom } from "@/lib/hardware";
const VENDORS: Record<string, GpuVendor> = { "0x10de": "nvidia", "0x8086": "intel", "0x1002": "amd" };
const VENDOR_LABEL: Record<GpuVendor, string> = { nvidia: "NVIDIA", intel: "Intel", amd: "AMD" };
const PCI_ADDR = /^[0-9a-f]{4,}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$/i;
const PCI_IDS = ["/usr/share/misc/pci.ids", "/usr/share/hwdata/pci.ids"];
/** Where drivers report total VRAM, if they do (amdgpu; xe/i915 vary by kernel). */
const VRAM_FILES = ["mem_info_vram_total", "tile0/physical_vram_size_bytes", "lmem_total_bytes"];
const IORESOURCE_MEM = BigInt(0x200);
const ZERO = BigInt(0);
const MIB = BigInt(2 ** 20);
const { basename, dirname, join } = posix;
/** The few file operations detection needs (absolute POSIX paths). */
export type SysFs = {
/** Trimmed file content, or null when it can't be read. */
read(path: string): Promise<string | null>;
list(dir: string): Promise<string[]>;
/** Symlinks resolved (sysfs device links); the path itself when it isn't one. */
resolve(path: string): Promise<string>;
};
export const nodeFs: SysFs = {
read: (p) => readFile(p, "utf8").then((t) => t.trim(), () => null),
list: (d) => readdir(d).catch(() => []),
resolve: (p) => realpath(p).catch(() => p),
};
const num = (s: string | null) => (s != null && /^\d+$/.test(s) ? Number(s) : null);
/** nvidia-smi's "00000000:01:00.0" → sysfs "0000:01:00.0". */
export function normalizePciAddress(id: string): string {
const [domain, ...rest] = id.trim().toLowerCase().split(":");
return [domain.slice(-4).padStart(4, "0"), ...rest].join(":");
}
/** Largest memory BAR in MiB, from a device's `resource` file ("start end flags" per line). */
export function largestBarMb(resource: string | null): number | null {
if (!resource) return null;
let max = ZERO;
for (const line of resource.split("\n")) {
const [start, end, flags] = line.trim().split(/\s+/).map((x) => {
try {
return BigInt(x);
} catch {
return ZERO;
}
});
if (!end || !(flags & IORESOURCE_MEM)) continue;
const size = end - start + BigInt(1);
if (size > max) max = size;
}
return max > ZERO ? Number(max / MIB) : null;
}
/**
* The card's own upstream link: cards like Intel's Arc B-series sit behind an on-card PCIe switch,
* whose internal link is what the GPU function reports. Walk up while the parent belongs to the same
* vendor and isn't the root port.
*/
async function cardUpstream(fs: SysFs, dev: string, vendor: string): Promise<string> {
let cur = dev;
for (;;) {
const parent = dirname(cur);
if (!PCI_ADDR.test(basename(parent)) || !PCI_ADDR.test(basename(dirname(parent)))) return cur;
if ((await fs.read(join(parent, "vendor"))) !== vendor) return cur;
cur = parent;
}
}
async function link(fs: SysFs, dir: string, kind: "current" | "max") {
const gen = linkGen(await fs.read(join(dir, `${kind}_link_speed`)));
const width = num(await fs.read(join(dir, `${kind}_link_width`)));
return gen == null && width == null ? null : { gen, width };
}
const pciIds = new WeakMap<SysFs, Promise<string | null>>();
async function pciIdsText(fs: SysFs): Promise<string | null> {
if (!pciIds.has(fs)) {
pciIds.set(
fs,
(async () => {
for (const p of PCI_IDS) {
const text = await fs.read(p);
if (text) return text;
}
return null;
})(),
);
}
return pciIds.get(fs)!;
}
/** Name from pci.ids: the subsystem's (board) name if listed, else the chip's; "[Arc B580]" preferred. */
export function pciName(ids: string, vendor: string, device: string, subVendor?: string | null, subDevice?: string | null): string | null {
const v = vendor.replace(/^0x/, "").toLowerCase();
const d = device.replace(/^0x/, "").toLowerCase();
const sub = subVendor && subDevice ? `${subVendor.replace(/^0x/, "")} ${subDevice.replace(/^0x/, "")}`.toLowerCase() : null;
const lines = ids.split("\n");
let i = lines.findIndex((l) => l.startsWith(`${v} `));
if (i < 0) return null;
let chip: string | null = null;
for (i++; i < lines.length && (lines[i].startsWith("\t") || lines[i].startsWith("#") || !lines[i].trim()); i++) {
const l = lines[i];
if (!l.startsWith("\t\t") && l.startsWith("\t")) {
if (chip) break;
if (l.slice(1, 5).toLowerCase() === d) chip = l.slice(7).trim();
} else if (chip && sub && l.startsWith("\t\t") && l.slice(2, 11).toLowerCase() === sub) {
return l.slice(13).trim();
}
}
return chip;
}
/** "AD102 [GeForce RTX 4090]" → "NVIDIA GeForce RTX 4090". */
export function gpuDisplayName(vendor: GpuVendor, pciIdsName: string | null): string | null {
if (!pciIdsName) return null;
const bracket = pciIdsName.match(/\[([^\]]+)\]/)?.[1];
const name = bracket ?? pciIdsName;
const label = VENDOR_LABEL[vendor];
return name.toLowerCase().startsWith(label.toLowerCase()) ? name : `${label} ${name}`;
}
function uevent(text: string | null): Record<string, string> {
return Object.fromEntries((text ?? "").split("\n").map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]));
}
/** Display controllers (class 0x03…) from NVIDIA, Intel and AMD. NVIDIA names/VRAM come from nvidia-smi. */
export async function detectGpus(fs: SysFs, nvidia: HostGpu[], kernel: string | null): Promise<HardwareGpu[]> {
const base = "/sys/bus/pci/devices";
const addrs = (await fs.list(base)).filter((a) => PCI_ADDR.test(a)).sort();
const out: HardwareGpu[] = [];
for (const addr of addrs) {
const dev = await fs.resolve(join(base, addr));
const [cls, vendorId] = await Promise.all([fs.read(join(dev, "class")), fs.read(join(dev, "vendor"))]);
const vendor = vendorId ? VENDORS[vendorId.toLowerCase()] : undefined;
if (!cls?.startsWith("0x03") || !vendor) continue;
const ev = uevent(await fs.read(join(dev, "uevent")));
const driver = ev.DRIVER || null;
const up = await cardUpstream(fs, dev, vendorId!.toLowerCase());
const nv = nvidia.find((g) => g.pciAddress && normalizePciAddress(g.pciAddress) === addr.toLowerCase());
let vramMb: number | null = nv?.memoryMb ?? null;
for (const f of VRAM_FILES) {
if (vramMb) break;
const bytes = num(await fs.read(join(dev, f)));
if (bytes) vramMb = Math.round(bytes / 2 ** 20);
}
const ids = await pciIdsText(fs);
const [device, subVendor, subDevice] = await Promise.all(["device", "subsystem_vendor", "subsystem_device"].map((f) => fs.read(join(dev, f))));
const barMb = largestBarMb(await fs.read(join(dev, "resource")));
const moduleVersion = driver ? await fs.read(join("/sys/module", driver, "version")) : null;
out.push({
vendor,
pciAddress: addr.toLowerCase(),
name: nv?.name ?? (ids && device ? gpuDisplayName(vendor, pciName(ids, vendorId!, device, subVendor, subDevice)) : null),
vramMb,
driver,
driverVersion: nv?.driver ?? moduleVersion ?? (driver && kernel ? `kernel ${kernel}` : null),
linkCurrent: (await link(fs, up, "current")) ?? nv?.linkCurrent ?? null,
linkMax: (await link(fs, up, "max")) ?? nv?.linkMax ?? null,
barMb,
rebar: rebarFrom(barMb, vramMb),
});
}
// NVIDIA GPUs that aren't on the visible PCI bus (WSL2 passes them through its own driver).
for (const g of nvidia) {
const addr = g.pciAddress ? normalizePciAddress(g.pciAddress) : `nvidia-${g.index}`;
if (out.some((o) => o.pciAddress === addr)) continue;
out.push({
vendor: "nvidia",
pciAddress: addr,
name: g.name,
vramMb: g.memoryMb || null,
driver: "nvidia",
driverVersion: g.driver || null,
linkCurrent: g.linkCurrent ?? null,
linkMax: g.linkMax ?? null,
barMb: null,
rebar: null,
});
}
return out;
}
/** The current link of each GPU's card (upstream port), for sampling during a run; skips unknown ones. */
export async function currentLinks(fs: SysFs, pciAddresses: string[]): Promise<Record<string, PcieLink>> {
const out: Record<string, PcieLink> = {};
for (const addr of pciAddresses) {
const dev = await fs.resolve(join("/sys/bus/pci/devices", addr));
const vendor = await fs.read(join(dev, "vendor"));
if (!vendor) continue;
const l = await link(fs, await cardUpstream(fs, dev, vendor.toLowerCase()), "current");
if (l) out[addr] = l;
}
return out;
}
/** `nvidia-smi topo -p2p r`: "OK" between every pair → on, none → off. */
export function parseP2p(text: string): "on" | "off" | "partial" | null {
const cells = text
.split("\n")
.filter((l) => /^\s*GPU\d+\s/.test(l))
.flatMap((l) => l.trim().split(/\s+/).slice(1))
.filter((c) => c !== "X" && !/^GPU\d+$/.test(c));
if (cells.length === 0) return null;
const ok = cells.filter((c) => c === "OK").length;
return ok === cells.length ? "on" : ok === 0 ? "off" : "partial";
}
export function parseCpu(cpuinfo: string | null): HostHardware["cpu"] & { hypervisor: boolean } {
if (!cpuinfo) return { model: null, cores: null, threads: null, hypervisor: false };
const blocks = cpuinfo.split(/\n\s*\n/).filter((b) => /^processor\s*:/m.test(b));
const field = (b: string, k: string) => b.match(new RegExp(`^${k}\\s*:\\s*(.*)$`, "m"))?.[1]?.trim() ?? null;
const cores = new Set(blocks.map((b) => `${field(b, "physical id") ?? 0}:${field(b, "core id") ?? field(b, "processor")}`));
return {
model: blocks[0] ? field(blocks[0], "model name") : null,
cores: blocks.length ? cores.size : null,
threads: blocks.length || null,
hypervisor: blocks[0] ? /\bhypervisor\b/.test(field(blocks[0], "flags") ?? "") : false,
};
}
const HYPERVISORS: [RegExp, string][] = [
[/^QEMU|KVM/i, "KVM/QEMU"],
[/Microsoft/i, "Hyper-V"],
[/VMware/i, "VMware"],
[/Xen/i, "Xen"],
[/innotek|VirtualBox/i, "VirtualBox"],
[/Amazon/i, "AWS"],
[/Google/i, "Google Cloud"],
];
/** VM or bare metal, from the CPU's hypervisor flag and the DMI vendor (both readable unprivileged). */
export async function detectVirtualization(fs: SysFs, hypervisorFlag: boolean, kernel: string | null): Promise<HostHardware["virtualization"]> {
const dmi = [await fs.read("/sys/class/dmi/id/sys_vendor"), await fs.read("/sys/class/dmi/id/product_name")].filter(Boolean).join(" ");
if (kernel && /microsoft.*wsl/i.test(kernel)) return { vm: true, hypervisor: "WSL2 (Hyper-V)" };
const known = HYPERVISORS.find(([re]) => re.test(dmi))?.[1] ?? null;
if (hypervisorFlag || known) return { vm: true, hypervisor: known };
return { vm: dmi ? false : null, hypervisor: null };
}
/** The mount holding `dir` (longest mount point that is a prefix), as "major:minor". */
export function mountDevice(mountinfo: string, dir: string): string | null {
const target = posix.normalize(dir.replace(/\\/g, "/")).replace(/(.)\/$/, "$1");
let best: { point: string; dev: string } | null = null;
for (const line of mountinfo.split("\n")) {
const f = line.split(" ");
if (f.length < 5) continue;
const point = f[4].replace(/\\040/g, " ");
const inside = target === point || target.startsWith(point.endsWith("/") ? point : `${point}/`);
if (inside && (!best || point.length > best.point.length)) best = { point, dev: f[2] };
}
return best?.dev ?? null;
}
/** The disk behind a block device: partitions → their disk, device-mapper (LVM, LUKS) → first slave. */
async function diskOf(fs: SysFs, devDir: string, depth = 0): Promise<string | null> {
if (depth > 4) return null;
if (await fs.read(join(devDir, "partition"))) return dirname(devDir);
if (basename(devDir).startsWith("dm-") || basename(devDir).startsWith("md")) {
const slaves = await fs.list(join(devDir, "slaves"));
if (!slaves[0]) return devDir;
return diskOf(fs, await fs.resolve(join("/sys/class/block", slaves[0])), depth + 1);
}
return devDir;
}
export async function detectStorage(fs: SysFs, modelsDir: string): Promise<HostHardware["storage"]> {
const mountinfo = await fs.read("/proc/self/mountinfo");
const dev = mountinfo ? mountDevice(mountinfo, modelsDir) : null;
if (!dev || dev.startsWith("0:")) return null; // ZFS, overlay, network filesystems: no block device
const blockDir = join("/sys/dev/block", dev);
if ((await fs.list(blockDir)).length === 0) return null;
const disk = await diskOf(fs, await fs.resolve(blockDir));
if (!disk) return null;
const name = basename(disk);
const model = (await fs.read(join(disk, "device/model")))?.replace(/\s+/g, " ") || null;
const vendor = (await fs.read(join(disk, "device/vendor")))?.trim() ?? "";
const rotational = await fs.read(join(disk, "queue/rotational"));
const sectors = num(await fs.read(join(disk, "size")));
const virtual = /^vd|^xvd/.test(name) || vendor === "0x1af4" || /QEMU|Virtual Disk|VBOX|VMware/i.test(`${vendor} ${model ?? ""}`);
return {
model: model ?? (virtual ? "virtio disk" : null),
kind: virtual ? "virtual" : name.startsWith("nvme") ? "nvme" : rotational === "1" ? "hdd" : rotational === "0" ? "ssd" : null,
sizeBytes: sectors != null ? sectors * 512 : null,
};
}
export async function detectHardware(o: { fs?: SysFs; modelsDir: string; nvidia?: HostGpu[]; p2p?: HostHardware["p2p"]; kernel?: string | null }): Promise<HostHardware> {
const fs = o.fs ?? nodeFs;
const kernel = o.kernel !== undefined ? o.kernel : release();
const cpu = parseCpu(await fs.read("/proc/cpuinfo"));
const memKb = Number((await fs.read("/proc/meminfo"))?.match(/^MemTotal:\s+(\d+)\s*kB/m)?.[1]);
const gpus = await detectGpus(fs, o.nvidia ?? [], kernel);
return {
gpus,
p2p: gpus.length >= 2 ? (o.p2p ?? null) : null,
cpu: { model: cpu.model, cores: cpu.cores, threads: cpu.threads },
memoryBytes: Number.isFinite(memKb) && memKb > 0 ? memKb * 1024 : null,
kernel,
virtualization: await detectVirtualization(fs, cpu.hypervisor, kernel),
storage: await detectStorage(fs, o.modelsDir).catch(() => null),
checkedAt: new Date().toISOString(),
};
}
+14 -1
View File
@@ -10,7 +10,9 @@ import { promisify } from "node:util";
import { asc, eq, inArray } from "drizzle-orm";
import { benchmarksDir, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
import { db } from "@/lib/db/client";
import { benchmarkPublications, settings } from "@/lib/db/schema";
import { benchmarkPublications, benchmarkRuns, settings } from "@/lib/db/schema";
import { metaRows } from "@/lib/benchmark-meta";
import { systemSummaryLines } from "@/lib/hardware";
import { coreEnv } from "@/lib/env";
import { log } from "./log";
@@ -60,6 +62,16 @@ export async function reportL80Status(): Promise<void> {
log.info(version ? `L80 CLI ${version}, publish token ${value.tokenSet ? "set" : "not set"}` : "L80 CLI not found; publishing to launch80 is unavailable");
}
/** The run's description, hardware/runtime facts and system summary, as page sections (only whitelisted host facts). */
export async function runSections(runId: string): Promise<[string, string][]> {
const run = await db().query.benchmarkRuns.findFirst({ columns: { description: true, system: true, meta: true }, where: eq(benchmarkRuns.id, runId) });
const out: [string, string][] = [];
if (run?.description?.trim()) out.push(["Description", run.description.trim()]);
if (run?.meta) out.push(["Hardware and runtime", metaRows(run.meta).map((r) => `${r.label}: ${r.value}`).join("\n")]);
if (run?.system) out.push(["System", systemSummaryLines(run.system).join("\n")]);
return out;
}
async function exists(p: string) {
return access(p).then(
() => true,
@@ -88,6 +100,7 @@ export async function tickPublications(): Promise<void> {
const args = ["betterbench", "--results", results, "--dry-run", "--payload-out", payload, "--json"];
if (p.title) args.push("--title", p.title);
if (p.summary) args.push("--summary", p.summary);
for (const [heading, body] of await runSections(p.runId)) args.push("--section", `${heading}=${body}`);
try {
const { stdout } = await run(env.L80_BIN, args, { env: cliEnv(false), timeout: 60_000, maxBuffer: 8 * 2 ** 20 });
const out = JSON.parse(stdout) as { byte_size?: number; template?: string };
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff. Show more