Compare commits

..
4 Commits
Author SHA1 Message Date
Pascal LinxweilerandClaude Opus 5.5 4f05ee165c Release 0.14.2: steady download progress
Release / release (push) Successful in 6m29s
A progress sample that missed a partial file showed 0 B while hf kept
downloading. Walk the download cache tolerating vanished folders and
never let a file's progress go backwards within a run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:03:33 +02:00
Pascal LinxweilerandClaude Opus 5.5 22a54f731d Release 0.14.1: use Xet for files over 50 GB
Release / release (push) Successful in 3m27s
huggingface_hub 2.1.1 refuses files over MAX_HTTP_DOWNLOAD_SIZE (50 GB)
without Xet; Kaname disables Xet by default for steady progress, so such
downloads failed. A download that includes a file over the limit now
runs hf with Xet enabled and says so in the job log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:39:41 +02:00
Pascal LinxweilerandClaude Opus 5.5 6b67c653b5 Release 0.14.0: quality eval
Release / release (push) Successful in 3m17s
A deterministic quality eval as a run type next to BetterBench: tool
calling (12 requests), coding (8 Python functions checked by unit tests
in a locked-down sandbox container) and long-context retrieval (needle at
3 depths in 3 lengths up to the context). Versioned eval set in
src/evals/v1, score stored per run, shown on the run page, in compare
views, the benchmark list and sweep tables (optional eval per variant);
API kind "eval", quality in run/sweep/compare answers; skill updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:24:36 +02:00
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
81 changed files with 10013 additions and 286 deletions

No files matched your search

+98
View File
@@ -4,6 +4,104 @@ 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.
## [0.14.2] - 2026-10-22
### Fixed
- A running download's progress could jump back and forth between the real value and 0 B while
`hf` kept downloading. A single progress reading that missed the partial file (a folder changing
while the worker listed it, or a stale size on a network share) counted as nothing downloaded.
Folders that vanish mid-listing are now skipped instead of failing the whole listing, and a file's
progress no longer goes backwards during a run.
## [0.14.1] - 2026-10-22
### Fixed
- Downloads with a file over 50 GB failed with "The file is too large to be downloaded using the
regular download method". `hf` (huggingface_hub 2.1.1) only downloads such files over Xet, which
Kaname turns off by default for steady progress; a download that includes one now uses Xet (noted
in the job log; its progress grows in bursts).
## [0.14.0] - 2026-10-21
A quality eval next to the speed benchmarks: a short, deterministic check of tool calling, coding and
long-context retrieval, so a launch option that makes a model faster but worse shows up.
No changes to `compose.yaml` or `.env`. The new column is added on start.
### Added
- **Quality eval** as a run type (deployment page → Benchmark → Quality), run against a deployment
with greedy decoding, a fixed seed and thinking turned off:
- **tool calling**: 12 requests; one tool call with valid JSON, the right function and arguments;
- **coding**: 8 short Python functions, checked by unit tests in a throwaway container from Kaname's
own image (no network, read-only, unprivileged user, no capabilities, CPU/memory/process limits);
- **long-context retrieval**: a code hidden at 10/50/90 % depth in texts of 25/50/100 % of the
context, sized with the server's own tokenizer.
The score (0–100) is the mean pass rate of the sections that could run; a server that refuses tool
calls doesn't count as 0. The eval set is versioned data in the repo (`src/evals/v1`), and every
result records its version (`kaname-eval-1`).
- The run page shows the score, each section and every item with the reason it failed. Compare views
get a "Quality" group; the benchmark list shows the score; sweeps can run the eval on every variant
("Also run the quality eval") and show it as a column.
- API: `POST /api/v1/benchmarks` with `kind: "eval"` (optional `sections`), `quality` in run, sweep
and compare answers, `"quality": true` for sweeps; the same guardrails as other runs.
- The tuning skill checks quality after speed and reports both.
## [0.13.0] - 2026-10-21
The agent API can now deploy and benchmark models, so an AI agent can tune launch options for the
hardware: within guardrails you set, only on deployments its own token created, and by default only
after you approve each start, run and sweep.
No changes to `compose.yaml` or `.env`. The new columns and table are added on start. Existing
tokens keep their scopes; grant the new ones with **Scopes** in Settings → API tokens.
### Added
- **Token scopes** `deployments:read`, `deployments:write`, `benchmarks:read`, `benchmarks:run`, and
editing an existing token's scopes.
- **`/api/v1` for deployments** ([docs/api.md](docs/api.md)):
- `GET /api/v1/runtimes`: pulled runtimes, what they serve, whether agents may use them and which
extra arguments; the host's GPUs.
- `GET /api/v1/deployments`, `GET /api/v1/deployments/{id}`: state, endpoint, options, the engine
version and slots, live CPU/RAM; the log with `?log=N`.
- `POST /api/v1/deployments` with the same validation, memory/VRAM estimate and `docker run`
command as the form (returned in the answer); `dryRun: true` only checks. Unknown fields are
refused instead of ignored.
- `PATCH`, `POST …/start`, `POST …/stop`, `DELETE` for the token's own deployments.
- **`/api/v1` for benchmarks**: `POST /api/v1/benchmarks` (run or A/B, quick or full, phases,
description), `GET /api/v1/benchmarks/{id}` with a compact result (headline numbers, the run's
hardware/runtime/model setup, GPU and RAM use; the full summary with `?full=1`), cancel, a list,
`GET /api/v1/benchmarks/compare?ids=` (what differs, what's the same), and sweeps
(`POST /api/v1/sweeps`, `GET /api/v1/sweeps/{id}`, cancel).
- **`?wait=<seconds>`** (max 900) on the job, deployment, run and sweep status endpoints: the request
returns once the state settles, so agents make one call instead of polling. Things that wait for
approval answer right away.
- **Guardrails for API deployments and benchmarks** (Settings → API tokens): approval (default: ask
me), agent deployments at once (1), one agent run or sweep at a time and no agent start while one
runs, time limits per run and sweep (30 min / 3 h, enforced by the worker), max sweep variants (8),
a runtime allowlist, an allowlist of extra argument flags per engine (values can't be paths or
URLs; the error names the argument), host ports only within a range (none by default), and caps
for memory and CPUs (agent deployments always get a memory limit).
- **Protected deployments**: the Protect button on a deployment's page. Agents can't edit, stop,
delete or benchmark it, nor start anything on the same GPUs that would crowd it out of VRAM
(estimated).
- **Approval** for agent starts, runs and sweeps on the deployment, run and sweep pages; "awaiting
approval" in the lists.
- Everything an agent creates shows **requested by &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
+7 -4
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
@@ -104,7 +106,8 @@ Notes on the `hf` CLI (huggingface_hub 2.1.1, pinned in the image):
- Interrupted files are **not resumed**: a re-run skips finished files and restarts unfinished ones.
Kaname cleans up the leftover partial files.
- With Xet transfers the partial file only grows in large bursts, so Kaname disables Xet by default
to show accurate progress.
to show accurate progress. Files over 50 GB can only be downloaded with Xet, so a download that
includes one uses Xet anyway.
- `hf` exits successfully even if nothing matched, so Kaname checks every file's size and hash
metadata after each download.
- Files that already exist in the target folder without hf's metadata (copied in by hand) are
+192
View File
@@ -0,0 +1,192 @@
---
name: kaname-tuning
description: Deploy local LLMs on the user's Kaname server, benchmark their speed and check their answer quality to find good launch options (context, KV cache type, batch sizes, GPU layers, runtime) for the hardware. Use when the user asks to deploy, test, benchmark, tune or compare a model's settings, or to find the fastest setup for a model.
required_environment_variables:
- name: KANAME_URL
prompt: Kaname base URL (no trailing slash)
- name: KANAME_TOKEN
prompt: Kaname API token (kn_…) with the deployments and benchmarks scopes
---
# Kaname: deploy and tune models
Kaname runs models in containers (llama.cpp or vLLM) and measures them with BetterBench. With this
skill you deploy a downloaded model, benchmark it, change **one** launch option at a time and report
which setup is best. To find or download models, use the `kaname-models` skill (`SKILL.md`).
You may only change and benchmark deployments your own token created. You **cannot** touch the
user's deployments (especially protected ones), change settings, runtimes or tokens, or delete
models. Tell the user when something needs one of those.
Every call needs `KANAME_URL` and `KANAME_TOKEN` (never print the token or put it in a URL), and the
`kaname` helper (a `curl` wrapper that adds the token and JSON headers; see `SKILL.md` → Setup). If
`kaname` is missing, write out
`curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" …` instead.
Errors are `{"error": {"code", "message"}}`; the message says what to do.
## Rules
- **No polling loops.** Status calls take `?wait=S` (max 900): Kaname holds the request until the
state settles. Make one call, with `-m` (curl's time limit) a bit above the wait.
- **Approval:** by default every start, run and sweep waits for the user (`state:
pending_approval`). Then **stop**: tell the user what you asked for and that it awaits their
approval in Kaname. Don't retry, don't poll. Continue when the user says it's approved.
- **Never work around a guardrail** (another token, splitting a sweep, renaming things). Report the
error message and stop.
- **One GPU job at a time:** one of your deployments running at once (unless the user raised the
limit), one run or sweep at a time. Stop your deployment when you're done.
- **Change one variable at a time**, so a difference has one cause.
## 1. Know your limits
```bash
kaname "$KANAME_URL/api/v1"
```
`deploymentGuardrails`: approval mode, how many of your deployments may run, run/sweep time limits,
max sweep variants, caps, host ports. Your scopes must include `deployments:write` and
`benchmarks:run`; if not, tell the user.
## 2. Pick a model and a runtime
```bash
kaname "$KANAME_URL/api/v1/models?status=ready&q=qwen3"
kaname "$KANAME_URL/api/v1/models/<modelId>" # its files (pick a .gguf for llama.cpp)
kaname "$KANAME_URL/api/v1/runtimes"
```
Runtimes say what they serve (llama.cpp: a GGUF file, vLLM: a safetensors repo), whether you may use
them (`"allowed": true`) and which extra argument flags you may pass (`allowedExtraArgs`). `gpus`
lists the host's GPUs and their VRAM.
Previous results for this model, to start from what is known:
```bash
kaname "$KANAME_URL/api/v1/benchmarks?limit=10"
```
## 3. Deploy
Check first (nothing is created; you get the exact command and the memory/VRAM estimates):
```bash
kaname -X POST "$KANAME_URL/api/v1/deployments" -d '{
"runtimeId": "<runtimeId>", "modelId": "<modelId>", "dryRun": true,
"options": { "modelFile": "Qwen3-8B-Q4_K_M.gguf", "contextSize": 16384, "gpuLayers": "auto",
"cacheTypeK": "q8_0", "cacheTypeV": "q8_0", "parallel": 1, "extraArgs": [] }
}'
```
If `estimates.vramMb` is above `estimates.gpuVramMb`, lower the context, quantize the KV cache or
pick a smaller quant. Then the same body without `"dryRun"`:
- `state: pending_approval` → tell the user and stop (see Rules).
- `state: starting` → wait until it is ready:
```bash
kaname -m 660 "$KANAME_URL/api/v1/deployments/<id>?wait=600"
```
`state: running` → go on. `state: failed` → read `error` (and `?log=50`), fix the options
(`PATCH`, below) and start again; don't repeat the same failing options.
## 4. Benchmark
```bash
kaname -X POST "$KANAME_URL/api/v1/benchmarks" -d '{
"deploymentId": "<id>", "quick": true, "label": "Q4_K_M ctx16k q8_0 KV",
"description": "Baseline for tuning Qwen3-8B on this GPU"
}'
kaname -m 960 "$KANAME_URL/api/v1/benchmarks/<runId>?wait=900"
```
- `quick: true` (5 passes) to screen options; `quick: false` (20 passes) to confirm the winner.
- `phases` (`decode`, `prefill`, `concurrency`) narrows what is measured; leave it out for all.
- The result's `headline` has `decodeTps` (generation speed), `prefillTps` (prompt processing at the
deepest prompt), `ttftMs` (time to first token) and `peakParallelTps`; `setup` lists GPU, PCIe,
engine version, model/quant/KV cache, context and concurrency; `resources` has VRAM, power and
temperature. `?full=1` only when you need the per-category details.
- If the wait times out, the run is still going: one more call with `?wait=900`, then report.
Then check that the answers are still right (speed alone can hide a broken setup):
```bash
kaname -X POST "$KANAME_URL/api/v1/benchmarks" -d '{"kind": "eval", "deploymentId": "<id>", "label": "Q4_K_M ctx16k q8_0 KV"}'
kaname -m 960 "$KANAME_URL/api/v1/benchmarks/<runId>?wait=900"
```
`quality.score` (0–100) and per section (`tools`, `coding`, `retrieval`). Add `?full=1` to see which
items failed. A drop of more than a few points against the baseline means the change hurt quality,
however fast it is.
## 5. Change one variable and compare
Stop, change one option, start, wait, benchmark again:
```bash
kaname -X POST "$KANAME_URL/api/v1/deployments/<id>/stop"
kaname -m 120 "$KANAME_URL/api/v1/deployments/<id>?wait=60"
kaname -X PATCH "$KANAME_URL/api/v1/deployments/<id>" -d '{"options": {"cacheTypeK": "f16", "cacheTypeV": "f16"}}'
kaname -X POST "$KANAME_URL/api/v1/deployments/<id>/start"
```
Or let Kaname do it: a **sweep** deploys each variant of one or two settings, benchmarks it (with
`"quality": true` also runs the quality eval) and removes it again (stop your own deployment first;
it counts as one run):
```bash
kaname -X POST "$KANAME_URL/api/v1/sweeps" -d '{
"baseDeploymentId": "<id>", "quick": true, "quality": true,
"params": [{ "key": "kvCache", "values": ["f16", "q8_0", "q4_0"] }]
}'
kaname -m 960 "$KANAME_URL/api/v1/sweeps/<sweepId>?wait=900"
```
Keys: `contextSize`, `modelFile`, `kvCache`, `threads`, `parallel`, `batchSize`, `ubatchSize`,
`flashAttn`, `cacheRamMb`, `gpuLayers` (llama.cpp); `dtype`, `maxNumSeqs`, `gpuMemoryUtilization`
(vLLM); `cpus`. A sweep can take long: after a timed-out wait, report progress instead of waiting
again and again.
Compare runs side by side:
```bash
kaname "$KANAME_URL/api/v1/benchmarks/compare?ids=<run1>,<run2>,<run3>"
```
Differences under ~2 % between separate runs are noise. For a small difference that matters, run
an A/B (two deployments of the same model at once, if the user allows 2 agent deployments):
`{"kind": "ab", "deploymentId": "<A>", "deploymentBId": "<B>"}`.
## 6. Report and clean up
Report a compact table, one row per setup, the varied option first:
| KV cache | Decode t/s | Prefill t/s | TTFT ms | Quality | VRAM peak | Notes |
| --- | --- | --- | --- | --- | --- | --- |
| f16 | 58.1 | 1910 | 88 | 86.1 | 11.2 GB | baseline |
| q8_0 | 57.6 | 1880 | 90 | 86.1 | 9.4 GB | −1 % speed, same quality, 1.8 GB less VRAM |
Name the winner and why: speed and quality together (and what stayed the same: GPU, engine version,
quant, context). Then stop
your deployment (or delete it if the user doesn't need it):
```bash
kaname -X POST "$KANAME_URL/api/v1/deployments/<id>/stop"
```
## When something is refused
| `error.code` | What to do |
| --- | --- |
| `too_many_deployments` | Stop your other deployment first, or tell the user. |
| `gpu_busy` | Another agent job is running or a deployment is loading: wait once with `?wait=`, then retry once; otherwise report and stop. |
| `vram_protected` | It would crowd the user's protected deployment out of VRAM: smaller quant, context or quantized KV cache, or tell the user. |
| `arg_not_allowed` | That flag isn't allowed; use the structured option if there is one (`contextSize`, `gpuLayers`, `cacheTypeK`, …) or drop it. |
| `limit_exceeded` | Over the memory/CPU cap: smaller model or context. |
| `port_not_allowed` | Leave out `hostPort`. |
| `runtime_not_allowed`, `runtime_not_pulled` | Pick another runtime from `GET /api/v1/runtimes`, or tell the user. |
| `protected`, `not_owner` | Not your deployment: deploy your own. |
| `too_many_variants` | Vary fewer values. |
| `busy` | Stop the deployment before changing it. |
| `unauthorized`, `forbidden` | Token wrong, revoked or missing a scope: tell the user. |
+11 -6
View File
@@ -12,7 +12,9 @@ required_environment_variables:
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:
@@ -94,17 +96,20 @@ Answer:
## 4. Follow it
```bash
kaname "$KANAME_URL/api/v1/jobs/<jobId>"
kaname -m 660 "$KANAME_URL/api/v1/jobs/<jobId>?wait=600"
```
`state`: `pending_approval` → `queued` → `downloading` → `verifying` → `completed`. Every check
costs a full round of your context, so check rarely:
`state`: `pending_approval` → `queued` → `downloading` → `verifying` → `completed`. With `?wait=600`
Kaname holds the request until the job is finished (or 600 s have passed; then `timedOut` is
`true`), so one call replaces a polling loop. Keep `-m` (curl's time limit) a bit above the wait.
Every call costs a full round of your context, so call rarely:
- **`pending_approval`:** do **not** poll. Tell the user what you requested and that it awaits
their approval in Kaname, then stop. Check again only when the user says it's approved, or, if
the user asks for it, schedule a single one-off check later with your cron/scheduling tool.
- **`queued` / `downloading` / `verifying`:** check at most once, around the reported
`etaSeconds`; if there is no ETA, once after about 10 minutes. Never loop in short intervals.
- **`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.
+183 -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,138 @@ 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, BetterBench speed), `ab` (paired A/B with `deploymentBId`, same model; needs 2 agent deployments) or `eval` (the [quality eval](#quality-eval)) |
| `deploymentId`, `deploymentBId` | Own, running deployments |
| `quick` | `true`: 5 passes, a smoke check; default `false`: 20 passes, comparable |
| `passes`, `phases` | Optional: passes per category; phases `decode`, `prefill`, `concurrency` (default all) |
| `label`, `description` | Optional; the description goes into the report and the launch80 preview |
| `sections` | `eval` only: `tools`, `coding`, `retrieval` (default all) |
Answers `201` with `state` `pending_approval` (default) or `queued`, and the run's time limit.
#### `GET /api/v1/benchmarks/{id}[?wait=S][&full=1]`, `GET /api/v1/benchmarks[?deployment=&requested_by=&limit=]`
`benchmarks:read`. Compact result:
```json
{ "id": "01M…", "kind": "run", "state": "completed", "label": "q8_0 KV", "mine": true,
"headline": { "decodeTps": 61.3, "prefillTps": 1840, "prefillDepth": 16000, "ttftMs": 92, "peakParallelTps": 155.2, "peakParallelLevel": 8 },
"setup": { "gpus": "1× Intel Arc Pro B65 (32 GiB)", "pcie": "Gen5 x8 of Gen5 x16", "p2p": "n/a", "rebar": "on",
"engine": "llama.cpp b11541-f2918cabb", "image": "ghcr.io/ggml-org/llama.cpp:server-intel", "digest": "sha256:…",
"model": "Qwen3-8B-GGUF Q4_K_M with q8_0 KV cache", "ctx": "16,384", "concurrency": "4" },
"resources": { "cpuAvgCores": 1.1, "ramPeakBytes": 2100000000,
"gpus": [{ "name": "Intel Arc Pro B65", "vramPeakMb": 9100, "vramTotalMb": 32768, "utilAvg": 88.5, "powerAvgW": 151.2, "tempPeakC": 71 }] },
"error": null, "next": "Done. Compare runs with GET /api/v1/benchmarks/compare?ids=…" }
```
`?full=1` adds BetterBench's complete summary (per category, per prompt depth, per concurrency
level). A/B runs add `ab` (pairs, verdict, decode difference with its confidence interval). Eval runs
have `quality` instead of `headline`:
`{"evalSet": "kaname-eval-1", "score": 83.3, "sections": {"tools": "11/12", "coding": "6/8", "retrieval": "8/9"}}`,
and with `?full=1` the `failed` items with the reason.
`POST /api/v1/benchmarks/{id}/cancel` cancels an own run.
#### `GET /api/v1/benchmarks/compare?ids=a,b,…`
`benchmarks:read`. 2–16 runs: headline numbers side by side, the setup values that differ per run
(`differs`) and the ones they share (`same`).
#### `POST /api/v1/sweeps`, `GET /api/v1/sweeps/{id}[?wait=S]`, `POST /api/v1/sweeps/{id}/cancel`
`benchmarks:run` / `benchmarks:read`. One or two settings varied from an own base deployment, e.g.
`{"baseDeploymentId": "…", "params": [{"key": "kvCache", "values": ["f16", "q8_0"]}], "quick": true}`;
`"quality": true` also runs the quality eval on each variant.
Keys: `contextSize`, `modelFile`, `kvCache`, `threads`, `parallel`, `batchSize`, `ubatchSize`,
`flashAttn`, `cacheRamMb`, `gpuLayers`, `dtype`, `maxNumSeqs`, `kvCacheGb`, `gpuMemoryUtilization`,
`cpus` (per engine, as in the UI). Each variant is deployed, benchmarked and removed again. The
answer lists every variant with its headline numbers and setup.
#### Quality eval
BetterBench measures speed only. `kind: "eval"` checks what a deployment answers, deterministically
(greedy decoding, temperature 0, fixed seed, thinking turned off where the chat template supports
it), so a quant, KV cache type or build that changes quality shows up next to the speed numbers:
| Section | Items | Passes when |
| --- | --- | --- |
| `tools` | 12 requests with 3 tools each | exactly one tool call, valid JSON arguments, the right function and the expected arguments |
| `coding` | 8 short Python functions | the answer's code passes its unit tests, run in a throwaway container (no network, read-only, unprivileged) |
| `retrieval` | a six-digit code hidden at 10 %, 50 % and 90 % depth in texts of 25 %, 50 % and 100 % of the context | the answer contains the code |
The score is the mean pass rate of the sections that could run (a server that refuses tool calls,
e.g. vLLM without a tool-call parser, doesn't count as 0). The eval set is versioned (`evalSet`);
only results of the same version compare.
## Waiting instead of polling
Every status call costs an agent a round of its context. The status endpoints (`/jobs/{id}`,
`/deployments/{id}`, `/benchmarks/{id}`, `/sweeps/{id}`) take `?wait=S` (seconds, at most 900): the
request is held until the state is settled (finished, running, failed, cancelled) or the time is up,
then answers with the current state plus `waitedSeconds` and `timedOut`. Something that waits for the
user's approval answers right away: there is nothing to wait for. Use one waiting call instead of a
polling loop, with a wait shorter than your HTTP client's timeout (and any proxy's).
## Guardrails
### Downloads
Settings → API tokens → **Guardrails for API downloads**. They apply to every token together;
downloads started in the UI aren't affected.
@@ -197,6 +336,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
+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;
+1
View File
@@ -0,0 +1 @@
ALTER TABLE `benchmark_runs` ADD `quality` text;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+14
View File
@@ -134,6 +134,20 @@
"when": 1792513935880,
"tag": "0018_benchmark_metadata",
"breakpoints": true
},
{
"idx": 19,
"version": "6",
"when": 1792587768766,
"tag": "0019_agent_tuning",
"breakpoints": true
},
{
"idx": 20,
"version": "6",
"when": 1792588720328,
"tag": "0020_quality_eval",
"breakpoints": true
}
]
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "kaname",
"version": "0.12.0",
"version": "0.14.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kaname",
"version": "0.12.0",
"version": "0.14.2",
"dependencies": {
"@base-ui/react": "^1.8.0",
"@libsql/client": "^0.18.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "kaname",
"version": "0.12.0",
"version": "0.14.2",
"private": true,
"scripts": {
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
@@ -33,9 +33,12 @@ import { Input } from "@/components/ui/input";
import { reportSummary, weightsLabel } from "@/lib/benchmark-report";
import { CONFIG_ROWS, describeSettings } from "@/lib/benchmark-view";
import type { ListRow } from "../benchmark-list";
import { AgentApprovalBar } from "@/components/approval-bar";
import { RequestedByBadge } from "@/components/requested-by-badge";
import { RunMetaCard } from "@/components/run-meta";
import { cancelBenchmark, deleteBenchmark, describeBenchmark, renameBenchmark } from "../actions";
import { AbReport } from "./ab-report";
import { QualityReport } from "./quality-report";
import { BenchmarkReport } from "./benchmark-report";
import { PublishCard } from "./publish-card";
@@ -60,7 +63,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
const [now, setNow] = useState(() => Date.now());
const [label, setLabel] = useState(initial.label ?? "");
const [description, setDescription] = useState(initial.description ?? "");
const active = r.state === "queued" || r.state === "running";
const active = r.state === "pending_approval" || r.state === "queued" || r.state === "running";
useEffect(() => {
if (!active) return;
@@ -82,6 +85,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
body: JSON.stringify({
deploymentId: r.deploymentId,
deploymentBId: r.kind === "ab" ? r.deploymentBId : null,
kind: r.kind,
label: r.label,
description: r.description,
...r.settings,
@@ -120,6 +124,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
state={r.state}
cancelling={!!r.cancelRequestedAt}
/>
<RequestedByBadge name={r.requestedBy} />
</div>
<p className="text-sm text-muted-foreground">
{r.deploymentId ? (
@@ -171,7 +176,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
)}
</p>
<p className="text-xs text-muted-foreground">
BetterBench ·{" "}
{r.kind === "eval" ? "Kaname" : "BetterBench"} ·{" "}
{r.kind === "ab"
? `paired A/B, target ±${r.settings.mdePct ?? 1}%, up to ${r.settings.maxPairs ?? 200} pairs`
: describeSettings(r.settings)}{" "}
@@ -265,6 +270,13 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
</CardContent>
</Card>
{r.state === "pending_approval" && (
<AgentApprovalBar
requestedBy={r.requestedBy}
what={`run ${r.kind === "ab" ? "an A/B" : r.kind === "eval" ? "the quality eval" : "a benchmark"} on ${s.deploymentName} (${describeSettings(r.settings)}${r.timeLimitS ? `, at most ${Math.round(r.timeLimitS / 60)} min` : ""})`}
base={`/api/benchmarks/${r.id}`}
/>
)}
{r.error && (
<div className="flex gap-3 rounded-xl border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm">
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-destructive" />
@@ -284,7 +296,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_340px]">
<div className="flex min-w-0 flex-col gap-4">
{r.kind === "ab" ? <AbReport run={r} /> : <BenchmarkReport run={r} />}
{r.kind === "ab" ? <AbReport run={r} /> : r.kind === "eval" ? <QualityReport quality={r.quality} running={active} /> : <BenchmarkReport run={r} />}
<LiveLog
url={`/api/benchmarks/${r.id}/logs`}
title="BetterBench output"
@@ -345,7 +357,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
</CardContent>
</Card>
<RunMetaCard meta={r.meta} metaB={r.metaB} system={r.system} />
{r.kind === "run" && (
{r.kind !== "ab" && (
<Card size="sm">
<CardHeader>
<CardTitle>Settings measured</CardTitle>
@@ -0,0 +1,68 @@
import { CheckIcon, XIcon } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import type { QualityResult } from "@/lib/db/schema";
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
import { cn } from "@/lib/utils";
/** A quality eval's result: the score, each section's pass rate and every item. */
export function QualityReport({ quality, running }: { quality: QualityResult | null; running: boolean }) {
if (!quality) {
return (
<Card>
<CardContent className="text-sm text-muted-foreground">{running ? "The quality eval is running; results appear when it's done." : "No result."}</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<CardTitle>Quality</CardTitle>
<CardDescription>
Eval set {quality.evalSet}: greedy decoding (temperature {quality.config.temperature}, seed {quality.config.seed}), thinking{" "}
{quality.config.thinking ? "on" : "off"}
{quality.config.contextTokens ? `, context ${quality.config.contextTokens.toLocaleString("en-US")} tokens` : ""}. Scores are the share of items that pass;
only results of the same eval set compare.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="flex items-baseline gap-2">
<span className="text-4xl font-semibold tabular-nums">{quality.score != null ? `${quality.score}%` : "—"}</span>
<span className="text-sm text-muted-foreground">overall (mean of the sections)</span>
</div>
<Table>
<TableHeader>
<TableRow>
<TableHead>Section</TableHead>
<TableHead className="text-right">Passed</TableHead>
<TableHead className="text-right">Score</TableHead>
<TableHead className="text-right">Time</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{quality.sections.map((s) => (
<TableRow key={s.section}>
<TableCell className="whitespace-normal">
<div className="font-medium">{SECTION_LABEL[s.section]}</div>
<div className="text-xs text-muted-foreground">{s.unsupported ? `Not counted: ${s.unsupported}` : SECTION_HINT[s.section]}</div>
</TableCell>
<TableCell className="text-right tabular-nums">{s.unsupported ? "—" : `${s.passed} / ${s.total}`}</TableCell>
<TableCell className="text-right font-medium tabular-nums">{s.score != null ? `${s.score}%` : "—"}</TableCell>
<TableCell className="text-right text-muted-foreground tabular-nums">{s.seconds} s</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<ul className="flex flex-col gap-1 text-xs">
{quality.items.map((i) => (
<li key={`${i.section}-${i.id}`} className="flex items-start gap-1.5">
{i.pass ? <CheckIcon className="mt-0.5 size-3.5 shrink-0 text-emerald-600" /> : <XIcon className="mt-0.5 size-3.5 shrink-0 text-destructive" />}
<span className="font-mono">{i.id}</span>
<span className={cn("min-w-0 break-words text-muted-foreground", !i.pass && "text-foreground")}>{i.detail}</span>
</li>
))}
</ul>
</CardContent>
</Card>
);
}
+142 -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,68 @@ export function BenchmarkList({ rows: initial, compact }: { rows: ListRow[]; com
</TableCell>
)}
<TableCell className="whitespace-normal">
<Link href={`/benchmarks/${r.id}`} className="font-medium hover:underline">
<Link
href={`/benchmarks/${r.id}`}
className="font-medium hover:underline"
>
{r.label ?? s.deploymentName}
</Link>
<div className="text-xs text-muted-foreground">
<div className="flex flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
{r.label && `${s.deploymentName} · `}
{s.repoId} · <LocalTime value={r.createdAt} />
<RequestedByBadge
name={r.requestedBy}
className="h-4 text-[10px]"
/>
</div>
</TableCell>
<TableCell className="hidden max-w-md whitespace-normal lg:table-cell">
<div className="flex flex-wrap gap-1">
<span className="rounded-4xl border border-foreground/15 px-1.5 text-[11px] leading-4">{s.runtimeName}</span>
<span className="rounded-4xl border border-foreground/15 px-1.5 text-[11px] leading-4">
{s.runtimeName}
</span>
{configChips(s).map((c) => (
<span key={c} className="rounded-4xl bg-muted px-1.5 text-[11px] leading-4 text-muted-foreground">
<span
key={c}
className="rounded-4xl bg-muted px-1.5 text-[11px] leading-4 text-muted-foreground"
>
{c}
</span>
))}
</div>
<div className="mt-0.5 text-[11px] text-muted-foreground">{describeSettings(r.settings)}</div>
<div className="mt-0.5 text-[11px] text-muted-foreground">
{describeSettings(r.settings)}
</div>
</TableCell>
<TableCell className="text-right font-medium tabular-nums">{fmt(h.decode)}</TableCell>
<TableCell className="text-right tabular-nums">{h.ttftMs != null ? `${Math.round(h.ttftMs)} ms` : "–"}</TableCell>
<TableCell className="hidden text-right tabular-nums md:table-cell" title={h.prefill ? `at ${h.prefill.depth} tokens` : undefined}>
<TableCell className="text-right font-medium tabular-nums">
{r.kind === "eval" ? (
<span title="Quality eval score">{r.quality?.score != null ? `${r.quality.score}% quality` : "–"}</span>
) : (
fmt(h.decode)
)}
</TableCell>
<TableCell className="text-right tabular-nums">
{h.ttftMs != null ? `${Math.round(h.ttftMs)} ms` : "–"}
</TableCell>
<TableCell
className="hidden text-right tabular-nums md:table-cell"
title={
h.prefill ? `at ${h.prefill.depth} tokens` : undefined
}
>
{fmt(h.prefill?.tps, 0)}
</TableCell>
<TableCell className="hidden text-right tabular-nums md:table-cell" title={h.peak ? `at ${h.peak.level} parallel` : undefined}>
<TableCell
className="hidden text-right tabular-nums md:table-cell"
title={h.peak ? `at ${h.peak.level} parallel` : undefined}
>
{fmt(h.peak?.tps)}
</TableCell>
<TableCell>
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
<BenchmarkStateBadge
state={r.state}
cancelling={!!r.cancelRequestedAt}
/>
</TableCell>
</TableRow>
);
+21 -2
View File
@@ -5,6 +5,7 @@ import { Card } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { getBenchmarks } from "@/lib/benchmarks";
import { metaRows } from "@/lib/benchmark-meta";
import { SECTION_LABEL } from "@/lib/quality-view";
import { CONFIG_ROWS, deltaPct, describeSettings, headline } from "@/lib/benchmark-view";
import type { BenchmarkSummary } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
@@ -12,7 +13,7 @@ import { cn } from "@/lib/utils";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Compare benchmarks" };
type Metric = { label: string; unit: string; higherIsBetter: boolean; digits: number; get: (s: BenchmarkSummary | null) => number | null };
type Metric = { label: string; unit: string; higherIsBetter: boolean; digits: number; get: (s: BenchmarkSummary | null, runIndex?: number) => number | null };
/** Differences smaller than this are shown without color: below what a single run can resolve. */
const NOISE_PCT = 2;
@@ -87,6 +88,24 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
rows: levels.map((l) => ({ label: `${l} parallel`, unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => s?.concurrency.find((c) => c.level === l)?.aggregate_tps ?? null })),
},
];
// Quality evals: the score and each section's pass rate (only when some of the runs are evals).
const quality = runs.map((r) => r.quality);
if (quality.some(Boolean)) {
const sections = [...new Set(quality.flatMap((q) => q?.sections.map((s) => s.section) ?? []))];
groups.push({
group: `Quality (${[...new Set(quality.filter(Boolean).map((q) => q!.evalSet))].join(", ")})`,
rows: [
{ label: "Score", unit: "%", higherIsBetter: true, digits: 1, get: (_s, i) => quality[i!]?.score ?? null },
...sections.map((sec) => ({
label: SECTION_LABEL[sec],
unit: "%",
higherIsBetter: true,
digits: 1,
get: (_s: BenchmarkSummary | null, i?: number) => quality[i!]?.sections.find((x) => x.section === sec)?.score ?? null,
})),
],
});
}
const metrics = groups.filter((g) => g.rows.length > 0);
// Hardware, runtime version, model/quant/KV, context and concurrency as recorded at the start of each run.
@@ -187,7 +206,7 @@ function MetricGroup({ group, rows, sums, cols }: { group: string; rows: Metric[
</TableCell>
</TableRow>
{rows.map((m) => {
const vals = sums.map((s) => m.get(s));
const vals = sums.map((s, i) => m.get(s, i));
const present = vals.filter((v): v is number => v != null);
const best = present.length > 1 ? (m.higherIsBetter ? Math.max(...present) : Math.min(...present)) : null;
return (
@@ -9,20 +9,32 @@ import { BarChart } from "@/components/bar-chart";
import { BenchmarkStateBadge } from "@/components/benchmark-state";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { AgentApprovalBar } from "@/components/approval-bar";
import { RequestedByBadge } from "@/components/requested-by-badge";
import { metaRows } from "@/lib/benchmark-meta";
import { describeSettings, headline } from "@/lib/benchmark-view";
import type { benchmarkSweeps, BenchmarkSummary, ResourceStats, RunMeta, SweepVariant } from "@/lib/db/schema";
import type { benchmarkSweeps, BenchmarkSummary, QualityResult, ResourceStats, RunMeta, SweepVariant } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
import { cn } from "@/lib/utils";
type Sweep = typeof benchmarkSweeps.$inferSelect;
type Run = { id: string; state: string; summary: BenchmarkSummary | null; resources: ResourceStats | null; phase: string | null; error: string | null; meta: RunMeta | null };
type Run = {
id: string;
state: string;
summary: BenchmarkSummary | null;
resources: ResourceStats | null;
phase: string | null;
error: string | null;
meta: RunMeta | null;
quality: QualityResult | null;
};
export type SweepData = { sweep: Sweep; runs: Run[] };
const VARIANT_STATE: Record<SweepVariant["state"], string> = {
pending: "Waiting",
deploying: "Deploying",
benchmarking: "Benchmarking",
evaluating: "Quality eval",
done: "Done",
failed: "Failed",
skipped: "Skipped",
@@ -40,11 +52,13 @@ type Row = {
vram: number | null;
power: number | null;
temp: number | null;
quality: number | null;
};
function rowsOf(data: SweepData): Row[] {
return data.sweep.variants.map((v) => {
const run = data.runs.find((r) => r.id === v.runId) ?? null;
const ev = data.runs.find((r) => r.id === v.evalRunId) ?? null;
const h = headline(run?.summary ?? null);
const c = run?.resources?.containers.find((x) => x.side === "a");
const g = run?.resources?.gpus ?? [];
@@ -60,6 +74,7 @@ function rowsOf(data: SweepData): Row[] {
vram: g.some((x) => x.vramPeakMb != null) ? g.reduce((s, x) => s + (x.vramPeakMb ?? 0), 0) : null,
power: g.some((x) => x.powerAvgW != null) ? g.reduce((s, x) => s + (x.powerAvgW ?? 0), 0) : null,
temp: g.some((x) => x.tempPeakC != null) ? Math.max(...g.map((x) => x.tempPeakC ?? -Infinity)) : null,
quality: ev?.quality?.score ?? null,
};
});
}
@@ -90,7 +105,7 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
const [data, setData] = useState(initial);
const [busy, setBusy] = useState(false);
const { sweep } = data;
const active = sweep.state === "queued" || sweep.state === "running";
const active = sweep.state === "pending_approval" || sweep.state === "queued" || sweep.state === "running";
useEffect(() => {
if (!active) return;
@@ -127,7 +142,9 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
vram: best(rows, "vram", false),
power: best(rows, "power", false),
temp: best(rows, "temp", false),
quality: best(rows, "quality", true),
};
const hasQuality = !!sweep.settings.quality;
const cell = (v: number | null, b: number | null, fmt: (x: number) => string) => (
<td className={cn("px-3 py-2 text-right tabular-nums", v != null && v === b && "font-semibold")}>{v != null ? fmt(v) : "—"}</td>
);
@@ -153,6 +170,7 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
</p>
</div>
<div className="flex items-center gap-2">
<RequestedByBadge name={sweep.requestedBy} />
<BenchmarkStateBadge state={sweep.state} cancelling={!!sweep.cancelRequestedAt && active} />
{runIds.length >= 2 && (
<Link href={`/benchmarks/compare?ids=${runIds.join(",")}`} className={buttonVariants({ variant: "outline", size: "sm" })}>
@@ -179,6 +197,13 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
{done} of {rows.length} variants finished. Each variant is deployed, benchmarked and removed again, one after another.
</p>
)}
{sweep.state === "pending_approval" && (
<AgentApprovalBar
requestedBy={sweep.requestedBy}
what={`run a sweep of ${rows.length} variants from ${sweep.base.name} (${sweep.params.map((p) => `${p.key}: ${p.values.join(", ")}`).join("; ")}${sweep.timeLimitS ? `, at most ${Math.round(sweep.timeLimitS / 60)} min` : ""}); each variant is deployed, benchmarked and removed`}
base={`/api/sweeps/${sweep.id}`}
/>
)}
{sweep.error && <p className="text-sm text-destructive">{sweep.error}</p>}
{finished.length > 0 && (
@@ -226,6 +251,7 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
</th>
))}
<th className="px-3 py-2 text-right font-medium">Decode t/s</th>
{hasQuality && <th className="px-3 py-2 text-right font-medium">Quality</th>}
<th className="px-3 py-2 text-right font-medium">TTFT ms</th>
<th className="px-3 py-2 text-right font-medium">Prefill t/s</th>
<th className="px-3 py-2 text-right font-medium">Peak t/s</th>
@@ -259,6 +285,7 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
</td>
))}
{cell(r.decode, bestOf.decode, (x) => x.toFixed(1))}
{hasQuality && cell(r.quality, bestOf.quality, (x) => `${x}%`)}
{cell(r.ttft, bestOf.ttft, (x) => x.toFixed(0))}
{cell(r.prefill, bestOf.prefill, (x) => x.toFixed(0))}
{cell(r.peak, bestOf.peak, (x) => x.toFixed(1))}
@@ -64,6 +64,7 @@ export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initia
const keys = base ? sweepKeysFor(base.engine, base.accelerator) : [];
const [params, setParams] = useState<Param[]>([{ key: "contextSize", text: "", files: [] }]);
const [label, setLabel] = useState("");
const [quality, setQuality] = useState(false);
const [mode, setMode] = useState("quick");
const [passes, setPasses] = useState("10");
const [phases, setPhases] = useState<BenchmarkPhase[]>(["decode", "prefill", "concurrency"]);
@@ -95,6 +96,7 @@ export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initia
quick: mode === "quick",
passes: mode === "custom" ? Number(passes) || 10 : null,
phases: phases.length === PHASES.length ? [] : phases,
quality,
}),
});
const json = await res.json().catch(() => ({}));
@@ -205,6 +207,13 @@ export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initia
</label>
))}
</div>
<label className="flex cursor-pointer items-start gap-2 text-sm">
<Checkbox checked={quality} onCheckedChange={(v) => setQuality(v === true)} className="mt-0.5" />
<span className="flex flex-col">
<span>Also run the quality eval on each variant</span>
<span className="text-xs text-muted-foreground">Tool calling, coding and long-context retrieval, after the speed run (adds a few minutes per variant).</span>
</span>
</label>
<div className="flex flex-col gap-1.5">
<Label htmlFor="sw-label">Label</Label>
<Input id="sw-label" value={label} onChange={(e) => setLabel(e.target.value)} maxLength={80} placeholder="e.g. context vs KV cache (optional)" />
@@ -1,6 +1,6 @@
"use client";
import { GaugeIcon, GitCompareArrowsIcon, Grid3x3Icon } from "lucide-react";
import { BadgeCheckIcon, GaugeIcon, GitCompareArrowsIcon, Grid3x3Icon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
@@ -14,6 +14,8 @@ import { NativeSelect } from "@/components/ui/native-select";
import { abHeadline } from "@/lib/ab-report";
import { headline } from "@/lib/benchmark-view";
import type { BenchmarkPhase } from "@/lib/db/schema";
import { QUALITY_SECTIONS, type QualitySection } from "@/lib/db/schema";
import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view";
import { cn } from "@/lib/utils";
import type { ListRow } from "../../benchmarks/benchmark-list";
@@ -23,7 +25,7 @@ const PHASES: { id: BenchmarkPhase; label: string; hint: string }[] = [
{ id: "concurrency", label: "Parallel requests", hint: "1, 2, 4 and 8 at once" },
];
type Mode = "run" | "ab" | "sweep";
type Mode = "run" | "ab" | "quality" | "sweep";
type Peer = { id: string; name: string; state: string; modelId: string };
/** Benchmark this deployment: a single run, a paired A/B against another one, or a sweep. */
@@ -41,6 +43,7 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
const [peerId, setPeerId] = useState("");
const [mde, setMde] = useState("1");
const [maxPairs, setMaxPairs] = useState("200");
const [sections, setSections] = useState<QualitySection[]>([...QUALITY_SECTIONS]);
const active = runs.some((r) => r.state === "queued" || r.state === "running");
useEffect(() => {
@@ -87,6 +90,7 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
const TABS: { id: Mode; label: string; icon: typeof GaugeIcon }[] = [
{ id: "run", label: "Run", icon: GaugeIcon },
{ id: "ab", label: "A/B", icon: GitCompareArrowsIcon },
{ id: "quality", label: "Quality", icon: BadgeCheckIcon },
{ id: "sweep", label: "Sweep", icon: Grid3x3Icon },
];
@@ -211,6 +215,32 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
</>
)}
{tab === "quality" && (
<>
<p className="text-xs text-muted-foreground">
A short, deterministic check of the answers (greedy decoding, fixed seed, thinking off): to see whether a quant, KV cache type or build changes quality,
next to the speed numbers.
</p>
<div className="flex flex-col gap-1.5">
{QUALITY_SECTIONS.map((s) => (
<label key={s} className="flex cursor-pointer items-start gap-2">
<Checkbox checked={sections.includes(s)} onCheckedChange={(v) => setSections((cur) => (v ? [...cur, s] : cur.filter((x) => x !== s)))} className="mt-0.5" />
<span className="flex flex-col">
<span>{SECTION_LABEL[s]}</span>
<span className="text-xs text-muted-foreground">{SECTION_HINT[s]}</span>
</span>
</label>
))}
</div>
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
<Button onClick={() => start({ kind: "eval", evalSections: sections.length === QUALITY_SECTIONS.length ? [] : sections })} disabled={!running || busy || sections.length === 0}>
<BadgeCheckIcon />
Run quality eval
</Button>
{!running && <p className="text-xs text-muted-foreground">Start the deployment to evaluate it.</p>}
</>
)}
{tab === "sweep" && (
<>
<p className="text-xs text-muted-foreground">
@@ -231,11 +261,15 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
return (
<Link key={r.id} href={`/benchmarks/${r.id}`} className="flex items-center justify-between gap-2 rounded-md px-1.5 py-1 hover:bg-muted">
<span className="min-w-0 truncate">
{r.kind === "ab" && <span className="mr-1 rounded border px-1 text-[10px] text-muted-foreground">A/B</span>}
{r.kind !== "run" && <span className="mr-1 rounded border px-1 text-[10px] text-muted-foreground">{r.kind === "ab" ? "A/B" : "quality"}</span>}
{r.label ?? new Date(r.createdAt).toLocaleString()}
</span>
<span className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground tabular-nums">
{r.kind === "ab" ? r.ab && abHeadline(r.ab.decode_tps) : h.decode != null && `${h.decode.toFixed(1)} t/s`}
{r.kind === "ab"
? r.ab && abHeadline(r.ab.decode_tps)
: r.kind === "eval"
? r.quality?.score != null && `${r.quality.score}%`
: h.decode != null && `${h.decode.toFixed(1)} t/s`}
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
</span>
</Link>
@@ -1,6 +1,9 @@
"use client";
import { ExternalLinkIcon, PencilIcon, PlayIcon, SendIcon, SquareIcon, Trash2Icon } from "lucide-react";
import { ExternalLinkIcon, PencilIcon, PlayIcon, SendIcon, ShieldCheckIcon, ShieldIcon, SquareIcon, Trash2Icon } from "lucide-react";
import { toast } from "sonner";
import { AgentApprovalBar } from "@/components/approval-bar";
import { RequestedByBadge } from "@/components/requested-by-badge";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
@@ -83,6 +86,13 @@ export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment;
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-xl font-semibold">{d.name}</h1>
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
<RequestedByBadge name={d.requestedBy} />
{d.protected && (
<span className="inline-flex items-center gap-1 rounded-4xl border border-emerald-500/30 bg-emerald-500/10 px-2 text-xs text-emerald-700 dark:text-emerald-300">
<ShieldCheckIcon className="size-3" />
protected
</span>
)}
</div>
<p className="text-sm text-muted-foreground">
<Link href={`/${d.repoId}`} className="hover:underline">
@@ -118,6 +128,19 @@ export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment;
Start
</Button>
)}
<Button
variant="outline"
title={d.protected ? "Agents can't touch it now; click to allow them again" : "Agents (API tokens) can't edit, stop, delete or benchmark a protected deployment, nor crowd it out of VRAM"}
onClick={async () => {
const res = await fetch(`/api/deployments/${d.id}/protect`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ protected: !d.protected }) });
if (!res.ok) return void toast.error(`Could not change it (${res.status})`);
setD({ ...d, protected: !d.protected });
toast.success(d.protected ? "No longer protected from agents" : "Protected from agents");
}}
>
{d.protected ? <ShieldCheckIcon /> : <ShieldIcon />}
{d.protected ? "Protected" : "Protect"}
</Button>
<Link
href={`/deployments/${d.id}/edit`}
className={cn(buttonVariants({ variant: "outline" }), active && "pointer-events-none opacity-50")}
@@ -153,6 +176,13 @@ export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment;
</div>
</CardContent>
</Card>
{d.startRequestedAt && (
<AgentApprovalBar
requestedBy={d.requestedBy}
what={`start this deployment (${d.runtimeName}${file ? `, ${file}` : ""}, context ${d.options.contextSize}${d.memoryMb ? `, ${formatBytes(d.memoryMb * 2 ** 20)} RAM limit` : ""})`}
base={`/api/deployments/${d.id}`}
/>
)}
{d.state === "failed" && d.error && (
<pre className="max-h-72 overflow-auto rounded-xl bg-destructive/10 px-4 py-3 text-xs whitespace-pre-wrap text-destructive">{d.error}</pre>
+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>
);
}
+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>
);
}
+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);
}
});
@@ -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);
}
});
+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) => {
try {
const ids = (new URL(req.url).searchParams.get("ids") ?? "").split(",").map((s) => s.trim()).filter(Boolean).slice(0, 16);
if (ids.length < 2) return v1Error(400, "invalid_request", "Pass at least two run ids: ?ids=<id>,<id>");
return v1Json(await compareRuns(ids));
} catch (err) {
return v1Catch(err);
}
});
+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 speed run (kind "run"), a paired A/B ("ab") or the quality eval ("eval") on the token's own running deployment(s). */
export const POST = withToken("benchmarks:run", async (req, { token }) => {
try {
const body = AgentRunBody.parse(await req.json());
const r = await act(token, `benchmark.${body.kind}`, { type: "benchmark" }, () => requestRun(token, body));
return v1Json(
{
...r,
message:
r.state === "pending_approval"
? "Requested; it waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop."
: `Queued; GET /api/v1/benchmarks/${r.id}?wait=900 for the result (stopped after ${r.timeLimitMinutes} min).`,
},
201,
);
} catch (err) {
return v1Catch(err);
}
});
+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>
);
}
+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" />}
+89
View File
@@ -0,0 +1,89 @@
{
"instructions": "Write the Python 3 function described below. Use only the standard library. Reply with the complete function definition, starting with def, in a single ```python code block and nothing else.",
"items": [
{
"id": "is-palindrome",
"prompt": "is_palindrome(s: str) -> bool: True if s reads the same forwards and backwards, ignoring case and every character that isn't a letter or a digit.",
"tests": [
"assert is_palindrome('A man, a plan, a canal: Panama') is True",
"assert is_palindrome('race a car') is False",
"assert is_palindrome('') is True",
"assert is_palindrome('No lemon, no melon') is True",
"assert is_palindrome('ab2a') is False"
]
},
{
"id": "fizzbuzz",
"prompt": "fizzbuzz(n: int) -> list[str]: for 1..n, 'Fizz' for multiples of 3, 'Buzz' for multiples of 5, 'FizzBuzz' for multiples of both, else the number as a string.",
"tests": [
"assert fizzbuzz(5) == ['1', '2', 'Fizz', '4', 'Buzz']",
"assert fizzbuzz(15)[-1] == 'FizzBuzz'",
"assert fizzbuzz(0) == []",
"assert len(fizzbuzz(100)) == 100"
]
},
{
"id": "merge-intervals",
"prompt": "merge_intervals(intervals: list[list[int]]) -> list[list[int]]: merge overlapping or touching [start, end] intervals and return them sorted by start.",
"tests": [
"assert merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]",
"assert merge_intervals([[1, 4], [4, 5]]) == [[1, 5]]",
"assert merge_intervals([]) == []",
"assert merge_intervals([[5, 7], [1, 2]]) == [[1, 2], [5, 7]]",
"assert merge_intervals([[1, 10], [2, 3], [4, 5]]) == [[1, 10]]"
]
},
{
"id": "word-count",
"prompt": "word_count(text: str) -> dict[str, int]: count words, lowercased, where a word is a run of letters (anything else separates words).",
"tests": [
"assert word_count('Hello, hello world!') == {'hello': 2, 'world': 1}",
"assert word_count('') == {}",
"assert word_count('one-two three') == {'one': 1, 'two': 1, 'three': 1}",
"assert word_count('A a A b') == {'a': 3, 'b': 1}"
]
},
{
"id": "roman-to-int",
"prompt": "roman_to_int(s: str) -> int: convert a Roman numeral (I, V, X, L, C, D, M, with subtractive forms like IV and CM) to an integer.",
"tests": [
"assert roman_to_int('III') == 3",
"assert roman_to_int('LVIII') == 58",
"assert roman_to_int('MCMXCIV') == 1994",
"assert roman_to_int('XLIX') == 49",
"assert roman_to_int('MMXXVI') == 2026"
]
},
{
"id": "flatten",
"prompt": "flatten(nested: list) -> list: return all non-list items of an arbitrarily nested list, in order.",
"tests": [
"assert flatten([1, [2, [3, [4]], 5]]) == [1, 2, 3, 4, 5]",
"assert flatten([]) == []",
"assert flatten([[], [[]], [1]]) == [1]",
"assert flatten(['a', ['b', ['c']]]) == ['a', 'b', 'c']"
]
},
{
"id": "second-largest",
"prompt": "second_largest(nums: list[int]) -> int | None: the second largest distinct value, or None if there isn't one.",
"tests": [
"assert second_largest([3, 1, 4, 1, 5, 9, 2, 6]) == 6",
"assert second_largest([7, 7, 7]) is None",
"assert second_largest([]) is None",
"assert second_largest([-2, -5, -1]) == -2",
"assert second_largest([10, 9]) == 9"
]
},
{
"id": "rle-encode",
"prompt": "rle_encode(s: str) -> str: run-length encode a string as each character followed by its run length, e.g. 'aaabcc' -> 'a3b1c2'.",
"tests": [
"assert rle_encode('aaabcc') == 'a3b1c2'",
"assert rle_encode('') == ''",
"assert rle_encode('abc') == 'a1b1c1'",
"assert rle_encode('zzzzzzzzzzzz') == 'z12'"
]
}
]
}
+41
View File
@@ -0,0 +1,41 @@
{
"lengths": [0.25, 0.5, 1.0],
"positions": [0.1, 0.5, 0.9],
"reserveTokens": 384,
"seed": 20261021,
"needle": "Note for later: the access code for the {color} vault is {code}.",
"question": "In the text above there is one note with an access code for the {color} vault. What is that access code? Answer with the six-digit number only.",
"colors": ["amber", "cobalt", "crimson", "jade", "silver", "violet", "ochre", "teal", "scarlet"],
"filler": [
"The river bends twice before it reaches the old mill at the edge of the valley.",
"Most of the orchard was planted after the long winter, when the soil had recovered.",
"A narrow path leads from the station to the market square, lined with plane trees.",
"In spring the meadows fill with clover and the bees return to the wooden hives.",
"The library keeps its oldest maps in a cool room behind the reading hall.",
"Fishing boats leave the harbour before dawn and come back around midday.",
"The bakery on the corner opens at six and is usually sold out by ten.",
"Snow rarely stays on the lower slopes for more than a few days at a time.",
"An old stone bridge crosses the stream where the two footpaths meet.",
"The town hall clock was repaired last year and now runs a minute fast.",
"Every autumn the vineyards hire extra hands for the harvest weeks.",
"The lighthouse has been automated, but a keeper still checks it each week.",
"A small museum by the church shows tools that farmers used a century ago.",
"The tram line was extended to the university campus in the north.",
"Wild garlic grows along the shaded banks of the brook in early May.",
"The guesthouse serves breakfast in a garden room that faces the hills.",
"Cyclists often stop at the fountain to refill their bottles before the climb.",
"The weekly market sells cheese from three farms in the neighbouring villages.",
"On clear nights the observatory opens its dome to visitors after nine.",
"The ferry runs every hour in summer and twice a day in the colder months.",
"A row of chestnut trees marks the old boundary of the monastery grounds.",
"The pottery workshop fires its kiln on Thursdays and sells seconds on Fridays.",
"Fog settles in the valley on most mornings and lifts by late morning.",
"The cooperative store stocks seeds, rope, lamp oil and tinned food.",
"Herons nest in the reeds at the far end of the lake each year.",
"The school bus takes the long way round when the pass is closed.",
"A painter rents the attic above the bookshop for the summer months.",
"The old railway embankment is now a walking trail through the woods.",
"Shepherds move the flocks to the high pastures in the first week of June.",
"The smithy still repairs gates and hinges for the farms nearby."
]
}
+160
View File
@@ -0,0 +1,160 @@
{
"tools": {
"get_weather": {
"description": "Current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": { "type": "string", "description": "City name, e.g. Berlin" },
"unit": { "type": "string", "enum": ["celsius", "fahrenheit"] }
},
"required": ["city", "unit"]
}
},
"convert_currency": {
"description": "Convert an amount of money between currencies.",
"parameters": {
"type": "object",
"properties": {
"amount": { "type": "number" },
"from": { "type": "string", "description": "ISO 4217 code, e.g. USD" },
"to": { "type": "string", "description": "ISO 4217 code, e.g. EUR" }
},
"required": ["amount", "from", "to"]
}
},
"create_calendar_event": {
"description": "Add an event to the user's calendar.",
"parameters": {
"type": "object",
"properties": {
"title": { "type": "string" },
"date": { "type": "string", "description": "YYYY-MM-DD" },
"time": { "type": "string", "description": "HH:MM, 24-hour" },
"duration_minutes": { "type": "integer" }
},
"required": ["title", "date", "time", "duration_minutes"]
}
},
"set_timer": {
"description": "Start a countdown timer.",
"parameters": {
"type": "object",
"properties": { "minutes": { "type": "integer" } },
"required": ["minutes"]
}
},
"get_stock_price": {
"description": "Latest price of a stock by its ticker symbol.",
"parameters": {
"type": "object",
"properties": { "ticker": { "type": "string", "description": "e.g. AAPL" } },
"required": ["ticker"]
}
},
"search_files": {
"description": "Search the user's files.",
"parameters": {
"type": "object",
"properties": {
"query": { "type": "string" },
"extension": { "type": "string", "description": "File extension without the dot, e.g. pdf" }
},
"required": ["query"]
}
},
"send_message": {
"description": "Send a chat message to a contact.",
"parameters": {
"type": "object",
"properties": {
"recipient": { "type": "string" },
"text": { "type": "string" }
},
"required": ["recipient", "text"]
}
},
"calculate": {
"description": "Evaluate an arithmetic expression.",
"parameters": {
"type": "object",
"properties": { "expression": { "type": "string", "description": "e.g. 3 * (4 + 5)" } },
"required": ["expression"]
}
}
},
"items": [
{
"id": "weather-berlin",
"tools": ["get_weather", "get_stock_price", "set_timer"],
"prompt": "What's the weather in Berlin right now? Use Celsius.",
"expect": { "name": "get_weather", "args": { "city": "Berlin", "unit": "celsius" } }
},
{
"id": "currency-usd-eur",
"tools": ["convert_currency", "calculate", "get_stock_price"],
"prompt": "How much is 250 US dollars in euros?",
"expect": { "name": "convert_currency", "args": { "amount": 250, "from": "USD", "to": "EUR" } }
},
{
"id": "calendar-budget",
"tools": ["create_calendar_event", "set_timer", "send_message"],
"prompt": "Put a meeting called Budget review on 2026-11-03 at 14:30 for 45 minutes in my calendar.",
"expect": { "name": "create_calendar_event", "args": { "title": { "contains": "budget review" }, "date": "2026-11-03", "time": "14:30", "duration_minutes": 45 } }
},
{
"id": "timer-12",
"tools": ["set_timer", "create_calendar_event", "get_weather"],
"prompt": "Set a timer for 12 minutes.",
"expect": { "name": "set_timer", "args": { "minutes": 12 } }
},
{
"id": "stock-aapl",
"tools": ["get_stock_price", "convert_currency", "search_files"],
"prompt": "What's Apple's stock price at the moment? The ticker is AAPL.",
"expect": { "name": "get_stock_price", "args": { "ticker": "AAPL" } }
},
{
"id": "files-invoices",
"tools": ["search_files", "send_message", "calculate"],
"prompt": "Find my PDF files about invoices.",
"expect": { "name": "search_files", "args": { "query": { "contains": "invoice" }, "extension": { "oneOf": ["pdf", ".pdf"] } } }
},
{
"id": "message-maria",
"tools": ["send_message", "create_calendar_event", "set_timer"],
"prompt": "Tell Maria that I'll be ten minutes late.",
"expect": { "name": "send_message", "args": { "recipient": "Maria", "text": { "contains": "late" } } }
},
{
"id": "weather-tokyo-f",
"tools": ["get_weather", "convert_currency", "search_files"],
"prompt": "Weather in Tokyo, in Fahrenheit please.",
"expect": { "name": "get_weather", "args": { "city": "Tokyo", "unit": "fahrenheit" } }
},
{
"id": "currency-jpy-chf",
"tools": ["calculate", "convert_currency", "get_weather"],
"prompt": "Convert 1200 Japanese yen to Swiss francs.",
"expect": { "name": "convert_currency", "args": { "amount": 1200, "from": "JPY", "to": "CHF" } }
},
{
"id": "timer-90",
"tools": ["create_calendar_event", "set_timer", "send_message"],
"prompt": "I need a 90 minute timer.",
"expect": { "name": "set_timer", "args": { "minutes": 90 } }
},
{
"id": "calendar-dentist",
"tools": ["send_message", "get_weather", "create_calendar_event"],
"prompt": "Schedule 'Dentist' for 2026-12-01 at 09:00, it takes 30 minutes.",
"expect": { "name": "create_calendar_event", "args": { "title": { "contains": "dentist" }, "date": "2026-12-01", "time": "09:00", "duration_minutes": 30 } }
},
{
"id": "calc-17x23",
"tools": ["calculate", "get_stock_price", "set_timer"],
"prompt": "What is 17 times 23? Use the calculator.",
"expect": { "name": "calculate", "args": { "expression": { "matches": "^\\s*17\\s*[*x×]\\s*23\\s*$" } } }
}
]
}
+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.`;
}
+285
View File
@@ -0,0 +1,285 @@
import "server-only";
import { and, desc, eq, or } from "drizzle-orm";
import { z } from "zod";
import { checkRun, TuningError, type TuningGuardrails } from "@/lib/agent-tuning";
import { gpuLoad } from "@/lib/agent-deployments";
import type { TokenIdentity } from "@/lib/api-tokens";
import { metaRows } from "@/lib/benchmark-meta";
import { headline } from "@/lib/benchmark-view";
import { BENCHMARK_PHASES, type BenchmarkSummary, benchmarkRuns, QUALITY_SECTIONS, type QualityResult, type RunMeta } from "@/lib/db/schema";
import { db } from "@/lib/db/client";
import { BenchmarkBody, type BenchmarkRow, createBenchmark, getBenchmark, getBenchmarks } from "@/lib/benchmarks";
import { getDeployment } from "@/lib/deployments";
import { getTuning } from "@/lib/settings";
import { MAX_SWEEP_PARAMS, splitValues } from "@/lib/sweep";
import { createSweep, getSweep, type SweepRow } from "@/lib/sweeps";
// Benchmark runs, A/B runs and sweeps through the API: on the token's own deployments only, one at a
// time across all agents, with time limits and (by default) the user's approval.
export const AgentRunBody = z
.object({
/** run: BetterBench speed; ab: paired A/B; eval: the quality eval (tool calling, coding, retrieval). */
kind: z.enum(["run", "ab", "eval"]).default("run"),
deploymentId: z.string().min(1),
/** A/B: the second deployment (same model). */
deploymentBId: z.string().min(1).optional(),
label: z.string().trim().max(120).optional(),
description: z.string().trim().max(4000).optional(),
/** quick: 5 passes, a smoke check; full (default): 20 passes, comparable. */
quick: z.boolean().default(false),
passes: z.number().int().min(1).max(200).optional(),
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
mdePct: z.number().min(0.1).max(50).optional(),
maxPairs: z.number().int().min(12).max(2000).optional(),
/** eval: which sections (default all). */
sections: z.array(z.enum(QUALITY_SECTIONS)).max(3).optional(),
})
.strict();
export const AgentSweepBody = z
.object({
baseDeploymentId: z.string().min(1),
label: z.string().trim().max(80).optional(),
/** One or two settings with their values, e.g. [{ key: "kvCache", values: ["f16", "q8_0"] }]. */
params: z
.array(z.object({ key: z.string().min(1).max(40), values: z.array(z.string().max(1024)).min(1).max(16) }).strict())
.min(1)
.max(MAX_SWEEP_PARAMS),
quick: z.boolean().default(true),
passes: z.number().int().min(1).max(200).optional(),
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
/** Also run the quality eval on each variant. */
quality: z.boolean().default(false),
})
.strict();
/** A deployment this token may benchmark: its own, not protected, running. */
async function benchmarkable(token: TokenIdentity, id: string, role: string) {
const d = await getDeployment(id);
if (!d) throw new TuningError("not_owner", `${role} not found.`, 404);
if (d.protected) throw new TuningError("protected", `"${d.name}" is protected; agents can't benchmark it.`, 403);
if (d.requestedByTokenId !== token.id) throw new TuningError("not_owner", `"${d.name}" wasn't created by this token; agents only benchmark their own deployments. Deploy the model yourself (POST /api/v1/deployments).`, 403);
return d;
}
const requested = (token: TokenIdentity) => ({ tokenId: token.id, name: token.name });
/** Queue a run or A/B against the token's own running deployment(s). */
export async function requestRun(token: TokenIdentity, body: z.infer<typeof AgentRunBody>, g?: TuningGuardrails) {
const guard = g ?? (await getTuning());
await benchmarkable(token, body.deploymentId, body.kind === "ab" ? "Deployment A" : "The deployment");
if (body.kind === "ab") {
if (!body.deploymentBId) throw new TuningError("not_owner", "An A/B needs deploymentBId (your second deployment of the same model).", 400);
await benchmarkable(token, body.deploymentBId, "Deployment B");
}
checkRun(await gpuLoad());
const pending = guard.approvalMode === "approve";
const row = await createBenchmark(
BenchmarkBody.parse({
deploymentId: body.deploymentId,
deploymentBId: body.kind === "ab" ? body.deploymentBId : null,
label: body.label ?? null,
description: body.description ?? null,
quick: body.quick,
passes: body.passes ?? null,
phases: body.phases,
mdePct: body.mdePct ?? null,
maxPairs: body.maxPairs ?? null,
kind: body.kind,
evalSections: body.sections,
}),
{ requestedBy: requested(token), pendingApproval: pending, timeLimitS: guard.maxRunMinutes * 60 },
);
return { id: row.id, state: pending ? "pending_approval" : "queued", timeLimitMinutes: guard.maxRunMinutes };
}
/** Queue a sweep from the token's own base deployment (each variant deploys and is removed again). */
export async function requestSweep(token: TokenIdentity, body: z.infer<typeof AgentSweepBody>, g?: TuningGuardrails) {
const guard = g ?? (await getTuning());
const base = await benchmarkable(token, body.baseDeploymentId, "The base deployment");
const load = await gpuLoad();
checkRun(load);
// Each variant starts its own deployment; an agent deployment still running would share the GPU.
if (load.agentDeployments > 0) {
throw new TuningError("gpu_busy", "an agent deployment is still running or waiting to start; a sweep deploys each variant itself. Stop yours first (POST /api/v1/deployments/{id}/stop).", 429);
}
const count = body.params.reduce((n, p) => n * splitValues(p.values.join(",")).length, 1);
if (count > guard.maxSweepVariants) {
throw new TuningError("too_many_variants", `That's ${count} variants; agents may run at most ${guard.maxSweepVariants} per sweep. Vary fewer values.`);
}
const pending = guard.approvalMode === "approve";
const row = await createSweep(
{ baseDeploymentId: base.id, label: body.label ?? null, params: body.params, quick: body.quick, passes: body.passes ?? null, phases: body.phases, quality: body.quality },
{
requestedBy: requested(token),
pendingApproval: pending,
timeLimitS: guard.maxSweepMinutes * 60,
runTimeLimitS: guard.maxRunMinutes * 60,
maxVariants: guard.maxSweepVariants,
},
);
return { id: row.id, state: pending ? "pending_approval" : "queued", variants: count, timeLimitMinutes: guard.maxSweepMinutes };
}
/** Cancel a run or sweep this token asked for. */
export async function ownRun(token: TokenIdentity, id: string) {
const run = await getBenchmark(id);
if (!run) throw new TuningError("not_owner", "No benchmark run with this id.", 404);
if (run.requestedByTokenId !== token.id) throw new TuningError("not_owner", "This run wasn't started by this token; agents only cancel their own runs.", 403);
return run;
}
export async function ownSweep(token: TokenIdentity, id: string) {
const s = await getSweep(id);
if (!s) throw new TuningError("not_owner", "No sweep with this id.", 404);
if (s.sweep.requestedByTokenId !== token.id) throw new TuningError("not_owner", "This sweep wasn't started by this token; agents only cancel their own sweeps.", 403);
return s;
}
const r1 = (v: number | null | undefined) => (v == null ? null : Math.round(v * 10) / 10);
/** The quality eval in short: overall score and per section. */
export function qualityView(q: QualityResult | null | undefined) {
if (!q) return null;
return {
evalSet: q.evalSet,
score: q.score,
sections: Object.fromEntries(q.sections.map((s) => [s.section, s.unsupported ? `n/a (${s.unsupported})` : `${s.passed}/${s.total}`])),
};
}
/** Headline numbers + the setup (section 1 metadata) as key/value. */
function compact(summary: BenchmarkSummary | null, meta: RunMeta | null, quality?: QualityResult | null) {
const h = headline(summary);
return {
...(quality ? { quality: qualityView(quality) } : {}),
headline: {
decodeTps: r1(h.decode),
prefillTps: r1(h.prefill?.tps),
prefillDepth: h.prefill?.depth ?? null,
ttftMs: r1(h.ttftMs),
peakParallelTps: r1(h.peak?.tps),
peakParallelLevel: h.peak?.level ?? null,
},
setup: meta ? Object.fromEntries(metaRows(meta).map((r) => [r.key, r.value])) : null,
};
}
const RUN_NEXT: Record<string, string> = {
pending_approval: "Waiting for the user's approval in Kaname. Don't retry or poll; tell the user and stop.",
queued: "Queued (one benchmark at a time). GET it with ?wait=900 instead of polling.",
running: "Running. GET it with ?wait=900 instead of polling.",
completed: "Done. Compare runs with GET /api/v1/benchmarks/compare?ids=…",
failed: "Failed; see error. Fix the cause before trying again.",
cancelled: "Cancelled or rejected by the user (or by you).",
};
export const runSettled = (state: string) => state !== "queued" && state !== "running";
/** Compact run state: headline numbers, setup, resources; the full summary with `full`. */
export function runView(r: BenchmarkRow, token: TokenIdentity, full = false) {
const res = r.resources;
return {
id: r.id,
kind: r.kind,
state: r.state,
label: r.label,
description: r.description,
deploymentId: r.deploymentId,
deploymentBId: r.deploymentBId,
deployment: r.snapshot.deploymentName,
requestedBy: r.requestedBy,
mine: r.requestedByTokenId === token.id,
settings: r.settings,
phase: r.phase,
error: r.error,
timeLimitMinutes: r.timeLimitS ? Math.round(r.timeLimitS / 60) : null,
startedAt: r.startedAt ? new Date(r.startedAt).toISOString() : null,
finishedAt: r.finishedAt ? new Date(r.finishedAt).toISOString() : null,
...compact(r.summary, r.meta, r.quality),
...(r.kind === "eval" && r.quality && full ? { failed: r.quality.items.filter((i) => !i.pass) } : {}),
...(r.kind === "ab" && r.ab
? {
ab: {
pairs: r.ab.pairs,
verdict: r.ab.decode_tps.verdict,
decodeDiffPct: r1(r.ab.decode_tps.pct_diff),
ciPct: [r1(r.ab.decode_tps.ci_low_pct), r1(r.ab.decode_tps.ci_high_pct)],
significant: r.ab.decode_tps.significant,
setupB: r.metaB ? Object.fromEntries(metaRows(r.metaB).map((x) => [x.key, x.value])) : null,
},
}
: {}),
resources: res
? {
cpuAvgCores: r1(res.containers[0]?.cpuAvg),
ramPeakBytes: res.containers[0]?.memPeakBytes ?? null,
gpus: res.gpus.map((g) => ({ name: g.name, vramPeakMb: g.vramPeakMb, vramTotalMb: g.vramTotalMb, utilAvg: r1(g.utilAvg), powerAvgW: r1(g.powerAvgW), tempPeakC: r1(g.tempPeakC) })),
}
: null,
next: RUN_NEXT[r.state] ?? null,
...(full ? { summary: r.summary } : {}),
};
}
export function sweepView(data: NonNullable<Awaited<ReturnType<typeof getSweep>>>, token: TokenIdentity) {
const s: SweepRow = data.sweep;
return {
id: s.id,
state: s.state,
label: s.label,
baseDeploymentId: s.baseDeploymentId,
params: s.params,
settings: s.settings,
requestedBy: s.requestedBy,
mine: s.requestedByTokenId === token.id,
error: s.error,
timeLimitMinutes: s.timeLimitS ? Math.round(s.timeLimitS / 60) : null,
variants: s.variants.map((v) => {
const run = data.runs.find((r) => r.id === v.runId);
const ev = data.runs.find((r) => r.id === v.evalRunId);
return {
label: v.label,
overrides: v.overrides,
state: v.state,
runId: v.runId ?? null,
evalRunId: v.evalRunId ?? null,
error: v.error ?? null,
...compact(run?.summary ?? null, run?.meta ?? null, ev?.quality ?? null),
};
}),
startedAt: s.startedAt?.toISOString() ?? null,
finishedAt: s.finishedAt?.toISOString() ?? null,
next: s.state === "pending_approval" ? RUN_NEXT.pending_approval : s.state === "queued" || s.state === "running" ? "Running variant by variant. GET it with ?wait=900 instead of polling." : null,
};
}
/** Runs side by side: headline numbers and the setup keys whose values differ. */
export async function compareRuns(ids: string[]) {
const runs = await getBenchmarks(ids);
const rows = runs.map((r) => ({ id: r.id, kind: r.kind, label: r.label ?? r.snapshot.deploymentName, state: r.state, ...compact(r.summary, r.meta, r.quality) }));
const keys = [...new Set(rows.flatMap((r) => Object.keys(r.setup ?? {})))];
const differs = keys.filter((k) => new Set(rows.map((r) => r.setup?.[k] ?? "")).size > 1);
return {
runs: rows.map((r) => ({ ...r, setup: undefined, differs: Object.fromEntries(differs.map((k) => [k, r.setup?.[k] ?? null])) })),
same: Object.fromEntries(keys.filter((k) => !differs.includes(k)).map((k) => [k, rows[0]?.setup?.[k] ?? null])),
note: "Headline: decode t/s (weighted), prefill t/s at the deepest prompt, TTFT p50 ms; quality: the eval score 0–100 (same evalSet only). Differences under ~2 % between separate speed runs are noise; use an A/B for small effects.",
};
}
/** Recent runs, newest first, optionally of one deployment or token. */
export async function listRunsFor(filter: { deploymentId?: string; requestedBy?: string; limit: number }) {
const rows = await db()
.select({ id: benchmarkRuns.id })
.from(benchmarkRuns)
.where(
and(
filter.deploymentId ? or(eq(benchmarkRuns.deploymentId, filter.deploymentId), eq(benchmarkRuns.deploymentBId, filter.deploymentId)) : undefined,
filter.requestedBy ? eq(benchmarkRuns.requestedBy, filter.requestedBy.toLowerCase()) : undefined,
),
)
.orderBy(desc(benchmarkRuns.createdAt))
.limit(filter.limit);
return getBenchmarks(rows.map((r) => r.id));
}
+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 });
+581
View File
@@ -0,0 +1,581 @@
// /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]")));
});
});
describe("quality eval through the API", () => {
it("requests an eval run on the token's own deployment and reads its score", async () => {
const d = await create({ start: false });
await setState(d.body.id, "running");
const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { kind: "eval", deploymentId: d.body.id, sections: ["tools", "retrieval"] } });
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?.kind, "eval");
assert.deepEqual(row?.settings.evalSections, ["tools", "retrieval"]);
await M.db
.db()
.update(M.schema.benchmarkRuns)
.set({
state: "completed",
quality: {
evalSet: "kaname-eval-1",
score: 75,
sections: [
{ section: "tools", passed: 9, total: 12, score: 75, seconds: 20 },
{ section: "retrieval", passed: 0, total: 0, score: null, unsupported: "the context length is unknown", seconds: 0 },
],
items: [{ section: "tools", id: "timer-12", pass: false, detail: "no tool call" }],
config: { temperature: 0, seed: 1, thinking: false, contextTokens: null },
},
})
.where(eq(M.schema.benchmarkRuns.id, r.body.id));
const v = await call(M.run.GET, "/x", { token: hermes, params: { id: r.body.id } });
assert.deepEqual(v.body.quality, { evalSet: "kaname-eval-1", score: 75, sections: { tools: "9/12", retrieval: "n/a (the context length is unknown)" } });
const full = await call(M.run.GET, `/api/v1/benchmarks/${r.body.id}?full=1`, { token: hermes, params: { id: r.body.id } });
assert.equal(full.body.failed[0].id, "timer-12");
});
it("refuses unknown sections, and sweeps can add the eval per variant", async () => {
const d = await create({ start: false });
await setState(d.body.id, "running");
const bad = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { kind: "eval", deploymentId: d.body.id, sections: ["vibes"] } });
assert.equal(bad.status, 400);
await setState(d.body.id, "stopped");
const s = await call(M.sweeps.POST, "/api/v1/sweeps", { token: hermes, body: { baseDeploymentId: d.body.id, quality: true, params: [{ key: "kvCache", values: ["f16", "q8_0"] }] } });
assert.equal(s.status, 201);
const row = await M.db.db().query.benchmarkSweeps.findFirst({ where: eq(M.schema.benchmarkSweeps.id, s.body.id) });
assert.equal(row?.settings.quality, true);
});
});
+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);
+2
View File
@@ -70,6 +70,8 @@ export function configChips(s: BenchmarkSnapshot): string[] {
}
export function describeSettings(st: BenchmarkSettings): string {
// A quality eval's settings carry its sections (empty: all).
if (st.evalSections) return `quality eval · ${st.evalSections.length ? st.evalSections.join(", ") : "all sections"}`;
const passes = st.passes ?? (st.quick ? 5 : 20);
const phases = st.phases.length ? st.phases.join(", ") : "all phases";
return `${st.quick && st.passes == null ? "quick, " : ""}${passes} passes · ${phases}`;
+58 -14
View File
@@ -5,7 +5,7 @@ import { z } from "zod";
import { runDir } from "@/lib/benchmark-paths";
import { deploymentSnapshot } from "@/lib/benchmark-snapshot";
import { db } from "@/lib/db/client";
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns } from "@/lib/db/schema";
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, QUALITY_SECTIONS } from "@/lib/db/schema";
export class BenchmarkError extends Error {
constructor(
@@ -35,6 +35,10 @@ export const BenchmarkBody = z.object({
maxPairs: z.number().int().min(12).max(2000).nullable().optional(),
/** Set by sweeps. */
sweepId: z.string().nullable().optional(),
/** "eval": the quality eval instead of BetterBench (default: run, or ab with deploymentBId). */
kind: z.enum(["run", "ab", "eval"]).optional(),
/** eval: which sections (empty: all). */
evalSections: z.array(z.enum(QUALITY_SECTIONS)).max(3).optional(),
});
export type BenchmarkInput = z.infer<typeof BenchmarkBody>;
@@ -50,8 +54,13 @@ 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) {
const ab = !!input.deploymentBId;
/** 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 kind = input.kind ?? (input.deploymentBId ? "ab" : "run");
const ab = kind === "ab";
if (ab && !input.deploymentBId) throw new BenchmarkError("invalid", "An A/B needs a second deployment.", 400);
const a = await snapshotOf(input.deploymentId, ab ? "Deployment A" : "The deployment");
const b = ab ? await snapshotOf(input.deploymentBId!, "Deployment B") : null;
if (b) {
@@ -63,22 +72,33 @@ export async function createBenchmark(input: BenchmarkInput) {
const [row] = await db()
.insert(benchmarkRuns)
.values({
kind: ab ? "ab" : "run",
kind,
deploymentId: a.id,
deploymentBId: b?.id ?? null,
modelId: a.modelId,
label: input.label || null,
description: input.description || null,
settings: {
quick: input.quick,
passes: input.passes ?? null,
warmup: input.warmup ?? null,
phases: input.phases,
...(ab ? { mdePct: input.mdePct ?? null, maxPairs: input.maxPairs ?? null } : {}),
},
settings:
kind === "eval"
? { quick: false, passes: null, warmup: null, phases: [], evalSections: input.evalSections ?? [] }
: {
quick: input.quick,
passes: input.passes ?? null,
warmup: input.warmup ?? null,
phases: input.phases,
...(ab ? { mdePct: input.mdePct ?? null, maxPairs: input.maxPairs ?? null } : {}),
},
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;
@@ -105,7 +125,11 @@ const listColumns = {
snapshotB: benchmarkRuns.snapshotB,
ab: benchmarkRuns.ab,
resources: benchmarkRuns.resources,
quality: benchmarkRuns.quality,
sweepId: benchmarkRuns.sweepId,
requestedBy: benchmarkRuns.requestedBy,
requestedByTokenId: benchmarkRuns.requestedByTokenId,
timeLimitS: benchmarkRuns.timeLimitS,
meta: benchmarkRuns.meta,
metaB: benchmarkRuns.metaB,
system: benchmarkRuns.system,
@@ -139,17 +163,37 @@ 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));
}
}
/** 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> = {};
+72 -5
View File
@@ -601,6 +601,13 @@ export const deployments = sqliteTable("deployments", {
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(),
});
@@ -637,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(
@@ -657,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;
@@ -676,9 +703,34 @@ export type BenchmarkSettings = {
/** A/B: target minimum detectable effect in % (BetterBench --mde, default 1) and pair ceiling. */
mdePct?: number | null;
maxPairs?: number | null;
/** eval: which sections (empty: all). Sweeps: also run the quality eval for each variant. */
evalSections?: QualitySection[];
quality?: boolean;
};
export const BENCHMARK_KINDS = ["run", "ab"] as const;
export const QUALITY_SECTIONS = ["tools", "coding", "retrieval"] as const;
export type QualitySection = (typeof QUALITY_SECTIONS)[number];
/** A quality eval's result: pass rates per section and the overall score (their mean), 0–100. */
export type QualityResult = {
/** The eval set's version; only results of the same version are comparable. */
evalSet: string;
score: number | null;
sections: {
section: QualitySection;
passed: number;
total: number;
score: number | null;
/** Why the section couldn't run (e.g. the server doesn't do tool calls); then it doesn't count. */
unsupported?: string | null;
seconds: number;
}[];
items: { section: QualitySection; id: string; pass: boolean; detail?: string | null }[];
config: { temperature: number; seed: number; thinking: boolean; contextTokens: number | null };
};
/** run: BetterBench; ab: paired A/B; eval: Kaname's quality eval (tool calling, coding, retrieval). */
export const BENCHMARK_KINDS = ["run", "ab", "eval"] as const;
export type BenchmarkKind = (typeof BENCHMARK_KINDS)[number];
/** One side of a paired comparison, as BetterBench's paired_compare reports it. */
@@ -918,8 +970,15 @@ export const benchmarkRuns = sqliteTable(
snapshotB: text("snapshot_b", { mode: "json" }).$type<BenchmarkSnapshot>(),
ab: text("ab", { mode: "json" }).$type<AbSummary>(),
resources: text("resources", { mode: "json" }).$type<ResourceStats>(),
/** kind "eval": the quality eval's result. */
quality: text("quality", { mode: "json" }).$type<QualityResult>(),
/** 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>(),
@@ -983,7 +1042,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). */
@@ -994,9 +1053,11 @@ export type SweepVariant = {
/** Option overrides for this variant, e.g. { contextSize: 8192, cacheTypeK: "q8_0", cacheTypeV: "q8_0" }. */
overrides: Record<string, unknown>;
label: string;
state: "pending" | "deploying" | "benchmarking" | "done" | "failed" | "skipped";
state: "pending" | "deploying" | "benchmarking" | "evaluating" | "done" | "failed" | "skipped";
deploymentId?: string | null;
runId?: string | null;
/** The quality eval run of this variant (sweeps with quality: true). */
evalRunId?: string | null;
error?: string | null;
};
@@ -1016,5 +1077,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(),
});
+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,
+12
View File
@@ -0,0 +1,12 @@
// Labels for the quality eval's sections. Pure and small: safe for client components (the eval set
// itself stays in src/lib/quality.ts).
import type { QualitySection } from "@/lib/db/schema";
export const SECTION_LABEL: Record<QualitySection, string> = { tools: "Tool calling", coding: "Coding", retrieval: "Long-context retrieval" };
export const SECTION_HINT: Record<QualitySection, string> = {
tools: "12 requests: valid JSON, the right function and arguments",
coding: "8 short Python functions, checked by unit tests in a sandbox",
retrieval: "a code hidden at 3 depths in 3 text lengths up to the context size",
};
+135
View File
@@ -0,0 +1,135 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { describe, it } from "node:test";
import { argMatches, buildHaystack, EVAL_SET, extractCode, prng, retrievalCases, scoreNeedle, scoreToolCall, summarize, testProgram, toolDefs } from "./quality";
describe("eval set", () => {
it("tool items only use defined tools and expect one of their own", () => {
for (const item of EVAL_SET.tools.items) {
for (const t of item.tools) assert.ok(EVAL_SET.tools.tools[t], `${item.id}: unknown tool ${t}`);
assert.ok(item.tools.includes(item.expect.name), `${item.id}: expects ${item.expect.name}, not offered`);
const params = EVAL_SET.tools.tools[item.expect.name].parameters as { properties: Record<string, unknown> };
for (const k of Object.keys(item.expect.args)) assert.ok(params.properties[k], `${item.id}: ${k} isn't a parameter`);
}
assert.equal(EVAL_SET.tools.items.length, 12);
assert.equal(toolDefs(EVAL_SET.tools.items[0])[0].type, "function");
});
it("has unique ids", () => {
const ids = [...EVAL_SET.tools.items, ...EVAL_SET.coding.items].map((i) => i.id);
assert.equal(new Set(ids).size, ids.length);
});
// Reference solutions: the eval's own tests must accept a correct answer.
const python = ["python3", "python"].find((p) => spawnSync(p, ["--version"]).status === 0);
const REFERENCE: Record<string, string> = {
"is-palindrome": "def is_palindrome(s):\n t = [c.lower() for c in s if c.isalnum()]\n return t == t[::-1]",
fizzbuzz:
"def fizzbuzz(n):\n return ['FizzBuzz' if i % 15 == 0 else 'Fizz' if i % 3 == 0 else 'Buzz' if i % 5 == 0 else str(i) for i in range(1, n + 1)]",
"merge-intervals":
"def merge_intervals(intervals):\n out = []\n for s, e in sorted(intervals):\n if out and s <= out[-1][1]:\n out[-1][1] = max(out[-1][1], e)\n else:\n out.append([s, e])\n return out",
"word-count":
"import re\ndef word_count(text):\n d = {}\n for w in re.findall('[A-Za-z]+', text):\n d[w.lower()] = d.get(w.lower(), 0) + 1\n return d",
"roman-to-int":
"def roman_to_int(s):\n v = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}\n n = 0\n for i, c in enumerate(s):\n n += -v[c] if i + 1 < len(s) and v[s[i + 1]] > v[c] else v[c]\n return n",
flatten: "def flatten(nested):\n out = []\n for x in nested:\n out.extend(flatten(x) if isinstance(x, list) else [x])\n return out",
"second-largest": "def second_largest(nums):\n u = sorted(set(nums))\n return u[-2] if len(u) > 1 else None",
"rle-encode":
"from itertools import groupby\ndef rle_encode(s):\n return ''.join(f'{k}{len(list(g))}' for k, g in groupby(s))",
};
it("coding tests pass for a correct solution and fail for a wrong one", { skip: !python && "no python here" }, () => {
for (const item of EVAL_SET.coding.items) {
const ok = spawnSync(python!, ["-I", "-c", testProgram(REFERENCE[item.id], item.tests)], { encoding: "utf8" });
assert.equal(ok.status, 0, `${item.id}: ${ok.stderr}`);
assert.match(ok.stdout, /KANAME-OK/);
const fname = item.prompt.split("(")[0];
const bad = spawnSync(python!, ["-I", "-c", testProgram(`def ${fname}(*a, **k):\n return None`, item.tests)], { encoding: "utf8" });
assert.notEqual(bad.status, 0, `${item.id}: a wrong answer passed`);
}
});
});
describe("tool call scoring", () => {
const expect = EVAL_SET.tools.items.find((i) => i.id === "calendar-budget")!.expect;
const call = (args: unknown, name = "create_calendar_event") => [{ name, arguments: typeof args === "string" ? args : JSON.stringify(args) }];
it("accepts the right function with matching arguments (case-insensitive, extra ones fine)", () => {
const r = scoreToolCall(call({ title: "Budget Review", date: "2026-11-03", time: "14:30", duration_minutes: 45, location: "x" }), expect);
assert.equal(r.pass, true);
assert.equal(scoreToolCall(call({ title: "budget review meeting", date: "2026-11-03", time: "14:30", duration_minutes: "45" }), expect).pass, true);
});
it("refuses invalid JSON, the wrong function, wrong or missing arguments, several calls, none", () => {
assert.match(scoreToolCall(call("{title: 'x'"), expect).detail, /invalid JSON/);
assert.match(scoreToolCall(call("[1]"), expect).detail, /JSON object/);
assert.match(scoreToolCall(call({}, "set_timer"), expect).detail, /called set_timer/);
assert.match(scoreToolCall(call({ title: "Budget review", date: "2026-11-04", time: "14:30", duration_minutes: 45 }), expect).detail, /wrong date/);
assert.match(scoreToolCall(call({ title: "Budget review", date: "2026-11-03", time: "14:30" }), expect).detail, /wrong duration_minutes=undefined/);
assert.match(scoreToolCall([...call({}), ...call({})], expect).detail, /2 tool calls/);
assert.equal(scoreToolCall([], expect).pass, false);
assert.equal(scoreToolCall(null, expect).pass, false);
});
it("matches the argument rules", () => {
assert.ok(argMatches("PDF", { oneOf: ["pdf", ".pdf"] }));
assert.ok(argMatches(" 17 * 23 ", { matches: "^\\s*17\\s*[*x×]\\s*23\\s*$" }));
assert.ok(!argMatches("17+23", { matches: "^\\s*17\\s*[*x×]\\s*23\\s*$" }));
assert.ok(argMatches(250.0, 250));
assert.ok(!argMatches(null, "x"));
});
});
describe("code extraction", () => {
it("takes the last python block, or bare code", () => {
assert.equal(extractCode("Here:\n```python\ndef a(): pass\n```\nand\n```py\ndef b(): pass\n```"), "def b(): pass");
assert.equal(extractCode("```\ndef c(): pass\n```"), "def c(): pass");
assert.equal(extractCode("def d():\n return 1"), "def d():\n return 1");
assert.equal(extractCode("I can't do that."), null);
});
});
describe("long-context retrieval", () => {
it("plans lengths × positions within the context, deterministic codes", () => {
const c = retrievalCases(32768);
assert.equal(c.length, 9);
assert.ok(c.every((x) => x.targetTokens <= 32768 - EVAL_SET.retrieval.reserveTokens));
assert.deepEqual(retrievalCases(32768), c);
assert.ok(c.every((x) => /^\d{6}$/.test(x.code)));
assert.equal(retrievalCases(600).length, 0, "too short for any haystack");
assert.equal(retrievalCases(1200).length, 6, "the 25 % length is under 256 tokens");
});
it("puts the needle at its depth and the question at the end", () => {
const [first, , last] = retrievalCases(16384);
for (const c of [first, last]) {
const text = buildHaystack(c, 4);
const at = text.indexOf(c.code) / text.length;
assert.ok(Math.abs(at - c.position) < 0.05, `needle at ${at}, wanted ${c.position}`);
assert.ok(text.trimEnd().endsWith("only."));
assert.ok(Math.abs(text.length / 4 - c.targetTokens) / c.targetTokens < 0.06);
}
assert.equal(buildHaystack(first, 4), buildHaystack(first, 4));
});
it("scores the answer by the six digits", () => {
const c = retrievalCases(8192)[0];
assert.equal(scoreNeedle(`The code is ${c.code}.`, c).pass, true);
assert.equal(scoreNeedle("123456", { ...c, code: "654321" }).pass, false);
const r = prng(1);
assert.equal(prng(1)(), r());
});
});
describe("score", () => {
it("averages the sections that ran", () => {
const s = summarize([
{ section: "tools", passed: 9, total: 12, score: null, seconds: 10 },
{ section: "coding", passed: 4, total: 8, score: null, seconds: 30 },
{ section: "retrieval", passed: 0, total: 0, score: null, unsupported: "context unknown", seconds: 0 },
]);
assert.equal(s.score, 62.5);
assert.deepEqual(s.sections.map((x) => x.score), [75, 50, null]);
assert.equal(summarize([]).score, null);
});
});
+175
View File
@@ -0,0 +1,175 @@
// The quality eval: a small, deterministic check of what a deployment produces (not how fast), so
// launch options that change the output (quant, KV cache type, context, sampling bugs in a build)
// show up next to the speed numbers. Pure: the eval set, prompt building and scoring; the worker
// (src/worker/quality.ts) talks to the server and the code sandbox.
import type { QualityResult } from "@/lib/db/schema";
import coding from "@/evals/v1/coding.json";
import retrieval from "@/evals/v1/retrieval.json";
import tools from "@/evals/v1/tools.json";
/** Bump with any change to the eval set or the scoring: results are only comparable within a version. */
export const EVAL_SET_VERSION = "kaname-eval-1";
export const EVAL_SEED = 1;
export type ArgRule = string | number | boolean | { contains: string } | { oneOf: (string | number)[] } | { matches: string };
export type ToolItem = { id: string; tools: string[]; prompt: string; expect: { name: string; args: Record<string, ArgRule> } };
export type CodingItem = { id: string; prompt: string; tests: string[] };
export const EVAL_SET = {
version: EVAL_SET_VERSION,
tools: tools as unknown as { tools: Record<string, { description: string; parameters: Record<string, unknown> }>; items: ToolItem[] },
coding: coding as { instructions: string; items: CodingItem[] },
retrieval: retrieval as {
lengths: number[];
positions: number[];
reserveTokens: number;
seed: number;
needle: string;
question: string;
colors: string[];
filler: string[];
},
};
// --- tool calling ---------------------------------------------------------------------------
/** The OpenAI `tools` array for an item. */
export function toolDefs(item: ToolItem) {
return item.tools.map((name) => ({ type: "function" as const, function: { name, ...EVAL_SET.tools.tools[name] } }));
}
const norm = (v: unknown) => (typeof v === "string" ? v.trim().toLowerCase() : v);
/** One argument against its rule: strings case-insensitively, numbers by value. */
export function argMatches(value: unknown, rule: ArgRule): boolean {
if (value === undefined || value === null) return false;
if (typeof rule === "object") {
if ("contains" in rule) return typeof value === "string" && value.toLowerCase().includes(rule.contains.toLowerCase());
if ("oneOf" in rule) return rule.oneOf.some((r) => argMatches(value, r));
if ("matches" in rule) return typeof value === "string" && new RegExp(rule.matches, "i").test(value);
}
if (typeof rule === "number") return Number(value) === rule;
return norm(value) === norm(rule);
}
export type ToolCall = { name: string; arguments: string };
/**
* A tool call is right when there is exactly one, its arguments are valid JSON, the function is the
* expected one and every expected argument matches (extra arguments are fine).
*/
export function scoreToolCall(calls: ToolCall[] | null | undefined, expect: ToolItem["expect"]): { pass: boolean; detail: string } {
if (!calls || calls.length === 0) return { pass: false, detail: "no tool call" };
if (calls.length > 1) return { pass: false, detail: `${calls.length} tool calls, expected one` };
const [c] = calls;
let args: Record<string, unknown>;
try {
const parsed = JSON.parse(c.arguments || "{}");
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { pass: false, detail: "arguments aren't a JSON object" };
args = parsed as Record<string, unknown>;
} catch {
return { pass: false, detail: `invalid JSON arguments: ${c.arguments.slice(0, 120)}` };
}
if (c.name !== expect.name) return { pass: false, detail: `called ${c.name}, expected ${expect.name}` };
const wrong = Object.entries(expect.args).filter(([k, rule]) => !argMatches(args[k], rule));
if (wrong.length) return { pass: false, detail: `wrong ${wrong.map(([k]) => `${k}=${JSON.stringify(args[k])}`).join(", ")}` };
return { pass: true, detail: `${c.name}(${JSON.stringify(args)})` };
}
// --- coding -------------------------------------------------------------------------------
/** The last ```python block of a reply (or the only fenced block); null without one. */
export function extractCode(reply: string): string | null {
const blocks = [...reply.matchAll(/```(?:python|py)?[ \t]*\r?\n([\s\S]*?)```/gi)].map((m) => m[1]);
if (blocks.length) return blocks[blocks.length - 1].trim() || null;
// Some models answer with bare code.
return /^\s*(def|import|from)\s/m.test(reply) ? reply.trim() : null;
}
/** The program the sandbox runs: the model's code, then the tests; prints OK when all pass. */
export function testProgram(code: string, tests: string[]): string {
return `${code}\n\n# --- tests ---\n${tests.join("\n")}\nprint("KANAME-OK")\n`;
}
// --- long-context retrieval ---------------------------------------------------------------
/** A small, seeded PRNG (mulberry32): the haystacks are the same every run. */
export function prng(seed: number) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export type NeedleCase = { id: string; targetTokens: number; position: number; color: string; code: string };
/** The cases for a context of `contextTokens`: each length × each needle position, deduplicated. */
export function retrievalCases(contextTokens: number): NeedleCase[] {
const r = EVAL_SET.retrieval;
const usable = Math.max(0, contextTokens - r.reserveTokens);
const rand = prng(r.seed);
const out: NeedleCase[] = [];
const seen = new Set<number>();
let i = 0;
for (const len of r.lengths) {
const target = Math.floor(usable * len);
if (target < 256 || seen.has(target)) continue;
seen.add(target);
for (const position of r.positions) {
out.push({
id: `${Math.round(target / 100) / 10}k@${Math.round(position * 100)}%`,
targetTokens: target,
position,
color: r.colors[i++ % r.colors.length],
code: String(100000 + Math.floor(rand() * 900000)),
});
}
}
return out;
}
/**
* The haystack for a case: filler sentences in a seeded order up to about `targetTokens` (measured
* with the server's own tokenizer as characters per token), the needle at `position`, then the
* question.
*/
export function buildHaystack(c: NeedleCase, charsPerToken: number): string {
const r = EVAL_SET.retrieval;
const rand = prng(r.seed + c.targetTokens);
const targetChars = Math.floor(c.targetTokens * charsPerToken * 0.97);
const parts: string[] = [];
let len = 0;
while (len < targetChars) {
const s = r.filler[Math.floor(rand() * r.filler.length)];
parts.push(s);
len += s.length + 1;
}
const needle = r.needle.replace("{color}", c.color).replace("{code}", c.code);
parts.splice(Math.round(parts.length * c.position), 0, needle);
return `${parts.join(" ")}\n\n${r.question.replace("{color}", c.color)}`;
}
/** Did the answer give the code (the six digits, anywhere)? */
export function scoreNeedle(answer: string, c: NeedleCase): { pass: boolean; detail: string } {
const found: string[] = answer.match(/\d{6}/g) ?? [];
return found.includes(c.code) ? { pass: true, detail: c.code } : { pass: false, detail: `expected ${c.code}, got ${JSON.stringify(answer.trim().slice(0, 80))}` };
}
// --- score --------------------------------------------------------------------------------
/** Section pass rates and the overall score (mean of the sections that could run), 0–100. */
export function summarize(
sections: QualityResult["sections"],
): Pick<QualityResult, "score" | "sections"> {
const counted = sections.filter((s) => !s.unsupported && s.total > 0);
const withScore = sections.map((s) => ({ ...s, score: !s.unsupported && s.total > 0 ? Math.round((s.passed / s.total) * 1000) / 10 : null }));
const score = counted.length ? Math.round((counted.reduce((n, s) => n + s.passed / s.total, 0) / counted.length) * 1000) / 10 : null;
return { score, sections: withScore };
}
export { SECTION_LABEL } from "@/lib/quality-view";
+30
View File
@@ -3,6 +3,7 @@ import { eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
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";
@@ -138,3 +139,32 @@ export async function saveHardwareOverrides(input: unknown): Promise<HardwareOve
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;
}
+43 -7
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,
) {
@@ -28,10 +28,15 @@ export const SweepBody = z.object({
quick: z.boolean().default(true),
passes: z.number().int().min(1).max(200).nullable().optional(),
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
/** Also run the quality eval on each variant (after its speed run). */
quality: z.boolean().default(false),
});
/** 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 +67,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({
@@ -70,8 +78,17 @@ export async function createSweep(input: z.infer<typeof SweepBody>) {
// The variants' deployments must not publish ports or require a second copy of the base's port.
base: { name: base.name, runtimeId: base.runtimeId, modelId: base.modelId, options: base.options, cpus: base.cpus, memoryMb: base.memoryMb },
params: input.params,
settings: { quick: input.quick, passes: input.passes ?? null, warmup: null, phases: input.phases },
settings: { quick: input.quick, passes: input.passes ?? null, warmup: null, phases: input.phases, quality: input.quality },
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;
@@ -86,10 +103,19 @@ export async function listSweeps(): Promise<SweepRow[]> {
export async function getSweep(id: string) {
const sweep = await db().query.benchmarkSweeps.findFirst({ where: eq(benchmarkSweeps.id, id) });
if (!sweep) return null;
const runIds = sweep.variants.map((v) => v.runId).filter((x): x is string => !!x);
const runIds = sweep.variants.flatMap((v) => [v.runId, v.evalRunId]).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, meta: benchmarkRuns.meta })
.select({
id: benchmarkRuns.id,
state: benchmarkRuns.state,
summary: benchmarkRuns.summary,
resources: benchmarkRuns.resources,
phase: benchmarkRuns.phase,
error: benchmarkRuns.error,
meta: benchmarkRuns.meta,
quality: benchmarkRuns.quality,
})
.from(benchmarkRuns)
.where(inArray(benchmarkRuns.id, runIds))
: [];
@@ -99,19 +125,29 @@ 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) });
if (!s) throw new SweepRequestError("not_found", "Sweep not found.", 404);
if (s.state === "running" || s.state === "queued") throw new SweepRequestError("busy", "Cancel the sweep first.", 409);
const runIds = s.variants.map((v) => v.runId).filter((x): x is string => !!x);
const runIds = s.variants.flatMap((v) => [v.runId, v.evalRunId]).filter((x): x is string => !!x);
if (runIds.length) {
await db().delete(benchmarkLogs).where(inArray(benchmarkLogs.runId, runIds));
await db().delete(benchmarkRuns).where(inArray(benchmarkRuns.id, runIds));
+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 };
}
+116 -16
View File
@@ -6,11 +6,27 @@ 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, type RunMeta, runtimes } from "@/lib/db/schema";
import {
apiKeys,
type BenchmarkKind,
benchmarkLogs,
benchmarkRuns,
type BenchmarkSummary,
deployments,
type LogStream,
QUALITY_SECTIONS,
type QualityResult,
type QualitySection,
type RunMeta,
runtimes,
type SystemSummary,
} from "@/lib/db/schema";
import { EVAL_SEED, EVAL_SET_VERSION, SECTION_LABEL } from "@/lib/quality";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { coreEnv } from "@/lib/env";
import { abSummary } from "./ab-summary";
@@ -20,13 +36,16 @@ import { log } from "./log";
import { normalizePciAddress } from "./hardware";
import { errorCauses } from "./log-causes";
import { type GpuTargets, ResourceSampler } from "./resources";
import { runQualityEval } from "./quality";
import { docker, workerImage } from "./runtimes";
type Current = {
runId: string;
kind: "run" | "ab";
kind: BenchmarkKind;
deploymentIds: string[];
child: ChildProcess;
/** BetterBench (runs, A/B); null for a quality eval, which runs in-process and stops via `abort`. */
child: ChildProcess | null;
abort: AbortController | null;
sampler: ResourceSampler | null;
/** Recorded at the start; the PCIe links are replaced by the ones seen under load at the end. */
meta: RunMeta | null;
@@ -203,6 +222,7 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
const setup = await runSetup([a.id, b?.id ?? null]);
const [meta, metaB] = setup.metas;
const metaNotesA = meta ? metaNotes(meta, setup.system, run.description) : {};
if (run.kind === "eval") return startEval(run, a, keys, meta, setup.system);
const args =
run.kind === "ab" && b
? abArgs({
@@ -277,6 +297,7 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
kind: run.kind,
deploymentIds: [a.id, ...(b ? [b.id] : [])],
child,
abort: null,
sampler,
meta,
metaB,
@@ -295,13 +316,8 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
log.info(`benchmark ${run.id}: started (${run.kind}) for ${s.deploymentName}`);
}
async function done(cur: Current, code: number | null, signal: NodeJS.Signals | null) {
const id = cur.runId;
for (const stream of ["stdout", "stderr"] as const) {
const rest = partial.get(`${id}:${stream}`);
if (rest?.trim()) addLog(id, stream, rest, cur.secrets);
partial.delete(`${id}:${stream}`);
}
/** Stop the resource sampler; record the PCIe links seen under load in the run's meta. */
async function stopSampling(cur: Current) {
const resources = (await cur.sampler?.stop().catch(() => null)) ?? null;
if (current === cur) current = null;
if (resources?.links) {
@@ -309,9 +325,82 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
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)}`));
.where(eq(benchmarkRuns.id, cur.runId))
.catch((err) => log.warn(`benchmark ${cur.runId}: link update failed: ${message(err)}`));
}
return resources;
}
/** Kaname's quality eval: in-process against the deployment, coding answers in the sandbox. */
async function startEval(run: typeof benchmarkRuns.$inferSelect, a: Target, keys: string[], meta: RunMeta | null, system: SystemSummary) {
const s = run.snapshot;
const sections = run.settings.evalSections?.length ? run.settings.evalSections : [...QUALITY_SECTIONS];
const dep = await db().query.deployments.findFirst({ columns: { engineInfo: true, options: true }, where: eq(deployments.id, a.id) });
const contextTokens = dep?.engineInfo?.contextSize ?? dep?.options.contextSize ?? s.options.contextSize ?? null;
addLog(run.id, "system", `Quality eval ${EVAL_SET_VERSION} of ${s.deploymentName} (${s.repoId} on ${s.runtimeName}): ${sections.join(", ")}; greedy, seed ${EVAL_SEED}`);
await db().update(benchmarkRuns).set({ state: "running", startedAt: new Date(), error: null, phase: null, meta, system }).where(eq(benchmarkRuns.id, run.id));
const c = docker();
const sampler = c ? new ResourceSampler(c, [{ side: "a" as const, containerId: a.containerId }], await gpuTargets([meta, null])) : null;
await sampler?.start().catch((err) => log.warn(`resource sampling failed: ${message(err)}`));
const cur: Current = {
runId: run.id,
kind: "eval",
deploymentIds: [a.id],
child: null,
abort: new AbortController(),
sampler,
meta,
metaB: null,
maxPairs: null,
cancelled: false,
lost: null,
secrets: keys,
};
current = cur;
log.info(`benchmark ${run.id}: quality eval started for ${s.deploymentName}`);
const onLine = (line: string) => {
addLog(run.id, "stdout", line, keys);
const m = line.match(/^(tools|coding|retrieval): starting$/);
if (m) void db().update(benchmarkRuns).set({ phase: `Quality: ${SECTION_LABEL[m[1] as QualitySection]}` }).where(eq(benchmarkRuns.id, run.id)).then(() => {}, () => {});
};
runQualityEval(
{ base: `http://${a.containerName}:${ENGINE_PORT[a.engine]}`, model: s.repoId, engine: a.engine, apiKey: keys[0] ?? null, contextTokens },
{ sections, signal: cur.abort!.signal, log: onLine, docker: c, sandboxImage: workerImage() },
).then(
(q) => doneEval(cur, q, null),
(err) => doneEval(cur, null, err),
);
}
async function doneEval(cur: Current, quality: QualityResult | null, err: unknown) {
const id = cur.runId;
const resources = await stopSampling(cur);
if (cur.cancelled) {
addLog(id, "system", "Cancelled.");
await finish(id, { state: "cancelled", quality, resources });
} else if (cur.lost) {
addLog(id, "system", cur.lost);
await finish(id, { state: "failed", error: cur.lost, quality, resources });
} else if (err || !quality) {
await finish(id, { state: "failed", error: `The quality eval failed: ${message(err)}`, resources });
} else {
addLog(id, "system", `Done: score ${quality.score ?? "–"} (${quality.sections.map((x) => `${x.section} ${x.unsupported ? "n/a" : `${x.passed}/${x.total}`}`).join(", ")}).`);
await finish(id, { state: "completed", quality, resources });
}
tails.delete(id);
await flushBenchmarkLogs().catch(() => {});
log.info(`benchmark ${id}: quality eval ${cur.cancelled ? "cancelled" : cur.lost || err ? "failed" : `done, score ${quality?.score}`}`);
}
async function done(cur: Current, code: number | null, signal: NodeJS.Signals | null) {
const id = cur.runId;
for (const stream of ["stdout", "stderr"] as const) {
const rest = partial.get(`${id}:${stream}`);
if (rest?.trim()) addLog(id, stream, rest, cur.secrets);
partial.delete(`${id}:${stream}`);
}
const resources = await stopSampling(cur);
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)));
@@ -356,9 +445,11 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
}
function stop(cur: Current) {
if (cur.child.exitCode !== null) return;
cur.child.kill("SIGTERM");
setTimeout(() => cur.child.exitCode === null && cur.child.kill("SIGKILL"), 10_000).unref();
const child = cur.child;
if (!child) return void cur.abort?.abort();
if (child.exitCode !== null) return;
child.kill("SIGTERM");
setTimeout(() => child.exitCode === null && child.kill("SIGKILL"), 10_000).unref();
}
/** Start the next queued run, stop the current one on cancel or when its deployment goes away. */
@@ -366,12 +457,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") {
+14 -3
View File
@@ -20,11 +20,14 @@ import { escapeGlob } from "@/lib/selection";
import {
bytesOnDisk,
type ExpectedFile,
type FileProgress,
listIncomplete,
fileSize,
modelDir,
removeLocalFile,
removeStaleIncomplete,
steadyProgress,
xetFor,
} from "./hf-layout";
import { JobLog } from "./job-log";
import { log } from "./log";
@@ -248,6 +251,12 @@ export class DownloadRunner implements Runner {
expected: ExpectedFile[],
): Promise<{ code: number | null; signal: NodeJS.Signals | null; error?: string }> {
const env = coreEnv();
const xet = xetFor(expected, env.HF_HUB_DISABLE_XET);
if (xet.forcedBy.length) {
this.jobLog.system(
`Using Xet for this download: ${xet.forcedBy.slice(0, 3).join(", ")}${xet.forcedBy.length > 3 ? ", …" : ""} is over 50 GB, which hf only downloads with Xet (progress grows in bursts).`,
);
}
const args = [
"download",
this.model.repoId,
@@ -264,7 +273,7 @@ export class DownloadRunner implements Runner {
if (v !== undefined) childEnv[k] = v;
}
Object.assign(childEnv, {
HF_HUB_DISABLE_XET: env.HF_HUB_DISABLE_XET ? "1" : "0",
HF_HUB_DISABLE_XET: xet.useXet ? "0" : "1",
HF_HUB_DISABLE_PROGRESS_BARS: "1",
HF_HUB_DISABLE_TELEMETRY: "1",
NO_COLOR: "1",
@@ -275,7 +284,7 @@ export class DownloadRunner implements Runner {
this.jobLog.system(
`$ hf download ${this.model.repoId} --revision ${this.job.targetSha} --local-dir ${dir} ` +
`(${expected.length} --include pattern(s); xet ${env.HF_HUB_DISABLE_XET ? "off" : "on"}; token ${env.HF_TOKEN ? "set" : "not set"})`,
`(${expected.length} --include pattern(s); xet ${xet.useXet ? "on" : "off"}; token ${env.HF_TOKEN ? "set" : "not set"})`,
);
return new Promise((resolve) => {
@@ -311,11 +320,13 @@ export class DownloadRunner implements Runner {
// Progress from bytes on disk, written to the DB once per second.
const speed = new SpeedMeter();
let busy = false;
let last: FileProgress[] | null = null;
const timer = setInterval(async () => {
if (busy) return;
busy = true;
try {
const progress = await this.sample(dir, expected);
const progress = steadyProgress(last, await this.sample(dir, expected));
last = progress;
const doneBytes = progress.reduce((s, p) => s + p.done, 0);
speed.add(Date.now(), doneBytes);
await this.writeProgress(progress, doneBytes, speed);
+45 -14
View File
@@ -61,24 +61,41 @@ export type IncompleteFile = { path: string; etag: string | null; size: number }
/** All partial files under the local dir's download cache. */
export async function listIncomplete(dir: string): Promise<IncompleteFile[]> {
const root = join(dir, DOWNLOAD_DIR);
let entries;
try {
entries = await readdir(root, { recursive: true, withFileTypes: true });
} catch {
return [];
}
const out: IncompleteFile[] = [];
for (const e of entries) {
if (!e.isFile() || !e.name.endsWith(".incomplete")) continue;
const full = join(e.parentPath, e.name);
const size = await fileSize(full);
if (size == null) continue; // finished and moved between readdir and stat
out.push({ path: full, etag: etagFromIncompleteName(e.name), size });
}
// Walked by hand: readdir's `recursive` fails as a whole when hf removes a folder mid-walk,
// which read as "nothing downloaded" for that sample.
const walk = async (path: string) => {
let entries;
try {
entries = await readdir(path, { withFileTypes: true });
} catch {
return;
}
for (const e of entries) {
const full = join(path, e.name);
if (e.isDirectory()) await walk(full);
if (!e.isFile() || !e.name.endsWith(".incomplete")) continue;
const size = await fileSize(full);
if (size == null) continue; // finished and moved between readdir and stat
out.push({ path: full, etag: etagFromIncompleteName(e.name), size });
}
};
await walk(join(dir, DOWNLOAD_DIR));
return out;
}
export type FileProgress = { done: number; complete: boolean };
/**
* Progress that never goes backwards within one run. A sample can miss a partial file that is
* still being written (a folder renamed mid-walk, a stale size from a network share), and showing
* 0 B for a second is wrong; hf doesn't restart a file within a run.
*/
export function steadyProgress(prev: FileProgress[] | null, next: FileProgress[]): FileProgress[] {
if (!prev) return next;
return next.map((p, i) => (p.complete || !prev[i] ? p : { done: Math.max(p.done, prev[i].done), complete: false }));
}
/** Delete leftover partial files from earlier runs. Only call while no hf process uses the dir. */
export async function removeStaleIncomplete(dir: string): Promise<{ count: number; bytes: number }> {
const files = await listIncomplete(dir);
@@ -137,3 +154,17 @@ export async function listLocalFiles(dir: string): Promise<{ path: string; size:
}
return out.sort((a, b) => a.path.localeCompare(b.path));
}
/** huggingface_hub's MAX_HTTP_DOWNLOAD_SIZE (2.1.1): larger files can only come over Xet. */
export const MAX_HTTP_DOWNLOAD_BYTES = 50 * 1000 * 1000 * 1000;
/**
* Whether hf may use Xet for these files. Kaname turns Xet off for steady progress, but hf refuses
* files over 50 GB without it ("too large to be downloaded using the regular download method"), so
* such a job uses Xet regardless. Returns the files that forced it, for the log.
*/
export function xetFor(files: ExpectedFile[], disabledBySetting: boolean): { useXet: boolean; forcedBy: string[] } {
if (!disabledBySetting) return { useXet: true, forcedBy: [] };
const big = files.filter((f) => f.size > MAX_HTTP_DOWNLOAD_BYTES).map((f) => f.path);
return { useXet: big.length > 0, forcedBy: big };
}
+31
View File
@@ -0,0 +1,31 @@
import assert from "node:assert/strict";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, it } from "node:test";
import { listIncomplete, steadyProgress } from "./hf-layout";
const ETAG = "b139949c5bd74937ad8ed8c8cf3d9ffb1e99c866c823204dc42c0d91fa181897";
describe("download progress", () => {
it("never goes backwards for a file that isn't complete", () => {
const a = steadyProgress(null, [{ done: 300e6, complete: false }, { done: 0, complete: false }]);
const b = steadyProgress(a, [{ done: 0, complete: false }, { done: 5e6, complete: false }]);
assert.deepEqual(b, [{ done: 300e6, complete: false }, { done: 5e6, complete: false }]);
const c = steadyProgress(b, [{ done: 400e6, complete: true }, { done: 6e6, complete: false }]);
assert.deepEqual(c, [{ done: 400e6, complete: true }, { done: 6e6, complete: false }]);
});
it("finds partial files in subfolders and skips folders that are gone", async () => {
const dir = await mkdtemp(join(tmpdir(), "kaname-progress-"));
try {
const sub = join(dir, ".cache", "huggingface", "download", "Q4_K_M");
await mkdir(sub, { recursive: true });
await writeFile(join(sub, `abc=.${ETAG}.905d6ccf.incomplete`), Buffer.alloc(1234));
assert.deepEqual((await listIncomplete(dir)).map((f) => [f.etag, f.size]), [[ETAG, 1234]]);
assert.deepEqual(await listIncomplete(join(dir, "missing")), []);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
});
+101
View File
@@ -0,0 +1,101 @@
// The quality eval against a fake OpenAI-compatible server: requests, scoring, unsupported sections,
// cancelling. (The code sandbox needs Docker; here coding counts as unsupported.)
import assert from "node:assert/strict";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { after, before, describe, it } from "node:test";
import { EVAL_SET } from "@/lib/quality";
import { runQualityEval } from "./quality";
type Body = { messages: { content: string }[]; tools?: unknown[]; temperature?: number; seed?: number; chat_template_kwargs?: { enable_thinking?: boolean } };
let server: Server;
let base = "";
let refuseTools = false;
const seen: Body[] = [];
before(async () => {
server = createServer((req, res) => {
let raw = "";
req.on("data", (c) => (raw += c));
req.on("end", () => {
const body = JSON.parse(raw || "{}") as Body & { content?: string };
const json = (status: number, v: unknown) => {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(v));
};
if (req.url === "/tokenize") return json(200, { tokens: new Array(Math.ceil((body.content ?? "").length / 4)).fill(1) });
if (req.url !== "/v1/chat/completions") return json(404, {});
seen.push(body);
const prompt = body.messages[0].content;
if (body.tools) {
if (refuseTools) return json(400, { error: { message: "tools param requires --jinja flag" } });
const item = EVAL_SET.tools.items.find((i) => i.prompt === prompt)!;
// Half right: every other item calls the wrong function.
const idx = EVAL_SET.tools.items.indexOf(item);
const args = Object.fromEntries(Object.entries(item.expect.args).map(([k, v]) => [k, typeof v === "object" ? ("contains" in v ? v.contains : "oneOf" in v ? v.oneOf[0] : "17 * 23") : v]));
const wrong = item.expect.name === "set_timer" ? "get_weather" : "set_timer";
const name = idx % 2 === 0 ? item.expect.name : wrong;
return json(200, { choices: [{ message: { content: null, tool_calls: [{ function: { name, arguments: JSON.stringify(args) } }] } }] });
}
const code = prompt.match(/vault is (\d{6})/)?.[1];
// Finds the needle in the first two thirds of the text only.
const found = code && prompt.indexOf(code) / prompt.length < 0.66;
return json(200, { choices: [{ message: { content: found ? `The code is ${code}.` : "I couldn't find it." } }] });
});
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
after(() => server.close());
const target = () => ({ base, model: "test/model", engine: "llama.cpp" as const, apiKey: null, contextTokens: 4096 });
const opts = (o: Partial<Parameters<typeof runQualityEval>[1]> = {}) => ({
sections: ["tools", "coding", "retrieval"] as const as ("tools" | "coding" | "retrieval")[],
signal: new AbortController().signal,
log: () => {},
docker: null,
sandboxImage: null,
...o,
});
describe("quality eval run", () => {
it("scores tool calls and retrieval, greedy with a fixed seed and thinking off", async () => {
seen.length = 0;
const q = await runQualityEval(target(), opts());
const by = Object.fromEntries(q.sections.map((s) => [s.section, s]));
assert.equal(by.tools.passed, 6);
assert.equal(by.tools.total, 12);
assert.match(by.coding.unsupported!, /sandbox/);
assert.equal(by.retrieval.total, 9);
assert.equal(by.retrieval.passed, 6, "positions 10 % and 50 % found, 90 % not");
assert.equal(q.score, 58.3, "mean of 50 % and 66.7 %; coding doesn't count");
assert.equal(q.evalSet, "kaname-eval-1");
assert.ok(seen.every((b) => b.temperature === 0 && b.seed === 1 && b.chat_template_kwargs?.enable_thinking === false));
assert.equal(q.items.filter((i) => i.section === "tools" && !i.pass)[0].detail, "called set_timer, expected convert_currency");
});
it("marks tool calling unsupported when the server refuses tools", async () => {
refuseTools = true;
try {
const q = await runQualityEval(target(), opts({ sections: ["tools"] }));
assert.match(q.sections[0].unsupported!, /refused tool calls: .*--jinja/);
assert.equal(q.score, null);
} finally {
refuseTools = false;
}
});
it("can't plan retrieval without a context length", async () => {
const q = await runQualityEval({ ...target(), contextTokens: null }, opts({ sections: ["retrieval"] }));
assert.match(q.sections[0].unsupported!, /context length is unknown/);
});
it("stops early when cancelled", async () => {
const ac = new AbortController();
ac.abort();
const q = await runQualityEval(target(), opts({ signal: ac.signal }));
assert.equal(q.sections.length, 0);
});
});
+242
View File
@@ -0,0 +1,242 @@
// Runs the quality eval (src/lib/quality.ts) against a running deployment: greedy decoding with a
// fixed seed, thinking turned off where the chat template supports it, scoring that doesn't depend
// on judgement. Coding answers run with their unit tests in a throwaway container from Kaname's own
// image: no network, read-only, unprivileged user, all capabilities dropped, small limits.
import type { QualityResult, QualitySection, RuntimeEngine } from "@/lib/db/schema";
import {
buildHaystack,
EVAL_SEED,
EVAL_SET,
EVAL_SET_VERSION,
extractCode,
retrievalCases,
scoreNeedle,
scoreToolCall,
summarize,
testProgram,
type ToolCall,
toolDefs,
} from "@/lib/quality";
import type { DockerClient } from "./docker/client";
export type EvalTarget = {
/** http://<container>:<port> */
base: string;
model: string;
engine: RuntimeEngine;
apiKey: string | null;
/** Context per request (llama.cpp: per slot), for the retrieval lengths. */
contextTokens: number | null;
};
export type EvalOptions = {
sections: QualitySection[];
signal: AbortSignal;
log: (line: string) => void;
docker: DockerClient | null;
/** Image for the coding sandbox (Kaname's own, it has Python); null: coding can't run. */
sandboxImage: string | null;
};
const TEMPERATURE = 0;
const THINKING = false;
class HttpError extends Error {
constructor(
public status: number,
message: string,
) {
super(message);
}
}
async function post<T>(t: EvalTarget, path: string, body: unknown, signal: AbortSignal, timeoutMs: number): Promise<T> {
const res = await fetch(`${t.base}${path}`, {
method: "POST",
headers: { "Content-Type": "application/json", ...(t.apiKey ? { Authorization: `Bearer ${t.apiKey}` } : {}) },
body: JSON.stringify(body),
signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),
});
const text = await res.text();
if (!res.ok) throw new HttpError(res.status, text.slice(0, 300));
return JSON.parse(text) as T;
}
type ChatMessage = { content?: string | null; tool_calls?: { function?: { name?: string; arguments?: string } }[] };
/** One greedy chat completion; thinking off (Qwen3-style templates read enable_thinking, others ignore it). */
async function chat(t: EvalTarget, messages: { role: string; content: string }[], extra: Record<string, unknown>, signal: AbortSignal, timeoutMs = 300_000) {
const r = await post<{ choices?: { message?: ChatMessage }[] }>(
t,
"/v1/chat/completions",
{ model: t.model, messages, temperature: TEMPERATURE, seed: EVAL_SEED, chat_template_kwargs: { enable_thinking: THINKING }, ...extra },
signal,
timeoutMs,
);
return r.choices?.[0]?.message ?? {};
}
type Section = QualityResult["sections"][number];
type Item = QualityResult["items"][number];
async function toolsSection(t: EvalTarget, o: EvalOptions, items: Item[]): Promise<Omit<Section, "score" | "seconds">> {
let passed = 0;
const all = EVAL_SET.tools.items;
for (const item of all) {
if (o.signal.aborted) break;
try {
const m = await chat(t, [{ role: "user", content: item.prompt }], { tools: toolDefs(item), tool_choice: "auto", max_tokens: 512 }, o.signal);
const calls: ToolCall[] = (m.tool_calls ?? []).map((c) => ({ name: c.function?.name ?? "", arguments: c.function?.arguments ?? "" }));
const r = scoreToolCall(calls, item.expect);
if (r.pass) passed++;
items.push({ section: "tools", id: item.id, pass: r.pass, detail: r.detail });
o.log(`tools ${item.id}: ${r.pass ? "pass" : `fail (${r.detail})`}`);
} catch (err) {
// The server can't do tool calls at all (e.g. no tool-call parser configured): the section
// doesn't count instead of scoring 0.
if (err instanceof HttpError && err.status >= 400 && err.status < 500 && items.every((x) => x.section !== "tools")) {
o.log(`tools: the server refused tool calls (${err.status}): ${err.message}`);
return { section: "tools", passed: 0, total: 0, unsupported: `the server refused tool calls: ${err.message.slice(0, 200)}` };
}
if (o.signal.aborted) break;
items.push({ section: "tools", id: item.id, pass: false, detail: err instanceof Error ? err.message.slice(0, 200) : String(err) });
o.log(`tools ${item.id}: error ${err instanceof Error ? err.message : err}`);
}
}
return { section: "tools", passed, total: all.length };
}
/** Run a program in the sandbox; ok when it exits 0 and printed the marker. */
async function runPython(c: DockerClient, image: string, program: string, signal: AbortSignal): Promise<{ ok: boolean; output: string }> {
const runner = "import base64,os;exec(compile(base64.b64decode(os.environ['KANAME_CODE']).decode(),'solution','exec'),{'__name__':'__main__'})";
const created = await c.createContainer(`kaname-eval-sandbox-${Date.now().toString(36)}${Math.floor(Math.random() * 1e6).toString(36)}`, {
Image: image,
User: "65534:65534",
Entrypoint: ["python3", "-I", "-c", runner],
Cmd: [],
Env: [`KANAME_CODE=${Buffer.from(program).toString("base64")}`, "PYTHONDONTWRITEBYTECODE=1"],
NetworkDisabled: true,
Labels: { "kaname.managed": "true", "kaname.probe": "eval-sandbox" },
HostConfig: {
NetworkMode: "none",
ReadonlyRootfs: true,
Tmpfs: { "/tmp": "rw,noexec,nosuid,size=16m" },
CapDrop: ["ALL"],
SecurityOpt: ["no-new-privileges"],
Memory: 256 * 2 ** 20,
MemorySwap: 256 * 2 ** 20,
NanoCpus: 1e9,
PidsLimit: 64,
Privileged: false,
AutoRemove: false,
},
});
const lines: string[] = [];
try {
await c.startContainer(created.Id);
await c
.followLogs(created.Id, (_s, line) => lines.length < 200 && lines.push(line), { tail: "all", signal: AbortSignal.any([signal, AbortSignal.timeout(15_000)]) })
.catch(() => {});
const st = await c.containerState(created.Id);
if (st?.Running) {
await c.stopContainer(created.Id, 0).catch(() => {});
return { ok: false, output: "timed out (15 s)" };
}
return { ok: st?.ExitCode === 0 && lines.some((l) => l.includes("KANAME-OK")), output: lines.slice(-6).join("\n") };
} finally {
await c.removeContainer(created.Id).catch(() => {});
}
}
async function codingSection(t: EvalTarget, o: EvalOptions, items: Item[]): Promise<Omit<Section, "score" | "seconds">> {
if (!o.docker || !o.sandboxImage) return { section: "coding", passed: 0, total: 0, unsupported: "no Docker access for the code sandbox" };
let passed = 0;
const all = EVAL_SET.coding.items;
for (const item of all) {
if (o.signal.aborted) break;
let pass = false;
let detail: string;
try {
const m = await chat(t, [{ role: "user", content: `${EVAL_SET.coding.instructions}\n\n${item.prompt}` }], { max_tokens: 1024 }, o.signal);
const code = extractCode(m.content ?? "");
if (!code) detail = "no code block in the answer";
else {
const r = await runPython(o.docker, o.sandboxImage, testProgram(code, item.tests), o.signal);
pass = r.ok;
detail = r.ok ? "tests pass" : `tests fail: ${r.output.split("\n").slice(-2).join(" ").slice(0, 200)}`;
}
} catch (err) {
if (o.signal.aborted) break;
detail = err instanceof Error ? err.message.slice(0, 200) : String(err);
}
if (pass) passed++;
items.push({ section: "coding", id: item.id, pass, detail });
o.log(`coding ${item.id}: ${pass ? "pass" : `fail (${detail})`}`);
}
return { section: "coding", passed, total: all.length };
}
/** Characters per token of the filler text, by the server's own tokenizer (4 if it can't tell). */
async function charsPerToken(t: EvalTarget, signal: AbortSignal): Promise<number> {
const sample = EVAL_SET.retrieval.filler.join(" ");
try {
const r =
t.engine === "llama.cpp"
? await post<{ tokens?: unknown[] }>(t, "/tokenize", { content: sample }, signal, 30_000)
: await post<{ count?: number; tokens?: unknown[] }>(t, "/tokenize", { model: t.model, prompt: sample }, signal, 30_000);
const n = (r as { count?: number }).count ?? r.tokens?.length ?? 0;
return n > 0 ? sample.length / n : 4;
} catch {
return 4;
}
}
async function retrievalSection(t: EvalTarget, o: EvalOptions, items: Item[]): Promise<Omit<Section, "score" | "seconds">> {
if (!t.contextTokens) return { section: "retrieval", passed: 0, total: 0, unsupported: "the context length is unknown" };
const cases = retrievalCases(t.contextTokens);
if (cases.length === 0) return { section: "retrieval", passed: 0, total: 0, unsupported: `context of ${t.contextTokens} tokens is too short` };
const cpt = await charsPerToken(t, o.signal);
let passed = 0;
for (const c of cases) {
if (o.signal.aborted) break;
let pass = false;
let detail: string;
try {
const m = await chat(t, [{ role: "user", content: buildHaystack(c, cpt) }], { max_tokens: 32 }, o.signal, 900_000);
({ pass, detail } = scoreNeedle(m.content ?? "", c));
} catch (err) {
if (o.signal.aborted) break;
detail = err instanceof Error ? err.message.slice(0, 200) : String(err);
}
if (pass) passed++;
items.push({ section: "retrieval", id: c.id, pass, detail });
o.log(`retrieval ${c.id}: ${pass ? "pass" : `fail (${detail})`}`);
}
return { section: "retrieval", passed, total: cases.length };
}
const RUNNERS: Record<QualitySection, (t: EvalTarget, o: EvalOptions, items: Item[]) => Promise<Omit<Section, "score" | "seconds">>> = {
tools: toolsSection,
coding: codingSection,
retrieval: retrievalSection,
};
/** The whole eval (or the chosen sections), in order; stops early when the signal aborts. */
export async function runQualityEval(t: EvalTarget, o: EvalOptions): Promise<QualityResult> {
const items: Item[] = [];
const sections: Section[] = [];
for (const s of o.sections) {
if (o.signal.aborted) break;
const t0 = Date.now();
o.log(`${s}: starting`);
const r = await RUNNERS[s](t, o, items);
sections.push({ ...r, score: null, seconds: Math.round((Date.now() - t0) / 1000) });
}
return {
evalSet: EVAL_SET_VERSION,
...summarize(sections),
items,
config: { temperature: TEMPERATURE, seed: EVAL_SEED, thinking: THINKING, contextTokens: t.contextTokens },
};
}
+42 -10
View File
@@ -7,6 +7,7 @@ import { deploymentSnapshot } from "@/lib/benchmark-snapshot";
import { db } from "@/lib/db/client";
import { benchmarkRuns, benchmarkSweeps, deployments, modelFiles, runtimes, type SweepVariant } from "@/lib/db/schema";
import { estimateMemoryMb } from "@/lib/deploy-command";
import { overTime } from "@/lib/agent-tuning";
import { applyOverrides } from "@/lib/sweep";
import { log } from "./log";
@@ -47,21 +48,24 @@ async function advance(sweep: Sweep): Promise<void> {
await save(sweep.id, { variants });
};
if (sweep.cancelRequestedAt) {
const timedOut = overTime(sweep.startedAt, sweep.timeLimitS);
if (sweep.cancelRequestedAt || timedOut) {
for (const v of variants) {
if (v.state === "benchmarking" && v.runId) await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, v.runId));
if (v.state === "deploying" || v.state === "benchmarking") await removeDeployment(v.deploymentId);
const open = v.state === "evaluating" ? v.evalRunId : v.state === "benchmarking" ? v.runId : null;
if (open) await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, open));
if (v.state === "deploying" || v.state === "benchmarking" || v.state === "evaluating") await removeDeployment(v.deploymentId);
}
await save(sweep.id, {
state: "cancelled",
state: timedOut ? "failed" : "cancelled",
...(timedOut ? { error: `Stopped: the sweep exceeded the time limit for agent sweeps (${Math.round((sweep.timeLimitS ?? 0) / 60)} min).` } : {}),
finishedAt: new Date(),
variants: variants.map((v) => (v.state === "pending" || v.state === "deploying" || v.state === "benchmarking" ? { ...v, state: "skipped" as const } : v)),
variants: variants.map((v) => (v.state === "pending" || v.state === "deploying" || v.state === "benchmarking" || v.state === "evaluating" ? { ...v, state: "skipped" as const } : v)),
});
log.info(`sweep ${sweep.id}: cancelled`);
log.info(`sweep ${sweep.id}: ${timedOut ? "stopped at its time limit" : "cancelled"}`);
return;
}
const i = variants.findIndex((v) => v.state === "pending" || v.state === "deploying" || v.state === "benchmarking");
const i = variants.findIndex((v) => v.state === "pending" || v.state === "deploying" || v.state === "benchmarking" || v.state === "evaluating");
if (i < 0) {
const ok = variants.filter((v) => v.state === "done").length;
await save(sweep.id, { state: ok > 0 ? "completed" : "failed", finishedAt: new Date(), error: ok > 0 ? null : "No variant could be benchmarked." });
@@ -114,20 +118,48 @@ async function advance(sweep: Sweep): Promise<void> {
settings: sweep.settings,
snapshot: snap.snapshot,
sweepId: sweep.id,
// Runs of an agent's sweep carry its token and the per-run time limit.
requestedByTokenId: sweep.requestedByTokenId,
requestedBy: sweep.requestedBy,
timeLimitS: sweep.runTimeLimitS,
})
.returning({ id: benchmarkRuns.id });
await put(i, { state: "benchmarking", runId: run.id });
return;
}
// benchmarking
const run = v.runId ? await db().query.benchmarkRuns.findFirst({ columns: { state: true, error: true }, where: eq(benchmarkRuns.id, v.runId) }) : null;
// benchmarking, then (sweeps with quality) evaluating
const runId = v.state === "evaluating" ? v.evalRunId : v.runId;
const run = runId ? await db().query.benchmarkRuns.findFirst({ columns: { state: true, error: true }, where: eq(benchmarkRuns.id, runId) }) : null;
if (!run) {
await put(i, { state: "failed", error: "The variant's run disappeared." });
return removeDeployment(v.deploymentId);
}
if (run.state === "queued" || run.state === "running") return;
await put(i, run.state === "completed" ? { state: "done" } : { state: "failed", error: run.error ?? `The run was ${run.state}.` });
if (run.state === "completed" && v.state === "benchmarking" && sweep.settings.quality) {
const snap = await deploymentSnapshot(v.deploymentId!);
if (snap) {
const [ev] = await db()
.insert(benchmarkRuns)
.values({
kind: "eval",
deploymentId: snap.id,
modelId: snap.modelId,
label: `${sweep.label ? `${sweep.label}: ` : ""}${v.label} · quality`.slice(0, 120),
settings: { quick: false, passes: null, warmup: null, phases: [], evalSections: [] },
snapshot: snap.snapshot,
sweepId: sweep.id,
requestedByTokenId: sweep.requestedByTokenId,
requestedBy: sweep.requestedBy,
timeLimitS: sweep.runTimeLimitS,
})
.returning({ id: benchmarkRuns.id });
return void (await put(i, { state: "evaluating", evalRunId: ev.id }));
}
}
const ok = run.state === "completed" || (v.state === "evaluating" && !!v.runId);
// A failed eval doesn't undo the speed result; it shows on the eval run.
await put(i, ok ? { state: "done" } : { state: "failed", error: run.error ?? `The run was ${run.state}.` });
await removeDeployment(v.deploymentId);
}
+19
View File
@@ -0,0 +1,19 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { MAX_HTTP_DOWNLOAD_BYTES, xetFor } from "./hf-layout";
const f = (path: string, size: number) => ({ path, size, etags: [] });
describe("Xet for files over 50 GB", () => {
it("stays off for ordinary files when the setting disables it", () => {
assert.deepEqual(xetFor([f("a.gguf", 20e9), f("b.gguf", MAX_HTTP_DOWNLOAD_BYTES)], true), { useXet: false, forcedBy: [] });
});
it("turns on for a job with a file hf only downloads over Xet", () => {
assert.deepEqual(xetFor([f("small.json", 1000), f("Huge-BF16.gguf", 54e9)], true), { useXet: true, forcedBy: ["Huge-BF16.gguf"] });
});
it("is on whenever the setting allows Xet", () => {
assert.deepEqual(xetFor([f("a.gguf", 1)], false), { useXet: true, forcedBy: [] });
});
});