Compare commits

..
8 Commits
Author SHA1 Message Date
Pascal LinxweilerandClaude Opus 5.5 f0b4adda63 Release 0.8.0: deployments
Release / release (push) Successful in 3m17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:30:14 +02:00
Pascal LinxweilerandClaude Opus 5.5 ea1f18cc74 Deployments: API keys, deploy from the library, reorganized form
- Settings → API keys (generate or paste, show again, delete). Deployments with
  "Require an API key" get them via LLAMA_API_KEY / VLLM_API_KEY (--api-key for
  several vLLM keys); values are masked in the stored/shown command and in logs.
  The chat proxy sends a key.
- "Deploy" in the library and on the model page preselects the model and a
  runtime that can serve it; library rows and the model page link to the
  model's deployments.
- Deployment form: grouped launch options with flags next to labels, command in
  its own step, extra arguments as flag/value rows (runtime form too).
- Native selects follow the dark theme (color-scheme), fixing unreadable options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:28:25 +02:00
Pascal LinxweilerandClaude Opus 5.5 66e6a8c4f7 Deployments: llama.cpp web UI toggle, clearer start failures, log fixes
- Web UI option for llama.cpp deployments (--no-webui when off); the deployment
  page links to it on the published host port.
- Follow container logs after the start with tail=all: following a created
  container returned an already-closed stream, so startup output was lost.
- Failed starts name the cause from the log (vLLM ValueError, llama.cpp error
  lines) before the last output.
- A deployment's vLLM dtype replaces the runtime's --dtype instead of repeating it.
- vLLM memory estimate: 3 GiB overhead (measured ~6.9 GiB for SmolLM2-135M
  with a 4 GiB KV cache).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 12:01:52 +02:00
Pascal LinxweilerandClaude Opus 5.5 8b74fa69db Deployments: serve a model with a runtime container
- deployments + deployment_logs tables; desired/actual state reconciled by
  the worker (create/start/stop/remove via the socket proxy, /health wait,
  log follower, stats, memory guard, adopt/remove containers on restart).
- Pure command builder for llama-server and vllm serve (mmproj, MTP draft,
  KV cache types, dtype, KV cache size) with tests; file candidates per
  engine with tests.
- New main menu entry Deployments: list, new/edit form (runtime -> model
  and files -> launch options, live command preview), detail page with
  stats, log, endpoint and a streaming chat smoke test.

Not yet tested end-to-end against real containers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 11:31:04 +02:00
Pascal LinxweilerandClaude Opus 5.5 4f7ae1fc8c Fix image pull progress never being written
`void query` doesn't execute a Drizzle query (it runs on then/await), so
pull progress stayed at "Starting" until the pull finished.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:39:15 +02:00
Pascal LinxweilerandClaude Opus 5.5 a756eb3794 Release workflow: drop setup-node's npm cache
The act_runner cache server isn't reachable from job containers
(getCacheEntry ETIMEDOUT), so restoring and saving the cache timed out
for ~4.5 min each, ~9 of the ~12 minutes per release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:30:25 +02:00
Pascal LinxweilerandClaude Opus 5.5 930126c5eb Release 0.7.0: runtimes and Docker connection
Release / release (push) Successful in 11m56s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:27:18 +02:00
Pascal LinxweilerandClaude Opus 5.5 b68b4a2b23 Runtimes: Docker connection via socket proxy, runtime images, host info
- docker-proxy service (tecnativa/docker-socket-proxy) in both compose
  files; worker uses it via DOCKER_HOST with a dependency-free client.
- runtimes table with presets (llama.cpp CPU, vLLM CPU) and custom
  images; validation of image refs, env, args, devices (/dev/dri, /dev/kfd).
- Worker reports Docker/CPU/memory facts and detects its network and
  models mount; pulls images with progress; image state per runtime.
- Settings -> Runtimes page with host card, list, editor, pull/update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 01:24:59 +02:00
70 changed files with 8881 additions and 12 deletions

No files matched your search

+2 -1
View File
@@ -14,10 +14,11 @@ jobs:
steps:
- uses: actions/checkout@v4
# No `cache: npm`: the runner's cache server isn't reachable from job containers here, and the
# restore + save timeouts cost ~9 minutes per run. `npm ci` alone takes ~20 s.
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- name: Resolve version and image name
run: |
+70
View File
@@ -6,6 +6,76 @@ step 1 (Hugging Face downloader) is released as a minor version.
## [Unreleased]
## [0.8.0] - 2026-10-06
Model testing, part two: deployments. Serve a downloaded model with a llama.cpp or vLLM runtime
container, tune its launch options, protect it with API keys and try it from Kaname.
No changes to `compose.yaml`; the new database tables are created on start.
### Added
- **Deployments** (new main menu entry): serve a downloaded model with a runtime container.
- **New deployment:** pick a runtime (only pulled images), then a model it can serve (llama.cpp:
downloaded GGUF files with the quant, optional mmproj for vision and MTP head / draft model for
speculative decoding; vLLM: safetensors repos with a config.json), then launch options: context
size, threads, parallel slots, KV cache types, flash attention, batch sizes (llama.cpp) or data
type, max sequences, KV cache GiB (vLLM), CPU and memory limits (with an estimate), an optional
published host port and extra arguments. A live preview shows the exact `docker run` command.
- The worker starts the container on Kaname's Docker network with the models mounted read-only,
waits for `/health`, follows the log, samples CPU/RAM every 5 s and refuses to start when the
memory limits of running deployments wouldn't fit. Containers keep running across worker
restarts; orphaned ones are removed.
- Deployment page: state, load time, live CPU/RAM, endpoint URLs (Docker network and published
port), live log, start/stop/edit/delete, and a "Try it" chat that streams the answer and shows
time to first token and tokens/s.
- llama.cpp's built-in **web UI** can be switched on or off per deployment (`--no-webui`); with a
published host port the deployment page links to it.
- A failed start names the cause from the log (e.g. vLLM's `ValueError` instead of the end of the
traceback), followed by the last lines of output.
- A deployment's vLLM data type replaces the runtime's `--dtype` instead of repeating the flag.
- Models and runtimes used by a deployment can't be deleted until the deployment is.
- **API keys** (Settings → API keys): add generated or own keys, show and copy them again later.
A deployment with "Require an API key" accepts any of them (`LLAMA_API_KEY`, `VLLM_API_KEY` or
`--api-key` for several vLLM keys); the values are masked in the shown command and in the log, and
Kaname's own "Try it" chat sends one. Key changes apply when a deployment restarts.
- **Deploy from the library:** a "Deploy" button in the library and on the model page opens a new
deployment with the model and a fitting runtime preselected. The library and the model page link
to the deployments that use a model.
- Deployment form reorganized: launch options in groups (General, Context, Performance, KV cache,
Resources, Extra arguments) with each field's flag next to its label, the command in its own step,
and extra arguments as flag/value rows with "+ Add argument" (also in the runtime form).
### Fixed
- Dropdowns were unreadable in dark mode (white option list with light text): native controls now
follow the theme.
- Image pulls showed "Starting · 0 B" until they finished: the worker's progress updates were never
written (Drizzle queries only run when awaited).
## [0.7.0] - 2026-10-06
First part of model testing: runtimes (llama.cpp, vLLM and your own images) and the Docker
connection through a socket proxy. Starting containers with a model comes next.
**Upgrade note:** `compose.yaml` has a new `docker-proxy` service and `DOCKER_HOST` on the worker;
copy them from `deploy/compose.yaml`.
### Added
- **Runtimes** (Settings → Runtimes): container images that serve models. Presets for the official
llama.cpp CPU server (`ghcr.io/ggml-org/llama.cpp:server`) and vLLM CPU
(`vllm/vllm-openai-cpu:v0.31.0`), plus your own images from any registry (e.g. patched forks) with
an engine type (llama.cpp- or vLLM-compatible), environment, extra arguments, shared memory,
device passthrough (only `/dev/dri…`, `/dev/kfd`) and an opt-in "NUMA tuning" switch (the
`CAP_SYS_NICE` + `seccomp=unconfined` that vLLM recommends on CPU; off by default).
- Pull and update runtime images from the UI, with progress and readable errors.
- Docker host card: Docker version, CPU model and features (AVX2, AVX-512, AMX, …), memory, and the
network and models source the worker detected from its own container.
- `docker-proxy` service (`tecnativa/docker-socket-proxy:v0.5.0`) in both compose files; the worker
reaches Docker only through it (`DOCKER_HOST`). New settings `DOCKER_HOST`,
`KANAME_DOCKER_NETWORK`, `KANAME_MODELS_SOURCE` (see the wiki).
## [0.6.0] - 2026-10-06
Delete models (with their files), verify and deep verify, one-click repair, and update checks
+3
View File
@@ -82,6 +82,9 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
updating is always your click. If a repo (or its pinned commit) disappears from Hugging Face, the
model is flagged and your local copy is kept.
- **Delete:** removes the model and, if you want, its files from disk.
- **Runtimes:** register llama.cpp, vLLM or your own fork images and pull them from Settings → Runtimes
(groundwork for testing model configs). See the
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Runtimes).
- **Jobs:** each download has a page with per-file progress and the full `hf` log.
## How it works
+22
View File
@@ -16,6 +16,11 @@ services:
worker:
<<: *app
command: worker
environment:
DATABASE_URL: file:/data/app.db
MODELS_DIR: /models
HF_HOME: /data/hf-home
DOCKER_HOST: tcp://docker-proxy:2375
volumes: [data:/data, models:/models]
web:
@@ -23,6 +28,23 @@ services:
ports: ["${WEB_PORT:-3000}:3000"]
volumes: [data:/data]
# Docker API for runtimes (llama.cpp / vLLM containers), limited to what Kaname needs:
# containers, images, networks, info. Not reachable from outside the compose network.
# Remove this service (and DOCKER_HOST on the worker) to run Kaname as a pure downloader.
docker-proxy:
image: tecnativa/docker-socket-proxy:v0.5.0
environment:
CONTAINERS: 1
IMAGES: 1
INFO: 1
NETWORKS: 1
POST: 1
ALLOW_START: 1
ALLOW_STOP: 1
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
restart: unless-stopped
volumes:
data:
models:
+19
View File
@@ -8,6 +8,8 @@ services:
image: git.linxweiler.xyz/pascallinxweiler/kaname:${KANAME_VERSION:-latest}
command: worker
env_file: .env
environment:
DOCKER_HOST: tcp://docker-proxy:2375
volumes:
- ${KANAME_DATA_DIR:-./data}:/data # SQLite DB, shared with web (local disk, not NFS)
- ${KANAME_MODELS_DIR:-./models}:/models # downloaded models (a host-mounted NAS share works)
@@ -20,3 +22,20 @@ services:
volumes:
- ${KANAME_DATA_DIR:-./data}:/data
restart: unless-stopped
# Docker API for runtimes (llama.cpp / vLLM containers), limited to what Kaname needs:
# containers, images, networks, info. Not reachable from outside the compose network.
# Remove this service (and DOCKER_HOST on the worker) to run Kaname as a pure downloader.
docker-proxy:
image: tecnativa/docker-socket-proxy:v0.5.0
environment:
CONTAINERS: 1
IMAGES: 1
INFO: 1
NETWORKS: 1
POST: 1
ALLOW_START: 1
ALLOW_STOP: 1
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
restart: unless-stopped
+26
View File
@@ -0,0 +1,26 @@
CREATE TABLE `runtimes` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`engine` text NOT NULL,
`image` text NOT NULL,
`description` text,
`env` text DEFAULT '{}' NOT NULL,
`extra_args` text DEFAULT '[]' NOT NULL,
`devices` text DEFAULT '[]' NOT NULL,
`shm_size_mb` integer,
`numa_tuning` integer DEFAULT false NOT NULL,
`preset` text,
`image_state` text DEFAULT 'unknown' NOT NULL,
`image_id` text,
`image_size` integer,
`image_created` text,
`pull_requested_at` integer,
`pull_started_at` integer,
`pull_progress` text,
`pull_error` text,
`image_checked_at` integer,
`created_at` integer NOT NULL,
`updated_at` integer NOT NULL
);
--> statement-breakpoint
ALTER TABLE `worker_state` ADD `docker` text;
+37
View File
@@ -0,0 +1,37 @@
CREATE TABLE `deployment_logs` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`deployment_id` text NOT NULL,
`ts` integer NOT NULL,
`stream` text NOT NULL,
`line` text NOT NULL,
FOREIGN KEY (`deployment_id`) REFERENCES `deployments`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE INDEX `deployment_logs_idx` ON `deployment_logs` (`deployment_id`,`id`);--> statement-breakpoint
CREATE TABLE `deployments` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`runtime_id` text NOT NULL,
`model_id` text NOT NULL,
`options` text NOT NULL,
`cpus` real,
`memory_mb` integer,
`host_port` integer,
`desired_state` text DEFAULT 'stopped' NOT NULL,
`state` text DEFAULT 'stopped' NOT NULL,
`delete_requested_at` integer,
`container_id` text,
`container_name` text,
`command` text,
`image_id` text,
`started_at` integer,
`ready_at` integer,
`stopped_at` integer,
`exit_code` integer,
`error` text,
`stats` text,
`created_at` integer NOT NULL,
`updated_at` integer NOT NULL,
FOREIGN KEY (`runtime_id`) REFERENCES `runtimes`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`model_id`) REFERENCES `models`(`id`) ON UPDATE no action ON DELETE no action
);
+8
View File
@@ -0,0 +1,8 @@
CREATE TABLE `api_keys` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`key` text NOT NULL,
`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `api_keys_key_unique` ON `api_keys` (`key`);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+21
View File
@@ -71,6 +71,27 @@
"when": 1791238659338,
"tag": "0009_verify_update",
"breakpoints": true
},
{
"idx": 10,
"version": "6",
"when": 1791242201063,
"tag": "0010_runtimes",
"breakpoints": true
},
{
"idx": 11,
"version": "6",
"when": 1791278463453,
"tag": "0011_deployments",
"breakpoints": true
},
{
"idx": 12,
"version": "6",
"when": 1791281615301,
"tag": "0012_api_keys",
"breakpoints": true
}
]
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "kaname",
"version": "0.6.0",
"version": "0.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kaname",
"version": "0.6.0",
"version": "0.8.0",
"dependencies": {
"@base-ui/react": "^1.8.0",
"@libsql/client": "^0.18.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "kaname",
"version": "0.6.0",
"version": "0.8.0",
"private": true,
"scripts": {
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
+44 -1
View File
@@ -9,6 +9,8 @@ import {
LanguagesIcon,
ListChecksIcon,
MessagesSquareIcon,
PlusIcon,
RocketIcon,
ScaleIcon,
SparklesIcon,
TriangleAlertIcon,
@@ -17,12 +19,14 @@ import type { Metadata } from "next";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { HubStateBadge } from "@/components/hub-state-badge";
import { LocalTime } from "@/components/local-time";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { formatBytes, shortSha } from "@/lib/format";
import { deploymentsByModel, listDeployableModels } from "@/lib/deployments";
import { fetchModelCard } from "@/lib/hub/client";
import { modelFamilies } from "@/lib/hub/metadata";
import { listModelJobs } from "@/lib/jobs";
@@ -97,13 +101,17 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
const hubTags = model.hubTags ?? [];
const hubMissing = model.hubState === "repo_missing" || model.hubState === "commit_missing";
const [tags, related, card, worker, recentJobs] = await Promise.all([
const [tags, related, card, worker, recentJobs, byModel, deployable] = await Promise.all([
modelTagList(model.id),
relatedModels(model.id, baseModels),
tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined),
getWorkerStatus(),
listModelJobs(model.id, 1),
deploymentsByModel(),
listDeployableModels(),
]);
const modelDeployments = byModel.get(model.id) ?? [];
const canDeploy = deployable.some((m) => m.id === model.id);
const update =
!hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha
? model.updateDiff
@@ -143,6 +151,15 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
</span>
)}
<div className="ml-auto flex items-center gap-2">
{canDeploy && (
<Link
href={`/deployments/new?model=${model.id}`}
className={cn(buttonVariants({ variant: "outline", size: "sm" }), "border-foreground/15 bg-background shadow-xs")}
>
<RocketIcon />
Deploy
</Link>
)}
<DeleteModelButton
id={model.id}
repoId={model.repoId}
@@ -287,6 +304,32 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
<DownloadCard modelId={model.id} status={model.status} hubMissing={hubMissing} />
</SideCard>
{(modelDeployments.length > 0 || canDeploy) && (
<SideCard title="Deployments" icon={RocketIcon}>
<div className="flex flex-col gap-2">
{modelDeployments.length === 0 ? (
<p className="text-sm text-muted-foreground">Not deployed yet.</p>
) : (
modelDeployments.map((d) => (
<Link key={d.id} href={`/deployments/${d.id}`} className="flex items-center justify-between gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted">
<span className="flex min-w-0 flex-col">
<span className="truncate font-medium">{d.name}</span>
<span className="truncate text-xs text-muted-foreground">{d.runtimeName}</span>
</span>
<DeploymentStateBadge state={d.state} desiredState={d.desiredState} />
</Link>
))
)}
{canDeploy && (
<Link href={`/deployments/new?model=${model.id}`} className="flex items-center gap-1 self-start text-xs text-muted-foreground hover:text-foreground">
<PlusIcon className="size-3.5" />
New deployment
</Link>
)}
</div>
</SideCard>
)}
<SideCard title="Local copy" icon={ListChecksIcon}>
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1.5 text-sm">
<dt className="text-muted-foreground">Selection</dt>
@@ -0,0 +1,421 @@
"use client";
import { ExternalLinkIcon, PencilIcon, PlayIcon, SendIcon, SquareIcon, Trash2Icon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
import { ENGINE_PORT } from "@/lib/deploy-command";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes, percent } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { cn } from "@/lib/utils";
import { deleteDeployment, startDeployment, stopDeployment } from "../actions";
type Deployment = Omit<DeploymentRow, "startedAt" | "readyAt" | "stoppedAt" | "createdAt"> & {
startedAt: string | null;
readyAt: string | null;
stoppedAt: string | null;
createdAt: string;
};
type LogLine = { id: number; ts: number; stream: string; line: string };
function Stat({ label, value, children }: { label: string; value: React.ReactNode; children?: React.ReactNode }) {
return (
<div className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">{label}</span>
<span className="text-lg font-semibold tabular-nums">{value}</span>
{children}
</div>
);
}
export function DeploymentDetail({ initial }: { initial: Deployment }) {
const router = useRouter();
const [d, setD] = useState(initial);
const [now, setNow] = useState(() => Date.now());
const active = d.desiredState === "running" || d.state === "starting" || d.state === "running" || d.state === "stopping";
useEffect(() => {
const t = setInterval(async () => {
setNow(Date.now());
const res = await fetch(`/api/deployments/${d.id}`, { cache: "no-store" }).catch(() => null);
if (res?.status === 404) router.push("/deployments");
else if (res?.ok) setD(await res.json());
}, 2_000);
return () => clearInterval(t);
}, [d.id, router]);
const file = d.options.modelFile ? (quantGroup(d.options.modelFile) ?? d.options.modelFile) : null;
const loadSecs = d.readyAt && d.startedAt ? (new Date(d.readyAt).getTime() - new Date(d.startedAt).getTime()) / 1000 : null;
const startingSecs = d.state === "starting" && d.startedAt ? Math.max(0, (now - new Date(d.startedAt).getTime()) / 1000) : null;
const port = ENGINE_PORT[d.engine];
const internal = d.containerName ? `http://${d.containerName}:${port}/v1` : null;
const hostname = useHostname();
const published = d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/v1` : null;
const webUi = webUiUrl(d, hostname);
return (
<div className="flex flex-col gap-4">
<Card>
<CardContent className="flex flex-wrap items-start justify-between gap-4">
<div className="flex min-w-0 flex-col gap-1">
<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} />
</div>
<p className="text-sm text-muted-foreground">
<Link href={`/${d.repoId}`} className="hover:underline">
{d.repoId}
</Link>
{file && ` · ${file}`}
{d.options.mmproj && " · vision"}
{d.options.draftFile && ` · ${d.options.draftType === "draft-mtp" ? "MTP" : "draft"}`} · {d.runtimeName}
</p>
<code className="font-mono text-xs text-muted-foreground">{d.runtimeImage}</code>
</div>
<div className="flex flex-wrap items-center gap-2">
{webUi && (
<a
href={webUi}
target="_blank"
rel="noreferrer"
className={cn(buttonVariants({ variant: "outline" }), d.state !== "running" && "pointer-events-none opacity-50")}
aria-disabled={d.state !== "running"}
>
<ExternalLinkIcon />
Web UI
</a>
)}
{active ? (
<Button variant="outline" onClick={() => stopDeployment(d.id)}>
<SquareIcon />
Stop
</Button>
) : (
<Button onClick={() => startDeployment(d.id)}>
<PlayIcon />
Start
</Button>
)}
<Link
href={`/deployments/${d.id}/edit`}
className={cn(buttonVariants({ variant: "outline" }), active && "pointer-events-none opacity-50")}
aria-disabled={active}
title={active ? "Stop it first" : undefined}
>
<PencilIcon />
Edit
</Link>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="outline" className="text-destructive hover:bg-destructive/10 hover:text-destructive" />}>
<Trash2Icon />
Delete
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete {d.name}?</AlertDialogTitle>
<AlertDialogDescription>The container is stopped and removed. The model files stay in the library.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={async () => {
if (await deleteDeployment(d.id)) router.push("/deployments");
}}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</CardContent>
</Card>
{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>
)}
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_380px]">
<div className="flex min-w-0 flex-col gap-4">
<Card>
<CardContent className="grid grid-cols-2 gap-4 md:grid-cols-4">
<Stat
label="CPU"
value={d.state === "running" && d.stats ? `${(d.stats.cpuPercent / 100).toFixed(1)} cores` : "–"}
>
<span className="text-xs text-muted-foreground">{d.cpus ? `limit ${d.cpus}` : "no limit"}</span>
</Stat>
<Stat label="Memory" value={d.stats && d.state === "running" ? formatBytes(d.stats.memoryBytes) : "–"}>
{d.stats && d.state === "running" && d.memoryMb ? (
<Progress value={percent(d.stats.memoryBytes, d.memoryMb * 2 ** 20)} />
) : (
<span className="text-xs text-muted-foreground">{d.memoryMb ? `limit ${formatBytes(d.memoryMb * 2 ** 20)}` : "no limit"}</span>
)}
</Stat>
<Stat
label={d.state === "starting" ? "Loading" : "Load time"}
value={startingSecs != null ? `${startingSecs.toFixed(0)} s` : loadSecs != null ? `${loadSecs.toFixed(1)} s` : "–"}
>
<span className="text-xs text-muted-foreground">until /health answered</span>
</Stat>
<Stat label="Context" value={d.options.contextSize.toLocaleString("en-US")}>
<span className="text-xs text-muted-foreground">
{d.engine === "vllm" ? `seqs ${d.options.maxNumSeqs ?? "default"}` : `slots ${d.options.parallel ?? "auto"}`}
</span>
</Stat>
</CardContent>
</Card>
<Logs id={d.id} />
</div>
<div className="flex flex-col gap-4">
<Chat id={d.id} running={d.state === "running"} />
<Card size="sm">
<CardHeader>
<CardTitle>Endpoint</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-2 text-xs">
{internal ? (
<div className="flex items-center justify-between gap-2">
<code className="font-mono break-all">{internal}</code>
<CopyButton value={internal} label="Copy URL" />
</div>
) : (
<span className="text-muted-foreground">Not started yet.</span>
)}
<span className="text-muted-foreground">On the Docker network, for Kaname and other containers.</span>
{published && (
<div className="flex items-center justify-between gap-2 border-t pt-2">
<code className="font-mono break-all">{published}</code>
<CopyButton value={published} label="Copy URL" />
</div>
)}
<span className="text-muted-foreground">
OpenAI-compatible; model name <code className="font-mono">{d.repoId}</code>.
{d.options.requireApiKey && (
<>
{" "}
Requires one of the{" "}
<Link href="/settings/api-keys" className="underline">
API keys
</Link>{" "}
as <code className="font-mono">Authorization: Bearer</code>.
</>
)}
</span>
</CardContent>
</Card>
<Card size="sm">
<CardHeader>
<CardTitle>Details</CardTitle>
</CardHeader>
<CardContent>
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-xs">
<dt className="text-muted-foreground">Container</dt>
<dd className="font-mono break-all">{d.containerName ?? "–"}</dd>
<dt className="text-muted-foreground">Started</dt>
<dd>
<LocalTime value={d.startedAt} />
</dd>
<dt className="text-muted-foreground">Stopped</dt>
<dd>
<LocalTime value={d.stoppedAt} />
</dd>
{d.command && (
<>
<dt className="text-muted-foreground">Arguments</dt>
<dd className="flex items-start gap-1">
<code className="font-mono break-all">{d.command.join(" ")}</code>
<CopyButton value={d.command.join(" ")} label="Copy arguments" />
</dd>
</>
)}
</dl>
</CardContent>
</Card>
</div>
</div>
</div>
);
}
/** Live container log (polls new lines every 1.5 s). */
function Logs({ id }: { id: string }) {
const [lines, setLines] = useState<LogLine[]>([]);
const box = useRef<HTMLDivElement>(null);
const stick = useRef(true);
useEffect(() => {
let last = 0;
let stopped = false;
const load = async () => {
const res = await fetch(`/api/deployments/${id}/logs?after=${last}`, { cache: "no-store" }).catch(() => null);
if (!res?.ok || stopped) return;
const next: LogLine[] = await res.json();
if (next.length === 0) return;
last = next[next.length - 1].id;
setLines((prev) => [...prev, ...next].slice(-2000));
};
void load();
const t = setInterval(load, 1_500);
return () => {
stopped = true;
clearInterval(t);
};
}, [id]);
useEffect(() => {
if (stick.current && box.current) box.current.scrollTop = box.current.scrollHeight;
}, [lines]);
return (
<Card size="sm" className="min-w-0">
<CardHeader>
<CardTitle>Log</CardTitle>
</CardHeader>
<CardContent>
<div
ref={box}
onScroll={(e) => {
const el = e.currentTarget;
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
}}
className="h-96 overflow-auto rounded-lg bg-muted/50 px-3 py-2 font-mono text-[11px] leading-relaxed"
>
{lines.length === 0 ? (
<span className="text-muted-foreground">No output yet.</span>
) : (
lines.map((l) => (
<div key={l.id} className={cn("break-all whitespace-pre-wrap", l.stream === "system" && "text-sky-700 dark:text-sky-300")}>
{l.line}
</div>
))
)}
</div>
</CardContent>
</Card>
);
}
/** Smoke test over the OpenAI API: streams the answer and measures time to first token and speed. */
function Chat({ id, running }: { id: string; running: boolean }) {
const [prompt, setPrompt] = useState("Write one sentence about the sea.");
const [answer, setAnswer] = useState("");
const [busy, setBusy] = useState(false);
const [stats, setStats] = useState<{ ttft: number | null; total: number; tokens: number | null; promptTokens: number | null } | null>(null);
const [error, setError] = useState<string | null>(null);
async function send() {
setBusy(true);
setAnswer("");
setError(null);
setStats(null);
const t0 = performance.now();
let first: number | null = null;
let usage: { completion_tokens?: number; prompt_tokens?: number } | null = null;
let chunks = 0;
try {
const res = await fetch(`/api/deployments/${id}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: [{ role: "user", content: prompt }], maxTokens: 256 }),
});
if (!res.ok || !res.body) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error?.message ?? `HTTP ${res.status}`);
}
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buf = "";
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buf += value;
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim();
buf = buf.slice(nl + 1);
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (data === "[DONE]") continue;
const j = JSON.parse(data);
if (j.usage) usage = j.usage;
const delta: string = j.choices?.[0]?.delta?.content ?? j.choices?.[0]?.delta?.reasoning_content ?? "";
if (delta) {
first ??= performance.now();
chunks++;
setAnswer((a) => a + delta);
}
}
}
const total = (performance.now() - t0) / 1000;
setStats({ ttft: first ? (first - t0) / 1000 : null, total, tokens: usage?.completion_tokens ?? chunks, promptTokens: usage?.prompt_tokens ?? null });
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
const genSecs = stats && stats.ttft != null ? stats.total - stats.ttft : null;
return (
<Card size="sm">
<CardHeader>
<CardTitle>Try it</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-2">
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
rows={3}
disabled={!running}
className="w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50 dark:bg-input/30"
/>
<Button size="sm" onClick={send} disabled={!running || busy || !prompt.trim()} className="self-end">
<SendIcon />
{busy ? "Generating…" : running ? "Send" : "Start the deployment first"}
</Button>
{error && <p className="rounded-md bg-destructive/10 px-2.5 py-2 text-xs text-destructive">{error}</p>}
{answer && <div className="max-h-60 overflow-auto rounded-md bg-muted/50 px-2.5 py-2 text-sm whitespace-pre-wrap">{answer}</div>}
{stats && (
<div className="grid grid-cols-3 gap-2 text-center text-xs">
<div>
<div className="font-semibold tabular-nums">{stats.ttft != null ? `${(stats.ttft * 1000).toFixed(0)} ms` : "–"}</div>
<div className="text-muted-foreground">first token</div>
</div>
<div>
<div className="font-semibold tabular-nums">
{stats.tokens && genSecs && genSecs > 0 ? `${(stats.tokens / genSecs).toFixed(1)} tok/s` : "–"}
</div>
<div className="text-muted-foreground">generation</div>
</div>
<div>
<div className="font-semibold tabular-nums">{stats.tokens ?? "–"}</div>
<div className="text-muted-foreground">tokens in {stats.total.toFixed(1)} s</div>
</div>
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,26 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getDeployment } from "@/lib/deployments";
import { DeploymentForm } from "../../deployment-form";
import { formData } from "../../form-data";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Edit deployment" };
export default async function EditDeploymentPage({ params }: PageProps<"/deployments/[id]/edit">) {
const { id } = await params;
const [d, data] = await Promise.all([getDeployment(id), formData()]);
if (!d) notFound();
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">Edit {d.name}</h1>
{d.state !== "stopped" && d.state !== "failed" && (
<p className="rounded-md bg-amber-500/10 px-3 py-2 text-sm text-amber-800 dark:text-amber-200">Stop the deployment before saving changes.</p>
)}
<DeploymentForm
{...data}
initial={{ id: d.id, name: d.name, runtimeId: d.runtimeId, modelId: d.modelId, options: d.options, cpus: d.cpus, memoryMb: d.memoryMb, hostPort: d.hostPort }}
/>
</div>
);
}
+17
View File
@@ -0,0 +1,17 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getDeployment } from "@/lib/deployments";
import { DeploymentDetail } from "./deployment-detail";
export const dynamic = "force-dynamic";
export async function generateMetadata({ params }: PageProps<"/deployments/[id]">): Promise<Metadata> {
const d = await getDeployment((await params).id);
return { title: d ? d.name : "Deployment" };
}
export default async function DeploymentPage({ params }: PageProps<"/deployments/[id]">) {
const d = await getDeployment((await params).id);
if (!d) notFound();
return <DeploymentDetail initial={JSON.parse(JSON.stringify(d))} />;
}
+15
View File
@@ -0,0 +1,15 @@
"use client";
import { toast } from "sonner";
async function call(url: string, method: string): Promise<boolean> {
const res = await fetch(url, { method });
if (res.ok) return true;
const body = await res.json().catch(() => ({}));
toast.error(body.error?.message ?? `Request failed (${res.status})`);
return false;
}
export const startDeployment = (id: string) => call(`/api/deployments/${id}/start`, "POST");
export const stopDeployment = (id: string) => call(`/api/deployments/${id}/stop`, "POST");
export const deleteDeployment = (id: string) => call(`/api/deployments/${id}`, "DELETE");
@@ -0,0 +1,612 @@
"use client";
import { BoxesIcon, CheckIcon, SearchIcon, TerminalIcon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { ArgsEditor } from "@/components/args-editor";
import { CopyButton } from "@/components/copy-button";
import { FileRoleBadge } from "@/components/labels";
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 { DeploymentOptions, RuntimeEngine } from "@/lib/db/schema";
import type { ModelCandidates } from "@/lib/deploy-candidates";
import { API_KEY_PLACEHOLDER, buildCommand, ENGINE_PORT, estimateMemoryMb, renderCommand } from "@/lib/deploy-command";
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { cn } from "@/lib/utils";
export type FormRuntime = {
id: string;
name: string;
engine: RuntimeEngine;
image: string;
imageState: string;
env: Record<string, string>;
extraArgs: string[];
};
export type FormModel = { id: string; repoId: string; localPath: string; candidates: ModelCandidates };
export type FormHost = { cpus: number | null; memoryBytes: number | null; cpuFeatures: string[] } | null;
export type FormInitial = {
id?: string;
name: string;
runtimeId: string;
modelId: string;
options: DeploymentOptions;
cpus: number | null;
memoryMb: number | null;
hostPort: number | null;
};
const CONTEXT_PRESETS = [2048, 4096, 8192, 16384, 32768];
const KV_TYPES = ["f16", "q8_0", "q4_0"];
const intOrNull = (s: string) => (s.trim() === "" ? null : Math.max(0, Math.round(Number(s)))) || null;
const numOrNull = (s: string) => (s.trim() === "" ? null : Number(s)) || null;
function Section({ step, title, description, children }: { step: number; title: string; description?: string; children: React.ReactNode }) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<span className="grid size-6 place-items-center rounded-full bg-primary text-xs text-primary-foreground">{step}</span>
{title}
</CardTitle>
{description && <CardDescription>{description}</CardDescription>}
</CardHeader>
<CardContent className="flex flex-col gap-4">{children}</CardContent>
</Card>
);
}
/** A titled block of related options inside the launch options card. */
function Group({ title, description, children }: { title: string; description?: string; children: React.ReactNode }) {
return (
<div className="grid gap-3 border-t pt-5 first:border-t-0 first:pt-0 md:grid-cols-[11rem_1fr] md:gap-6">
<div className="flex flex-col gap-0.5">
<h3 className="text-sm font-medium">{title}</h3>
{description && <p className="text-xs text-muted-foreground">{description}</p>}
</div>
<div className="grid content-start gap-4 sm:grid-cols-2">{children}</div>
</div>
);
}
/** `flag`: the command-line flag the field sets, shown next to the label. */
function Field({
label,
flag,
hint,
children,
htmlFor,
wide,
}: {
label: string;
flag?: string;
hint?: React.ReactNode;
children: React.ReactNode;
htmlFor?: string;
wide?: boolean;
}) {
return (
<div className={cn("flex flex-col gap-1.5", wide && "sm:col-span-2")}>
<div className="flex items-baseline justify-between gap-2">
<Label htmlFor={htmlFor}>{label}</Label>
{flag && <code className="font-mono text-[11px] text-muted-foreground">{flag}</code>}
</div>
{children}
{hint && <p className="text-xs text-muted-foreground">{hint}</p>}
</div>
);
}
/** Pick runtime → model and files → launch options. Used for "New deployment" and "Edit". */
export function DeploymentForm({
runtimes,
models,
host,
apiKeyCount,
initial,
}: {
runtimes: FormRuntime[];
models: FormModel[];
host: FormHost;
apiKeyCount: number;
initial?: FormInitial;
}) {
const router = useRouter();
const editing = !!initial?.id;
const [runtimeId, setRuntimeId] = useState(initial?.runtimeId ?? runtimes.find((r) => r.imageState === "present")?.id ?? "");
const runtime = runtimes.find((r) => r.id === runtimeId) ?? null;
const engine = runtime?.engine ?? "llama.cpp";
const [query, setQuery] = useState("");
const [modelId, setModelId] = useState(initial?.modelId ?? "");
const servable = models.filter((m) => (engine === "llama.cpp" ? m.candidates.gguf.length > 0 : m.candidates.vllm));
const shown = servable.filter((m) => m.repoId.toLowerCase().includes(query.trim().toLowerCase()));
const model = servable.find((m) => m.id === modelId) ?? null;
const o = initial?.options;
const [modelFile, setModelFile] = useState(o?.modelFile ?? "");
const [mmproj, setMmproj] = useState(o?.mmproj ?? "");
const [draftFile, setDraftFile] = useState(o?.draftFile ?? "");
const [name, setName] = useState(initial?.name ?? "");
const [contextSize, setContextSize] = useState(String(o?.contextSize ?? 4096));
const [threads, setThreads] = useState(o?.threads != null ? String(o.threads) : "");
const [parallel, setParallel] = useState(o?.parallel != null ? String(o.parallel) : "1");
const [cacheTypeK, setCacheTypeK] = useState(o?.cacheTypeK ?? "");
const [cacheTypeV, setCacheTypeV] = useState(o?.cacheTypeV ?? "");
const [flashAttn, setFlashAttn] = useState(o?.flashAttn ?? "");
const [webui, setWebui] = useState(o?.webui !== false);
const [requireApiKey, setRequireApiKey] = useState(!!o?.requireApiKey);
const [batchSize, setBatchSize] = useState(o?.batchSize != null ? String(o.batchSize) : "");
const [ubatchSize, setUbatchSize] = useState(o?.ubatchSize != null ? String(o.ubatchSize) : "");
const [dtype, setDtype] = useState(o?.dtype ?? "");
const [maxNumSeqs, setMaxNumSeqs] = useState(o?.maxNumSeqs != null ? String(o.maxNumSeqs) : "");
const [kvCacheGb, setKvCacheGb] = useState(o?.kvCacheGb != null ? String(o.kvCacheGb) : "");
const [argRows, setArgRows] = useState(() => argsToRows(o?.extraArgs ?? []));
const [cpus, setCpus] = useState(initial?.cpus != null ? String(initial.cpus) : "");
const [memoryMb, setMemoryMb] = useState(initial?.memoryMb != null ? String(initial.memoryMb) : "");
const [memoryTouched, setMemoryTouched] = useState(!!initial?.memoryMb);
const [hostPort, setHostPort] = useState(initial?.hostPort != null ? String(initial.hostPort) : "");
const [saving, setSaving] = useState(false);
function pickModel(m: FormModel) {
setModelId(m.id);
const first = m.candidates.gguf[0];
setModelFile(engine === "llama.cpp" ? (first?.path ?? "") : "");
setMmproj(m.candidates.mmproj[0]?.path ?? "");
setDraftFile("");
if (!editing) setName(`${m.repoId.split("/")[1]}${first && engine === "llama.cpp" ? ` ${quantGroup(first.path) ?? ""}` : ""}`.trim());
}
const options: DeploymentOptions = {
modelFile: engine === "llama.cpp" ? modelFile : "",
mmproj: engine === "llama.cpp" && mmproj ? mmproj : null,
draftFile: engine === "llama.cpp" && draftFile ? draftFile : null,
draftType: model?.candidates.drafts.find((d) => d.path === draftFile)?.type ?? null,
contextSize: intOrNull(contextSize) ?? 4096,
threads: intOrNull(threads),
parallel: intOrNull(parallel),
batchSize: engine === "llama.cpp" ? intOrNull(batchSize) : null,
ubatchSize: engine === "llama.cpp" ? intOrNull(ubatchSize) : null,
cacheTypeK: engine === "llama.cpp" && cacheTypeK ? cacheTypeK : null,
cacheTypeV: engine === "llama.cpp" && cacheTypeV ? cacheTypeV : null,
flashAttn: engine === "llama.cpp" && flashAttn ? (flashAttn as "auto" | "on" | "off") : null,
webui: engine === "llama.cpp" ? webui : null,
requireApiKey,
dtype: engine === "vllm" && dtype ? dtype : null,
maxNumSeqs: engine === "vllm" ? intOrNull(maxNumSeqs) : null,
kvCacheGb: engine === "vllm" ? numOrNull(kvCacheGb) : null,
extraArgs: rowsToArgs(argRows),
};
const fileBytes = model
? engine === "llama.cpp"
? (model.candidates.gguf.find((g) => g.path === modelFile)?.size ?? 0) +
(model.candidates.mmproj.find((g) => g.path === mmproj)?.size ?? 0) +
(model.candidates.drafts.find((g) => g.path === draftFile)?.size ?? 0)
: (model.candidates.vllm?.size ?? 0)
: 0;
const estimate = model ? estimateMemoryMb(fileBytes, options.contextSize, engine, options.kvCacheGb) : null;
const memory = memoryTouched ? intOrNull(memoryMb) : estimate;
const preview =
runtime && model ? renderCommand(runtime.image, buildCommand({
engine,
options,
model,
runtime: { env: runtime.env, extraArgs: runtime.extraArgs },
apiKeys: Array.from({ length: apiKeyCount }, () => API_KEY_PLACEHOLDER),
})) : null;
const noBf16 = host && !host.cpuFeatures.includes("avx512_bf16");
async function submit(start: boolean) {
if (!runtime || !model) return;
setSaving(true);
try {
const body = {
name: name.trim() || model.repoId,
runtimeId: runtime.id,
modelId: model.id,
options,
cpus: numOrNull(cpus),
memoryMb: memory,
hostPort: intOrNull(hostPort),
start,
};
const res = await fetch(editing ? `/api/deployments/${initial!.id}` : "/api/deployments", {
method: editing ? "PUT" : "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not save (${res.status})`);
return;
}
const id = editing ? initial!.id : json.id;
if (editing && start) await fetch(`/api/deployments/${id}/start`, { method: "POST" });
toast.success(start ? "Deployment starting" : "Deployment saved");
router.push(`/deployments/${id}`);
router.refresh();
} finally {
setSaving(false);
}
}
return (
<div className="flex flex-col gap-4">
<Section step={1} title="Runtime" description="The container image that serves the model.">
{runtimes.length === 0 ? (
<p className="text-sm text-muted-foreground">
No runtimes yet.{" "}
<Link href="/settings/runtimes" className="underline">
Add one in Settings
</Link>
.
</p>
) : (
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
{runtimes.map((r) => {
const ready = r.imageState === "present";
return (
<button
key={r.id}
type="button"
disabled={!ready}
onClick={() => {
setRuntimeId(r.id);
if (r.engine !== engine) setModelId("");
}}
className={cn(
"flex flex-col items-start gap-1 rounded-lg border px-3 py-2.5 text-left transition-colors disabled:cursor-not-allowed disabled:opacity-50",
runtimeId === r.id ? "border-primary bg-primary/5 ring-1 ring-primary" : "hover:bg-muted/50",
)}
>
<span className="flex w-full items-center justify-between gap-2 text-sm font-medium">
<span className="flex items-center gap-1.5">
<BoxesIcon className="size-4 text-muted-foreground" />
{r.name}
</span>
{runtimeId === r.id && <CheckIcon className="size-4 text-primary" />}
</span>
<code className="font-mono text-xs break-all text-muted-foreground">{r.image}</code>
<span className="text-xs text-muted-foreground">
{r.engine === "vllm" ? "vLLM · safetensors" : "llama.cpp · GGUF"}
{!ready && " · image not pulled"}
</span>
</button>
);
})}
</div>
)}
{runtimes.some((r) => r.imageState !== "present") && (
<p className="text-xs text-muted-foreground">
Runtimes whose image isn&apos;t pulled yet can&apos;t be picked.{" "}
<Link href="/settings/runtimes" className="underline">
Pull them in Settings
</Link>
.
</p>
)}
</Section>
{runtime && (
<Section
step={2}
title="Model"
description={engine === "llama.cpp" ? "Downloaded GGUF models. Pick the quant and optional extras." : "Downloaded safetensors repos (with config.json)."}
>
{servable.length === 0 ? (
<p className="text-sm text-muted-foreground">
No downloaded model fits this runtime.{" "}
<Link href="/" className="underline">
Add one in the library
</Link>
{engine === "vllm" ? " (a safetensors repo, e.g. HuggingFaceTB/SmolLM2-135M-Instruct)." : "."}
</p>
) : (
<>
{servable.length > 6 && (
<div className="relative">
<SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<Input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search models…" className="pl-8" />
</div>
)}
<div className="flex max-h-72 flex-col divide-y overflow-y-auto rounded-lg ring-1 ring-foreground/10">
{shown.map((m) => (
<button
key={m.id}
type="button"
onClick={() => pickModel(m)}
className={cn("flex items-center justify-between gap-3 px-3 py-2 text-left text-sm hover:bg-muted/50", modelId === m.id && "bg-primary/5")}
>
<span className="flex min-w-0 items-center gap-2">
{modelId === m.id ? <CheckIcon className="size-4 shrink-0 text-primary" /> : <span className="size-4 shrink-0" />}
<span className="truncate">{m.repoId}</span>
</span>
<span className="shrink-0 text-xs text-muted-foreground">
{engine === "llama.cpp"
? `${m.candidates.gguf.length} GGUF${m.candidates.mmproj.length ? " · vision" : ""}${m.candidates.drafts.length ? " · MTP/draft" : ""}`
: formatBytes(m.candidates.vllm?.size ?? 0)}
</span>
</button>
))}
</div>
{model && engine === "llama.cpp" && (
<div className="grid gap-4 md:grid-cols-3">
<Field label="Model file" flag="-m">
<div className="flex flex-col gap-1">
{model.candidates.gguf.map((g) => (
<label key={g.path} className={cn("flex cursor-pointer items-center gap-2 rounded-md border px-2 py-1.5 text-xs", modelFile === g.path && "border-primary bg-primary/5")}>
<input type="radio" name="modelFile" checked={modelFile === g.path} onChange={() => setModelFile(g.path)} className="accent-primary" />
<span className="min-w-0 flex-1 truncate font-mono" title={g.path}>
{quantGroup(g.path) ?? g.path}
</span>
<span className="text-muted-foreground tabular-nums">{formatBytes(g.size)}</span>
</label>
))}
</div>
</Field>
<Field label="Vision (mmproj)" flag="--mmproj" hint={model.candidates.mmproj.length === 0 ? "None downloaded." : "Needed for image input."}>
<NativeSelect value={mmproj} onChange={(e) => setMmproj(e.target.value)} disabled={model.candidates.mmproj.length === 0}>
<option value="">None</option>
{model.candidates.mmproj.map((m) => (
<option key={m.path} value={m.path}>
{m.path} ({formatBytes(m.size)})
</option>
))}
</NativeSelect>
</Field>
<Field
label="Speculative decoding"
flag="-md"
hint={model.candidates.drafts.length === 0 ? "No MTP head or draft model downloaded." : "Faster generation with an MTP head or draft model."}
>
<NativeSelect value={draftFile} onChange={(e) => setDraftFile(e.target.value)} disabled={model.candidates.drafts.length === 0}>
<option value="">Off</option>
{model.candidates.drafts.map((d) => (
<option key={d.path} value={d.path}>
{d.type === "draft-mtp" ? "MTP: " : "Draft: "}
{d.path} ({formatBytes(d.size)})
</option>
))}
</NativeSelect>
</Field>
</div>
)}
{model && (
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
{[modelFile, mmproj, draftFile].filter(Boolean).map((p) => (
<span key={p} className="flex items-center gap-1">
<FileRoleBadge path={p} />
</span>
))}
<span>{formatBytes(fileBytes)} of model files</span>
</div>
)}
</>
)}
</Section>
)}
{runtime && model && (
<Section step={3} title="Launch options" description="Empty fields use the engine's defaults.">
<Group title="General" description="Name and how to reach the server.">
<Field label="Name" htmlFor="d-name">
<Input id="d-name" value={name} onChange={(e) => setName(e.target.value)} maxLength={80} />
</Field>
<Field label="Host port" htmlFor="d-port" hint={`Publishes container port ${ENGINE_PORT[engine]}; empty: only reachable inside Docker.`}>
<Input id="d-port" value={hostPort} onChange={(e) => setHostPort(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="not published" />
</Field>
<label className="flex cursor-pointer items-start gap-2.5 text-sm sm:col-span-2">
<Checkbox checked={requireApiKey} onCheckedChange={(v) => setRequireApiKey(v === true)} className="mt-0.5" disabled={apiKeyCount === 0 && !requireApiKey} />
<span className="flex flex-col gap-0.5">
<span>Require an API key</span>
<span className="text-xs text-muted-foreground">
{apiKeyCount === 0 ? (
<>
No keys yet.{" "}
<Link href="/settings/api-keys" className="underline">
Add one in Settings
</Link>
.
</>
) : (
<>
Accepts any of the {apiKeyCount} key{apiKeyCount === 1 ? "" : "s"} from{" "}
<Link href="/settings/api-keys" className="underline">
Settings → API keys
</Link>{" "}
as <code className="font-mono">Authorization: Bearer</code>.{engine === "vllm" ? " vLLM only checks /v1 paths." : ""}
</>
)}
</span>
</span>
</label>
{engine === "llama.cpp" && (
<label className="flex cursor-pointer items-start gap-2.5 text-sm sm:col-span-2">
<Checkbox checked={webui} onCheckedChange={(v) => setWebui(v === true)} className="mt-0.5" />
<span className="flex flex-col gap-0.5">
<span>Serve the llama.cpp web UI</span>
<span className="text-xs text-muted-foreground">
{webui
? hostPort
? `Opens at http://<server>:${hostPort}/ (no login on that port).`
: "Set a host port to open it."
: "Off: passes --no-webui; the API keeps working."}
</span>
</span>
</label>
)}
</Group>
<Group title="Context" description="How much text the model sees and how many requests run at once.">
<Field label="Context size (tokens)" flag={engine === "vllm" ? "--max-model-len" : "-c"} htmlFor="d-ctx" wide>
<div className="flex flex-wrap items-center gap-1.5">
<Input id="d-ctx" value={contextSize} onChange={(e) => setContextSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-28" />
{CONTEXT_PRESETS.map((c) => (
<Button key={c} type="button" size="xs" variant={Number(contextSize) === c ? "default" : "outline"} onClick={() => setContextSize(String(c))}>
{c / 1024}k
</Button>
))}
</div>
</Field>
{engine === "vllm" ? (
<Field label="Max concurrent sequences" flag="--max-num-seqs" htmlFor="d-par">
<Input id="d-par" value={maxNumSeqs} onChange={(e) => setMaxNumSeqs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="default" />
</Field>
) : (
<Field label="Parallel slots" flag="-np" htmlFor="d-par" hint="The context is split between slots.">
<Input id="d-par" value={parallel} onChange={(e) => setParallel(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="auto" />
</Field>
)}
</Group>
{engine === "llama.cpp" ? (
<Group title="Performance" description="CPU threads and prompt processing.">
<Field label="Threads" flag="-t / -tb" htmlFor="d-thr" hint={host?.cpus ? `Host has ${host.cpus} threads.` : undefined}>
<Input id="d-thr" value={threads} onChange={(e) => setThreads(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="auto" />
</Field>
<Field label="Flash attention" flag="-fa" htmlFor="d-fa">
<NativeSelect id="d-fa" value={flashAttn} onChange={(e) => setFlashAttn(e.target.value)}>
<option value="">auto</option>
<option value="on">on</option>
<option value="off">off</option>
</NativeSelect>
</Field>
<Field label="Batch size" flag="-b" htmlFor="d-b">
<Input id="d-b" value={batchSize} onChange={(e) => setBatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="2048" />
</Field>
<Field label="Micro-batch size" flag="-ub" htmlFor="d-ub">
<Input id="d-ub" value={ubatchSize} onChange={(e) => setUbatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="512" />
</Field>
</Group>
) : (
<Group title="Performance" description="vLLM binds its CPU threads itself; limit cores under Resources.">
<Field
label="Data type"
flag="--dtype"
htmlFor="d-dtype"
hint={noBf16 ? "This CPU has no AVX-512 BF16; float32 is likely faster." : "Overrides the runtime's default."}
>
<NativeSelect id="d-dtype" value={dtype} onChange={(e) => setDtype(e.target.value)}>
<option value="">runtime default</option>
<option value="bfloat16">bfloat16</option>
<option value="float32">float32</option>
<option value="float16">float16</option>
<option value="auto">auto</option>
</NativeSelect>
</Field>
</Group>
)}
<Group title="KV cache" description="Memory for the context of running requests.">
{engine === "llama.cpp" ? (
<>
<Field label="K type" flag="-ctk" htmlFor="d-ctk" hint="q8_0 halves the memory.">
<NativeSelect id="d-ctk" value={cacheTypeK} onChange={(e) => setCacheTypeK(e.target.value)}>
<option value="">f16 (default)</option>
{KV_TYPES.filter((t) => t !== "f16").map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</NativeSelect>
</Field>
<Field label="V type" flag="-ctv" htmlFor="d-ctv">
<NativeSelect id="d-ctv" value={cacheTypeV} onChange={(e) => setCacheTypeV(e.target.value)}>
<option value="">f16 (default)</option>
{KV_TYPES.filter((t) => t !== "f16").map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</NativeSelect>
</Field>
</>
) : (
<Field label="KV cache size (GiB)" flag="VLLM_CPU_KVCACHE_SPACE" htmlFor="d-kv" hint="Reserved up front; must fit in the memory limit.">
<Input id="d-kv" value={kvCacheGb} onChange={(e) => setKvCacheGb(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder={runtime.env.VLLM_CPU_KVCACHE_SPACE ?? "4"} />
</Field>
)}
</Group>
<Group title="Resources" description="Container limits.">
<Field label="CPU cores" htmlFor="d-cpus" hint={host?.cpus ? `Empty: no limit (host: ${host.cpus}).` : "Empty: no limit."}>
<Input id="d-cpus" value={cpus} onChange={(e) => setCpus(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder="no limit" />
</Field>
<Field
label="Memory (MiB)"
htmlFor="d-mem"
hint={
<>
Estimate: {estimate != null ? formatBytes(estimate * 2 ** 20) : "–"}
{host?.memoryBytes ? ` · host: ${formatBytes(host.memoryBytes)}` : ""}
{memoryTouched && (
<button type="button" className="ml-1 underline" onClick={() => setMemoryTouched(false)}>
use estimate
</button>
)}
</>
}
>
<Input
id="d-mem"
value={memoryTouched ? memoryMb : String(estimate ?? "")}
onChange={(e) => {
setMemoryTouched(true);
setMemoryMb(e.target.value.replace(/\D/g, ""));
}}
inputMode="numeric"
/>
</Field>
</Group>
<Group
title="Extra arguments"
description={`Any other ${engine === "vllm" ? "vllm serve" : "llama-server"} flag. Added after the runtime's own arguments.`}
>
<div className="sm:col-span-2">
<ArgsEditor rows={argRows} onChange={setArgRows} placeholder={engine === "vllm" ? { flag: "--enforce-eager", value: "value (optional)" } : { flag: "--temp", value: "0.7" }} />
</div>
</Group>
</Section>
)}
{runtime && model && (
<Section step={4} title="Command" description="What Kaname runs, including the runtime's environment and arguments.">
{preview && (
<div className="relative">
<pre className="overflow-x-auto rounded-lg bg-muted/60 py-2.5 pr-12 pl-3 font-mono text-xs break-all whitespace-pre-wrap">
<TerminalIcon className="mr-1.5 inline size-3.5 align-[-2px] text-muted-foreground" />
{preview}
</pre>
<div className="absolute top-1.5 right-1.5">
<CopyButton value={preview} label="Copy command" />
</div>
</div>
)}
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={() => router.back()}>
Cancel
</Button>
<Button type="button" variant="outline" disabled={saving || (engine === "llama.cpp" && !modelFile)} onClick={() => submit(false)}>
{editing ? "Save" : "Create"}
</Button>
<Button type="button" disabled={saving || (engine === "llama.cpp" && !modelFile)} onClick={() => submit(true)}>
{editing ? "Save & start" : "Create & start"}
</Button>
</div>
</Section>
)}
</div>
);
}
@@ -0,0 +1,107 @@
"use client";
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 { Button, buttonVariants } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { startDeployment, stopDeployment } from "./actions";
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";
/** 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);
const hostname = useHostname();
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);
if (res?.ok) setRows(await res.json());
}
useEffect(() => {
const t = setInterval(reload, busy ? 2_000 : 5_000);
return () => clearInterval(t);
}, [busy]);
if (rows.length === 0) {
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>
<Link href="/deployments/new" className="text-sm underline">
New deployment
</Link>
</Card>
);
}
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>
<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>
);
}
+16
View File
@@ -0,0 +1,16 @@
import "server-only";
import { listApiKeys } from "@/lib/api-keys";
import { listDeployableModels } from "@/lib/deployments";
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
import type { FormHost, FormModel, FormRuntime } from "./deployment-form";
/** Everything the deployment form needs: runtimes, servable models, host facts, API key count. */
export async function formData(): Promise<{ runtimes: FormRuntime[]; models: FormModel[]; host: FormHost; apiKeyCount: number }> {
const [runtimes, models, docker, keys] = await Promise.all([listRuntimes(), listDeployableModels(), getDockerInfo(), listApiKeys()]);
return {
runtimes: runtimes.map((r) => ({ id: r.id, name: r.name, engine: r.engine, image: r.image, imageState: r.imageState, env: r.env, extraArgs: r.extraArgs })),
models,
host: docker ? { cpus: docker.cpus, memoryBytes: docker.memoryBytes, cpuFeatures: docker.cpuFeatures } : null,
apiKeyCount: keys.length,
};
}
+19
View File
@@ -0,0 +1,19 @@
import type { Metadata } from "next";
import { deployPreset } from "@/lib/deployments";
import { DeploymentForm } from "../deployment-form";
import { formData } from "../form-data";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "New deployment" };
/** `?model=<id>` (the library's "Deploy") preselects the model and a runtime that can serve it. */
export default async function NewDeploymentPage({ searchParams }: PageProps<"/deployments/new">) {
const { model } = await searchParams;
const [data, preset] = await Promise.all([formData(), typeof model === "string" ? deployPreset(model) : null]);
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">New deployment</h1>
<DeploymentForm {...data} initial={preset ?? undefined} />
</div>
);
}
+33
View File
@@ -0,0 +1,33 @@
import type { Metadata } from "next";
import Link from "next/link";
import { buttonVariants } from "@/components/ui/button";
import { listDeployments } from "@/lib/deployments";
import { getDockerInfo } from "@/lib/runtimes";
import { DeploymentList } from "./deployment-list";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Deployments" };
export default async function DeploymentsPage() {
const [rows, docker] = await Promise.all([listDeployments(), getDockerInfo()]);
return (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold">Deployments</h1>
<Link href="/deployments/new" className={buttonVariants()}>
New deployment
</Link>
</div>
{!docker?.connected && (
<p className="rounded-lg bg-amber-500/10 px-4 py-3 text-sm text-amber-800 dark:text-amber-200">
{docker ? `Docker isn't reachable: ${docker.error}` : "Docker isn't connected, so deployments can't start."} See{" "}
<Link href="/settings/runtimes" className="underline">
Settings → Runtimes
</Link>
.
</p>
)}
<DeploymentList rows={JSON.parse(JSON.stringify(rows))} />
</div>
);
}
+36 -2
View File
@@ -1,6 +1,6 @@
"use client";
import { SearchIcon, XIcon } from "lucide-react";
import { RocketIcon, SearchIcon, XIcon } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useMemo, useState } from "react";
@@ -10,7 +10,7 @@ import { HUB_STATE_LABEL, HubStateBadge } from "@/components/hub-state-badge";
import { MODEL_STATUS, ModelStatusBadge } from "@/components/model-status-badge";
import { TagBadge, TagDot } from "@/components/tag-badge";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
@@ -19,6 +19,7 @@ import type { ModelStatus } from "@/lib/db/schema";
import { formatBytes, shortSha } from "@/lib/format";
import type { JobSnapshot } from "@/lib/jobs";
import type { LibraryRow } from "@/lib/library";
import { cn } from "@/lib/utils";
import {
EMPTY_FILTERS,
type Facet,
@@ -180,6 +181,9 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
<TableHead className="hidden lg:table-cell">Pinned</TableHead>
<TableHead className="hidden md:table-cell">Downloaded</TableHead>
<TableHead className="w-56">Status</TableHead>
<TableHead className="w-24">
<span className="sr-only">Deploy</span>
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -195,6 +199,23 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
{base && base !== r.repoId && <span>base {base}</span>}
{r.architecture && <span>{r.architecture}</span>}
{r.deployments.map((d) => (
<Link
key={d.id}
href={`/deployments/${d.id}`}
title={`Deployment "${d.name}" (${d.runtimeName}): ${d.state}`}
className="inline-flex items-center gap-1 rounded-4xl border border-foreground/15 px-1.5 leading-4 hover:bg-muted"
>
<RocketIcon className="size-3" />
<span className="max-w-40 truncate">{d.name}</span>
<span
className={cn(
"size-1.5 rounded-full",
d.state === "running" ? "bg-emerald-500" : d.state === "failed" ? "bg-destructive" : d.state === "stopped" ? "bg-foreground/25" : "bg-amber-500",
)}
/>
</Link>
))}
{r.tags.map((t) => (
<button
key={t.id}
@@ -236,6 +257,19 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
</span>
)}
</TableCell>
<TableCell>
{r.deployable && (
<Link
href={`/deployments/new?model=${r.id}`}
className={buttonVariants({ variant: "outline", size: "xs" })}
title="Serve this model with a runtime"
aria-label={`Deploy ${r.repoId}`}
>
<RocketIcon />
Deploy
</Link>
)}
</TableCell>
</TableRow>
);
})}
@@ -0,0 +1,172 @@
"use client";
import { EyeIcon, EyeOffIcon, KeyRoundIcon, PlusIcon, Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { CopyButton } from "@/components/copy-button";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import type { ApiKeyRow } from "@/lib/api-keys";
/** Keys that deployments with "Require an API key" accept. */
export function ApiKeySettings({ keys }: { keys: ApiKeyRow[] }) {
const [created, setCreated] = useState<{ name: string; key: string } | null>(null);
return (
<Card>
<CardHeader>
<CardTitle>API keys</CardTitle>
<CardDescription>
Deployments with &ldquo;Require an API key&rdquo; accept any of these keys as <code className="font-mono text-xs">Authorization: Bearer &lt;key&gt;</code>.
Changes apply when a deployment (re)starts.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<NewKeyRow 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">API key &ldquo;{created.name}&rdquo; added. You can show it again from the list.</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.key}</code>
<CopyButton value={created.key} label="Copy API key" />
</div>
</div>
)}
{keys.length === 0 ? (
<p className="text-sm text-muted-foreground">No API keys yet.</p>
) : (
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{keys.map((k) => (
<KeyRow key={k.id} apiKey={k} />
))}
</div>
)}
</CardContent>
</Card>
);
}
function NewKeyRow({ onCreated }: { onCreated: (k: { name: string; key: string }) => void }) {
const router = useRouter();
const [name, setName] = useState("");
const [key, setKey] = useState("");
const [busy, setBusy] = useState(false);
async function create(e: React.FormEvent) {
e.preventDefault();
if (!name.trim()) return;
setBusy(true);
try {
const res = await fetch("/api/api-keys", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, key: key.trim() || undefined }),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not add the key (${res.status})`);
return;
}
onCreated({ name: json.name, key: json.key });
setName("");
setKey("");
router.refresh();
} finally {
setBusy(false);
}
}
return (
<form onSubmit={create} className="grid items-center gap-2 rounded-lg border border-dashed px-4 py-3 sm:grid-cols-[minmax(0,12rem)_minmax(0,1fr)_auto]">
<Input value={name} maxLength={80} disabled={busy} onChange={(e) => setName(e.target.value)} placeholder="Name, e.g. Open WebUI" aria-label="Key name" />
<Input
value={key}
maxLength={256}
disabled={busy}
onChange={(e) => setKey(e.target.value.replace(/\s/g, ""))}
placeholder="Key (empty: generate one)"
aria-label="Key value"
spellCheck={false}
autoComplete="off"
className="font-mono text-xs md:text-xs"
/>
<Button type="submit" size="sm" disabled={busy || !name.trim()}>
<PlusIcon />
Add
</Button>
</form>
);
}
function KeyRow({ apiKey }: { apiKey: ApiKeyRow }) {
const router = useRouter();
const [shown, setShown] = useState<string | null>(null);
async function toggle() {
if (shown) return setShown(null);
const res = await fetch(`/api/api-keys/${apiKey.id}`, { cache: "no-store" });
const json = await res.json().catch(() => ({}));
if (!res.ok) toast.error(json.error?.message ?? `Could not load the key (${res.status})`);
else setShown(json.key);
}
async function remove() {
const res = await fetch(`/api/api-keys/${apiKey.id}`, { method: "DELETE" });
if (!res.ok) toast.error(`Could not delete (${res.status})`);
else toast.success(`API key "${apiKey.name}" deleted`);
router.refresh();
}
return (
<div className="flex items-center gap-3 px-4 py-2.5">
<KeyRoundIcon className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate text-sm">{apiKey.name}</span>
{shown ? (
<span className="flex max-w-[60%] min-w-0 items-center gap-1">
<code className="min-w-0 truncate rounded-md bg-muted px-1.5 py-0.5 font-mono text-xs" title={shown}>
{shown}
</code>
<CopyButton value={shown} label="Copy API key" />
</span>
) : (
<code className="font-mono text-xs text-muted-foreground">{apiKey.hint}</code>
)}
<Button variant="ghost" size="icon-sm" onClick={toggle} aria-label={shown ? "Hide key" : "Show key"} title={shown ? "Hide key" : "Show key"}>
{shown ? <EyeOffIcon /> : <EyeIcon />}
</Button>
<span className="hidden text-xs text-muted-foreground sm:inline">
<LocalTime value={apiKey.createdAt} />
</span>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="ghost" size="icon-sm" aria-label={`Delete API key ${apiKey.name}`} />}>
<Trash2Icon />
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete API key &ldquo;{apiKey.name}&rdquo;?</AlertDialogTitle>
<AlertDialogDescription>Clients using it are rejected once their deployments restart.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove}>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
import type { Metadata } from "next";
import { listApiKeys } from "@/lib/api-keys";
import { ApiKeySettings } from "./api-key-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "API keys · Settings" };
export default async function ApiKeySettingsPage() {
return <ApiKeySettings keys={await listApiKeys()} />;
}
+3 -1
View File
@@ -1,10 +1,12 @@
import { DownloadIcon, TagIcon, TagsIcon } from "lucide-react";
import { BoxesIcon, DownloadIcon, KeyRoundIcon, TagIcon, TagsIcon } from "lucide-react";
import { SettingsNav } from "./settings-nav";
const SECTIONS = [
{ href: "/settings/labels", label: "File labels", icon: <TagIcon className="size-4" /> },
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
{ href: "/settings/runtimes", label: "Runtimes", icon: <BoxesIcon className="size-4" /> },
{ href: "/settings/api-keys", label: "API keys", icon: <KeyRoundIcon className="size-4" /> },
];
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
+12
View File
@@ -0,0 +1,12 @@
import type { Metadata } from "next";
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
import { getWorkerStatus } from "@/lib/worker-status";
import { RuntimesView } from "./runtimes-view";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Runtimes · Settings" };
export default async function RuntimesPage() {
const [runtimes, docker, worker] = await Promise.all([listRuntimes(), getDockerInfo(), getWorkerStatus()]);
return <RuntimesView runtimes={runtimes} docker={docker} workerOnline={worker.online} />;
}
@@ -0,0 +1,180 @@
"use client";
import { useState } from "react";
import { ArgsEditor } from "@/components/args-editor";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { RuntimeEngine } from "@/lib/db/schema";
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
import { formatEnvLines, parseEnvLines, type RuntimeInput, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
import { cn } from "@/lib/utils";
const ENGINES: { id: RuntimeEngine; label: string; hint: string }[] = [
{ id: "llama.cpp", label: "llama.cpp-compatible", hint: "llama-server command line, GGUF models" },
{ id: "vllm", label: "vLLM-compatible", hint: "vllm serve command line, safetensors models" },
];
const textareaClass =
"min-h-20 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 font-mono text-xs outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30";
/** Create/edit a runtime. Validates locally with the same rules as the server. */
export function RuntimeForm({
initial,
submitLabel,
onSubmit,
onCancel,
}: {
initial: RuntimeInput;
submitLabel: string;
onSubmit: (value: RuntimeInput) => Promise<boolean>;
onCancel: () => void;
}) {
const [name, setName] = useState(initial.name);
const [engine, setEngine] = useState<RuntimeEngine>(initial.engine);
const [image, setImage] = useState(initial.image);
const [description, setDescription] = useState(initial.description ?? "");
const [envText, setEnvText] = useState(formatEnvLines(initial.env ?? {}));
const [argRows, setArgRows] = useState(() => argsToRows(initial.extraArgs ?? []));
const [devicesText, setDevicesText] = useState((initial.devices ?? []).join(", "));
const [shm, setShm] = useState(initial.shmSizeMb != null ? String(initial.shmSizeMb) : "");
const [numa, setNuma] = useState(!!initial.numaTuning);
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
async function submit(e: React.FormEvent) {
e.preventDefault();
let value: RuntimeInput;
try {
value = validateRuntime({
name,
engine,
image,
description,
env: parseEnvLines(envText),
extraArgs: rowsToArgs(argRows),
devices: devicesText.split(/[,\s]+/),
shmSizeMb: shm.trim() ? Number(shm) : null,
numaTuning: numa,
});
} catch (err) {
setError(err instanceof RuntimeValidationError ? err.message : String(err));
return;
}
setError(null);
setSaving(true);
try {
await onSubmit(value);
} finally {
setSaving(false);
}
}
return (
<form onSubmit={submit} className="flex flex-col gap-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-name">Name</Label>
<Input id="rt-name" value={name} onChange={(e) => setName(e.target.value)} maxLength={60} placeholder="vLLM XPU (Arc patches)" />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-image">Image</Label>
<Input
id="rt-image"
value={image}
onChange={(e) => setImage(e.target.value)}
spellCheck={false}
className="font-mono text-xs"
placeholder="registry.example.com/org/image:tag"
/>
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label>Engine type</Label>
<div className="grid gap-2 sm:grid-cols-2">
{ENGINES.map((e) => (
<button
key={e.id}
type="button"
onClick={() => setEngine(e.id)}
className={cn(
"flex flex-col items-start rounded-lg border px-3 py-2 text-left text-sm transition-colors",
engine === e.id ? "border-primary bg-primary/5" : "hover:bg-muted/50",
)}
>
<span className="font-medium">{e.label}</span>
<span className="text-xs text-muted-foreground">{e.hint}</span>
</button>
))}
</div>
<p className="text-xs text-muted-foreground">
Decides how Kaname builds the command line. Forks with the same CLI (e.g. patched vLLM builds) use the same type.
</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-desc">Description</Label>
<Input id="rt-desc" value={description} onChange={(e) => setDescription(e.target.value)} maxLength={2000} />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-env">Environment</Label>
<textarea
id="rt-env"
value={envText}
onChange={(e) => setEnvText(e.target.value)}
spellCheck={false}
className={textareaClass}
placeholder={"VLLM_CPU_KVCACHE_SPACE=4"}
/>
<p className="text-xs text-muted-foreground">One KEY=value per line.</p>
</div>
<div className="flex flex-col gap-1.5">
<Label>Extra arguments</Label>
<ArgsEditor rows={argRows} onChange={setArgRows} placeholder={engine === "vllm" ? { flag: "--dtype", value: "bfloat16" } : { flag: "--temp", value: "0.7" }} />
<p className="text-xs text-muted-foreground">Added to every deployment&apos;s command; a deployment can override them.</p>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-shm">Shared memory (MiB)</Label>
<Input id="rt-shm" value={shm} onChange={(e) => setShm(e.target.value.replace(/[^\d]/g, ""))} inputMode="numeric" placeholder="Docker default (64)" />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-devices">Devices</Label>
<Input
id="rt-devices"
value={devicesText}
onChange={(e) => setDevicesText(e.target.value)}
spellCheck={false}
className="font-mono text-xs"
placeholder="/dev/dri (Intel/AMD GPUs, later)"
/>
</div>
</div>
<label className="flex cursor-pointer items-start gap-2.5 rounded-lg bg-muted/50 px-3 py-2.5 text-sm">
<Checkbox checked={numa} onCheckedChange={(v) => setNuma(v === true)} className="mt-0.5" />
<span className="flex flex-col gap-0.5">
<span>NUMA tuning</span>
<span className="text-xs text-muted-foreground">
Adds <code>CAP_SYS_NICE</code> and <code>seccomp=unconfined</code>, as vLLM recommends for its CPU build. This relaxes
the container&apos;s isolation; leave it off unless you need the extra speed.
</span>
</span>
</label>
{error && <p className="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">{error}</p>}
<div className="flex justify-end gap-2">
<Button type="button" variant="ghost" onClick={onCancel}>
Cancel
</Button>
<Button type="submit" disabled={saving}>
{saving ? "Saving…" : submitLabel}
</Button>
</div>
</form>
);
}
@@ -0,0 +1,352 @@
"use client";
import { ChevronDownIcon, CopyIcon, DownloadCloudIcon, PencilIcon, PlusIcon, ServerIcon, Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Progress } from "@/components/ui/progress";
import type { DockerHostInfo, runtimes } from "@/lib/db/schema";
import { formatBytes, percent } from "@/lib/format";
import { RUNTIME_PRESETS, type RuntimeInput } from "@/lib/runtimes-shared";
import { cn } from "@/lib/utils";
import { RuntimeForm } from "./runtime-form";
type Runtime = typeof runtimes.$inferSelect;
const FEATURE_LABEL: Record<string, string> = {
avx2: "AVX2",
avx512f: "AVX-512",
avx512_bf16: "AVX-512 BF16",
avx512_vnni: "AVX-512 VNNI",
avx512bw: "AVX-512 BW",
amx_bf16: "AMX BF16",
amx_int8: "AMX INT8",
f16c: "F16C",
fma: "FMA",
};
async function send(url: string, method: string, body?: unknown): Promise<boolean> {
const res = await fetch(url, {
method,
headers: body ? { "Content-Type": "application/json" } : undefined,
body: body ? JSON.stringify(body) : undefined,
});
if (res.ok) return true;
const json = await res.json().catch(() => ({}));
toast.error(json.error?.message ?? `Request failed (${res.status})`);
return false;
}
const toInput = (r: Runtime): RuntimeInput => ({
name: r.name,
engine: r.engine,
image: r.image,
description: r.description,
env: r.env,
extraArgs: r.extraArgs,
devices: r.devices,
shmSizeMb: r.shmSizeMb,
numaTuning: r.numaTuning,
});
export function RuntimesView({ runtimes, docker, workerOnline }: { runtimes: Runtime[]; docker: DockerHostInfo | null; workerOnline: boolean }) {
const router = useRouter();
const [creating, setCreating] = useState<(RuntimeInput & { preset?: string }) | null>(null);
const [editing, setEditing] = useState<string | null>(null);
const anyPulling = runtimes.some((r) => r.imageState === "pulling" || (r.pullRequestedAt && (!r.pullStartedAt || r.pullRequestedAt > r.pullStartedAt)));
// While a pull runs, refresh the server data every 2 s for its progress.
useEffect(() => {
if (!anyPulling) return;
const t = setInterval(() => router.refresh(), 2_000);
return () => clearInterval(t);
}, [anyPulling, router]);
return (
<div className="flex flex-col gap-4">
<HostCard docker={docker} workerOnline={workerOnline} />
<Card>
<CardHeader>
<CardTitle>Runtimes</CardTitle>
<CardDescription>
Container images that serve models: official llama.cpp and vLLM builds, or your own forks from any registry. Kaname
only starts images registered here, with the models mounted read-only.
</CardDescription>
<CardAction>
<DropdownMenu>
<DropdownMenuTrigger render={<Button size="sm" />}>
<PlusIcon />
Add runtime
<ChevronDownIcon className="opacity-70" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-72">
<DropdownMenuGroup>
<DropdownMenuLabel>From a preset</DropdownMenuLabel>
{RUNTIME_PRESETS.map((p) => (
<DropdownMenuItem key={p.id} onClick={() => setCreating({ ...p, name: p.name, preset: p.id })} className="flex-col items-start gap-0">
<span>{p.name}</span>
<span className="text-xs text-muted-foreground">{p.summary}</span>
</DropdownMenuItem>
))}
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setCreating({ name: "", engine: "vllm", image: "" })}>Custom image (fork)…</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</CardAction>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{creating && (
<div className="rounded-lg p-4 ring-1 ring-primary/40">
<RuntimeForm
initial={creating}
submitLabel="Add runtime"
onCancel={() => setCreating(null)}
onSubmit={async (value) => {
const ok = await send("/api/runtimes", "POST", { ...value, preset: creating.preset });
if (ok) {
toast.success(`Runtime "${value.name}" added`);
setCreating(null);
router.refresh();
}
return ok;
}}
/>
</div>
)}
{runtimes.length === 0 && !creating && <p className="text-sm text-muted-foreground">No runtimes yet. Add one from a preset.</p>}
{runtimes.map((r) =>
editing === r.id ? (
<div key={r.id} className="rounded-lg p-4 ring-1 ring-primary/40">
<RuntimeForm
initial={toInput(r)}
submitLabel="Save"
onCancel={() => setEditing(null)}
onSubmit={async (value) => {
const ok = await send(`/api/runtimes/${r.id}`, "PUT", value);
if (ok) {
setEditing(null);
router.refresh();
}
return ok;
}}
/>
</div>
) : (
<RuntimeRow
key={r.id}
runtime={r}
dockerReady={!!docker?.connected}
onEdit={() => setEditing(r.id)}
onDuplicate={() => setCreating({ ...toInput(r), name: `${r.name} (copy)` })}
/>
),
)}
</CardContent>
</Card>
</div>
);
}
function HostCard({ docker, workerOnline }: { docker: DockerHostInfo | null; workerOnline: boolean }) {
return (
<Card size="sm">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<ServerIcon className="size-4 text-muted-foreground" />
Docker host
</CardTitle>
<CardDescription>
{!workerOnline
? "The worker is offline; these facts may be outdated."
: !docker
? "Not connected. Runtimes need the worker to reach Docker through the socket proxy (DOCKER_HOST)."
: docker.connected
? `Docker ${docker.serverVersion} on ${docker.os} (${docker.architecture})`
: `Can't reach Docker: ${docker.error}`}
</CardDescription>
</CardHeader>
{docker && (
<CardContent>
<dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-1.5 text-sm">
<dt className="text-muted-foreground">CPU</dt>
<dd>
{docker.cpuModel ?? "unknown"}
{docker.cpus != null && <span className="text-muted-foreground"> · {docker.cpus} threads</span>}
</dd>
<dt className="text-muted-foreground">Features</dt>
<dd className="flex flex-wrap gap-1">
{docker.cpuFeatures.length === 0 ? (
<span className="text-muted-foreground">unknown</span>
) : (
docker.cpuFeatures.map((f) => (
<span
key={f}
className={cn(
"rounded border px-1.5 text-xs",
f.startsWith("avx512") || f.startsWith("amx") ? "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300" : "text-muted-foreground",
)}
>
{FEATURE_LABEL[f] ?? f}
</span>
))
)}
</dd>
<dt className="text-muted-foreground">Memory</dt>
<dd>{docker.memoryBytes != null ? formatBytes(docker.memoryBytes) : "unknown"}</dd>
<dt className="text-muted-foreground">Network</dt>
<dd className={cn("font-mono text-xs", !docker.network && "text-amber-700 dark:text-amber-300")}>
{docker.network ?? "not detected (set KANAME_DOCKER_NETWORK)"}
</dd>
<dt className="text-muted-foreground">Models</dt>
<dd className={cn("font-mono text-xs break-all", !docker.modelsSource && "text-amber-700 dark:text-amber-300")}>
{docker.modelsSource ? `${docker.modelsSource.source} (${docker.modelsSource.type}, mounted read-only)` : "not detected (set KANAME_MODELS_SOURCE)"}
</dd>
<dt className="text-muted-foreground">Checked</dt>
<dd>
<LocalTime value={docker.checkedAt} />
</dd>
</dl>
</CardContent>
)}
</Card>
);
}
function ImageState({ r }: { r: Runtime }) {
const requested = !!r.pullRequestedAt && (!r.pullStartedAt || r.pullRequestedAt > r.pullStartedAt);
if (r.imageState === "pulling" || requested) {
const p = r.pullProgress;
return (
<div className="flex min-w-48 flex-col gap-1">
<span className="text-xs text-muted-foreground">
{p ? `${p.status} · ${formatBytes(p.doneBytes)}${p.totalBytes ? ` / ${formatBytes(p.totalBytes)}` : ""}` : "Pull queued…"}
</span>
<Progress value={p && p.totalBytes ? percent(p.doneBytes, p.totalBytes) : 0} />
</div>
);
}
if (r.imageState === "present") {
return (
<span className="text-xs text-emerald-700 dark:text-emerald-400">
Pulled · {r.imageSize != null ? formatBytes(r.imageSize) : "?"}
{r.imageCreated && (
<span className="text-muted-foreground">
{" "}
· built <LocalTime value={r.imageCreated} />
</span>
)}
</span>
);
}
if (r.imageState === "failed") return <span className="text-xs break-all text-destructive">Pull failed: {r.pullError}</span>;
if (r.imageState === "missing") return <span className="text-xs text-muted-foreground">Not pulled yet</span>;
return <span className="text-xs text-muted-foreground">Not checked yet</span>;
}
function RuntimeRow({
runtime: r,
dockerReady,
onEdit,
onDuplicate,
}: {
runtime: Runtime;
dockerReady: boolean;
onEdit: () => void;
onDuplicate: () => void;
}) {
const router = useRouter();
const pulling = r.imageState === "pulling";
const envCount = Object.keys(r.env).length;
return (
<div className="flex flex-col gap-3 rounded-lg px-4 py-3 ring-1 ring-foreground/10">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">{r.name}</span>
<span className="rounded-md border px-1.5 text-xs text-muted-foreground">{r.engine === "vllm" ? "vLLM" : "llama.cpp"}</span>
{r.numaTuning && <span className="rounded-md border border-amber-500/30 px-1.5 text-xs text-amber-700 dark:text-amber-300">NUMA tuning</span>}
</div>
<code className="font-mono text-xs break-all text-muted-foreground">{r.image}</code>
{r.description && <p className="text-xs text-muted-foreground">{r.description}</p>}
</div>
<div className="flex items-center gap-1">
<Button
size="sm"
variant={r.imageState === "present" ? "ghost" : "outline"}
disabled={!dockerReady || pulling}
title={!dockerReady ? "Docker isn't connected" : r.imageState === "present" ? "Pull again to update the tag" : undefined}
onClick={async () => {
if (await send(`/api/runtimes/${r.id}/pull`, "POST")) router.refresh();
}}
>
<DownloadCloudIcon />
{r.imageState === "present" ? "Update" : "Pull"}
</Button>
<Button size="icon-sm" variant="ghost" onClick={onEdit} aria-label={`Edit ${r.name}`}>
<PencilIcon />
</Button>
<Button size="icon-sm" variant="ghost" onClick={onDuplicate} aria-label={`Duplicate ${r.name}`}>
<CopyIcon />
</Button>
<AlertDialog>
<AlertDialogTrigger render={<Button size="icon-sm" variant="ghost" aria-label={`Delete ${r.name}`} />}>
<Trash2Icon />
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete runtime &ldquo;{r.name}&rdquo;?</AlertDialogTitle>
<AlertDialogDescription>The pulled image stays in Docker; remove it there if you need the space.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
onClick={async () => {
if (await send(`/api/runtimes/${r.id}`, "DELETE")) router.refresh();
}}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-1 text-xs text-muted-foreground">
<ImageState r={r} />
<span>
{envCount > 0 && `${envCount} env var${envCount === 1 ? "" : "s"}`}
{r.extraArgs.length > 0 && `${envCount > 0 ? " · " : ""}${r.extraArgs.join(" ")}`}
{r.shmSizeMb != null && ` · shm ${r.shmSizeMb} MiB`}
{r.devices.length > 0 && ` · ${r.devices.join(", ")}`}
</span>
</div>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { ApiKeyError, deleteApiKey, revealApiKey } from "@/lib/api-keys";
export const dynamic = "force-dynamic";
/** The key's value ("show key" in Settings). */
export const GET = withAuth<RouteContext<"/api/api-keys/[id]">>(async (_req, { params }) => {
const { id } = await params;
try {
return NextResponse.json({ key: await revealApiKey(id) }, { headers: { "Cache-Control": "no-store" } });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Remove a key; running deployments keep accepting it until they restart. */
export const DELETE = withAuth<RouteContext<"/api/api-keys/[id]">>(async (_req, { params }) => {
const { id } = await params;
try {
await deleteApiKey(id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+19
View File
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { ApiKeyBody, ApiKeyError, createApiKey, listApiKeys } from "@/lib/api-keys";
export const dynamic = "force-dynamic";
/** Keys without their values (only the last characters). */
export const GET = withAuth(async () => NextResponse.json(await listApiKeys()));
/** Add a key (generated when `key` is missing); the response carries the full key once. */
export const POST = withAuth(async (req) => {
try {
return NextResponse.json(await createApiKey(ApiKeyBody.parse(await req.json())), { status: 201 });
} catch (err) {
if (err instanceof ApiKeyError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,45 @@
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { apiKeyValues } from "@/lib/api-keys";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { getDeployment } from "@/lib/deployments";
export const dynamic = "force-dynamic";
const Body = z.object({
messages: z.array(z.object({ role: z.enum(["system", "user", "assistant"]), content: z.string().max(100_000) })).min(1).max(100),
maxTokens: z.number().int().min(1).max(8192).default(256),
});
/**
* Smoke-test chat: forwards to the container's OpenAI-compatible API over the Docker network and
* streams the server-sent events back unchanged.
*/
export const POST = withAuth<RouteContext<"/api/deployments/[id]/chat">>(async (req, { params }) => {
try {
const d = await getDeployment((await params).id);
if (!d) return apiError(404, "not_found", "Deployment not found.");
if (d.state !== "running" || !d.containerName) return apiError(409, "not_running", "The deployment isn't running.");
const { messages, maxTokens } = Body.parse(await req.json());
// Any key works; keys added after the deployment started aren't known to it yet, so prefer the oldest.
const [key] = d.options.requireApiKey ? await apiKeyValues() : [];
const upstream = await fetch(`http://${d.containerName}:${ENGINE_PORT[d.engine]}/v1/chat/completions`, {
method: "POST",
headers: { "Content-Type": "application/json", ...(key ? { Authorization: `Bearer ${key}` } : {}) },
body: JSON.stringify({ model: d.repoId, messages, max_tokens: maxTokens, stream: true, stream_options: { include_usage: true } }),
signal: req.signal,
}).catch((err: Error) => {
throw new Error(`Can't reach the deployment (${err.message}). The web app must be on the same Docker network.`);
});
if (!upstream.ok || !upstream.body) {
const text = await upstream.text().catch(() => "");
if (upstream.status === 401) return apiError(502, "upstream", "The model server rejected Kaname's API key. Restart the deployment to pick up changed keys.");
return apiError(502, "upstream", `The model server answered ${upstream.status}: ${text.slice(0, 500)}`);
}
return new Response(upstream.body, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-store" } });
} catch (err) {
if (err instanceof Error && err.message.startsWith("Can't reach")) return apiError(502, "unreachable", err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,11 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { listDeploymentLogs } from "@/lib/deployments";
export const dynamic = "force-dynamic";
/** Log lines after `?after=<id>` (first call: the last 500). */
export const GET = withAuth<RouteContext<"/api/deployments/[id]/logs">>(async (req, { params }) => {
const after = Number(new URL(req.url).searchParams.get("after") ?? 0) || 0;
return NextResponse.json(await listDeploymentLogs((await params).id, after));
});
+32
View File
@@ -0,0 +1,32 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentBody, DeploymentError, getDeployment, requestDelete, updateDeployment } from "@/lib/deployments";
export const dynamic = "force-dynamic";
export const GET = withAuth<RouteContext<"/api/deployments/[id]">>(async (_req, { params }) => {
const d = await getDeployment((await params).id);
return d ? NextResponse.json(d) : apiError(404, "not_found", "Deployment not found.");
});
export const PUT = withAuth<RouteContext<"/api/deployments/[id]">>(async (req, { params }) => {
try {
await updateDeployment((await params).id, DeploymentBody.parse(await req.json()));
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
/** Stop the container (if running) and delete the deployment. */
export const DELETE = withAuth<RouteContext<"/api/deployments/[id]">>(async (_req, { params }) => {
try {
await requestDelete((await params).id);
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentError, setDesiredState } from "@/lib/deployments";
export const POST = withAuth<RouteContext<"/api/deployments/[id]/start">>(async (_req, { params }) => {
try {
await setDesiredState((await params).id, "running");
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { DeploymentError, setDesiredState } from "@/lib/deployments";
export const POST = withAuth<RouteContext<"/api/deployments/[id]/stop">>(async (_req, { params }) => {
try {
await setDesiredState((await params).id, "stopped");
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof DeploymentError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+20
View File
@@ -0,0 +1,20 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { createDeployment, DeploymentBody, DeploymentError, listDeployments } from "@/lib/deployments";
export const dynamic = "force-dynamic";
export const GET = withAuth(async () => NextResponse.json(await listDeployments()));
/** Create a deployment; `start: true` starts it right away. */
export const POST = withAuth(async (req) => {
try {
const body = DeploymentBody.extend({ start: z.boolean().default(true) }).parse(await req.json());
return NextResponse.json(await createDeployment(body, body.start), { status: 201 });
} catch (err) {
if (err instanceof DeploymentError) 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 { requestPull, RuntimeError } from "@/lib/runtimes";
/** Ask the worker to pull the image (again; updates moving tags like :server). */
export const POST = withAuth<RouteContext<"/api/runtimes/[id]/pull">>(async (_req, { params }) => {
const { id } = await params;
try {
await requestPull(id);
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+25
View File
@@ -0,0 +1,25 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { deleteRuntime, RuntimeBody, RuntimeError, updateRuntime } from "@/lib/runtimes";
export const PUT = withAuth<RouteContext<"/api/runtimes/[id]">>(async (req, { params }) => {
const { id } = await params;
try {
return NextResponse.json(await updateRuntime(id, RuntimeBody.parse(await req.json())));
} catch (err) {
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
export const DELETE = withAuth<RouteContext<"/api/runtimes/[id]">>(async (_req, { params }) => {
const { id } = await params;
try {
await deleteRuntime(id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+21
View File
@@ -0,0 +1,21 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { createRuntime, getDockerInfo, listRuntimes, RuntimeBody, RuntimeError } from "@/lib/runtimes";
export const dynamic = "force-dynamic";
/** Runtimes plus the Docker facts the worker reported. */
export const GET = withAuth(async () => NextResponse.json({ runtimes: await listRuntimes(), docker: await getDockerInfo() }));
export const POST = withAuth(async (req) => {
try {
const body = RuntimeBody.extend({ preset: z.string().optional() }).parse(await req.json());
return NextResponse.json(await createRuntime(body), { status: 201 });
} catch (err) {
if (err instanceof RuntimeError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+7
View File
@@ -127,4 +127,11 @@
html {
@apply font-sans;
}
/* Native controls (select popups, scrollbars, date pickers) follow the theme. */
.dark {
color-scheme: dark;
}
option {
@apply bg-popover text-popover-foreground;
}
}
+9 -3
View File
@@ -1,12 +1,18 @@
"use client";
import { LibraryIcon, SettingsIcon } from "lucide-react";
import { LibraryIcon, RocketIcon, SettingsIcon } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
const LINKS = [
{ href: "/", label: "Library", icon: LibraryIcon, active: (p: string) => !p.startsWith("/settings") && !p.startsWith("/jobs/") },
{
href: "/",
label: "Library",
icon: LibraryIcon,
active: (p: string) => !p.startsWith("/settings") && !p.startsWith("/deployments"),
},
{ href: "/deployments", label: "Deployments", icon: RocketIcon, active: (p: string) => p.startsWith("/deployments") },
{ href: "/settings", label: "Settings", icon: SettingsIcon, active: (p: string) => p.startsWith("/settings") },
];
@@ -16,7 +22,7 @@ export function AppNav() {
return (
<nav className="flex items-center gap-1 text-sm">
{LINKS.map((l) => {
const active = l.active(pathname) || (l.href === "/" && pathname.startsWith("/jobs/"));
const active = l.active(pathname);
return (
<Link
key={l.href}
+56
View File
@@ -0,0 +1,56 @@
"use client";
import { PlusIcon, XIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { ArgRow } from "@/lib/extra-args";
const GENERIC = { flag: "--flag", value: "value (optional)" };
/** Extra command-line arguments as flag/value rows (controlled). `placeholder` is the first row's example. */
export function ArgsEditor({
rows,
onChange,
placeholder = GENERIC,
addLabel = "Add argument",
}: {
rows: ArgRow[];
onChange: (rows: ArgRow[]) => void;
placeholder?: { flag: string; value: string };
addLabel?: string;
}) {
const set = (i: number, patch: Partial<ArgRow>) => onChange(rows.map((r, j) => (j === i ? { ...r, ...patch } : r)));
const single = (s: string) => s.replace(/[\r\n]/g, "");
return (
<div className="flex flex-col gap-1.5">
{rows.map((r, i) => (
<div key={i} className="flex items-center gap-1.5">
<Input
value={r.flag}
onChange={(e) => set(i, { flag: single(e.target.value) })}
placeholder={(i === 0 ? placeholder : GENERIC).flag}
spellCheck={false}
aria-label={`Argument ${i + 1} flag`}
className="font-mono text-xs md:text-xs"
/>
<Input
value={r.value}
onChange={(e) => set(i, { value: single(e.target.value) })}
placeholder={(i === 0 ? placeholder : GENERIC).value}
spellCheck={false}
aria-label={`Argument ${i + 1} value`}
className="font-mono text-xs md:text-xs"
/>
<Button type="button" variant="ghost" size="icon-sm" aria-label={`Remove argument ${i + 1}`} onClick={() => onChange(rows.filter((_, j) => j !== i))}>
<XIcon />
</Button>
</div>
))}
<Button type="button" variant="outline" size="sm" className="self-start" onClick={() => onChange([...rows, { flag: "", value: "" }])}>
<PlusIcon />
{addLabel}
</Button>
</div>
);
}
+23
View File
@@ -0,0 +1,23 @@
import { LoaderCircleIcon } from "lucide-react";
import { cn } from "@/lib/utils";
const STYLE: Record<string, { label: string; className: string }> = {
stopped: { label: "stopped", className: "border-foreground/15 text-muted-foreground" },
starting: { label: "starting", className: "border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300" },
running: { label: "running", className: "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300" },
stopping: { label: "stopping", className: "border-foreground/15 text-muted-foreground" },
failed: { label: "failed", className: "border-destructive/30 bg-destructive/10 text-destructive" },
};
/** Deployment state; shows "starting" as soon as a start was requested. */
export function DeploymentStateBadge({ state, desiredState, className }: { state: string; desiredState: string; className?: string }) {
const effective = desiredState === "running" && (state === "stopped" || state === "failed") ? "starting" : desiredState === "stopped" && (state === "running" || state === "starting") ? "stopping" : state;
const s = STYLE[effective] ?? STYLE.stopped;
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", s.className, className)}>
{(effective === "starting" || effective === "stopping") && <LoaderCircleIcon className="size-3 animate-spin" />}
{effective === "running" && <span className="size-1.5 rounded-full bg-emerald-500" />}
{s.label}
</span>
);
}
+21
View File
@@ -0,0 +1,21 @@
import { ChevronDownIcon } from "lucide-react";
import * as React from "react";
import { cn } from "@/lib/utils";
/** A native <select> styled like Input; the option list follows the theme via `color-scheme`. */
function NativeSelect({ className, children, ...props }: React.ComponentProps<"select">) {
return (
<div className={cn("relative w-full", className)}>
<select
data-slot="native-select"
className="h-8 w-full min-w-0 appearance-none rounded-lg border border-input bg-transparent py-1 pr-8 pl-2.5 text-sm transition-colors outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30"
{...props}
>
{children}
</select>
<ChevronDownIcon className="pointer-events-none absolute top-1/2 right-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
</div>
);
}
export { NativeSelect };
+9 -1
View File
@@ -1,6 +1,6 @@
"use client";
import { LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
import { BoxesIcon, KeyRoundIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
import Link from "next/link";
import { useTheme } from "next-themes";
import { useTransition } from "react";
@@ -67,6 +67,14 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
<TagsIcon />
Tags
</DropdownMenuItem>
<DropdownMenuItem render={<Link href="/settings/runtimes" />}>
<BoxesIcon />
Runtimes
</DropdownMenuItem>
<DropdownMenuItem render={<Link href="/settings/api-keys" />}>
<KeyRoundIcon />
API keys
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
+20
View File
@@ -0,0 +1,20 @@
"use client";
import { useSyncExternalStore } from "react";
/** The browser's host name; null while rendering on the server, so hydration matches. */
export function useHostname(): string | null {
return useSyncExternalStore(
() => () => {},
() => window.location.hostname,
() => null,
);
}
/** llama-server's built-in chat UI, served at / on the published host port. */
export function webUiUrl(
d: { engine: string; hostPort: number | null; options: { webui?: boolean | null } },
hostname: string | null,
): string | null {
return d.engine === "llama.cpp" && d.options.webui !== false && d.hostPort && hostname ? `http://${hostname}:${d.hostPort}/` : null;
}
+67
View File
@@ -0,0 +1,67 @@
import "server-only";
import { randomBytes } from "node:crypto";
import { asc, eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "@/lib/db/client";
import { apiKeys } from "@/lib/db/schema";
export class ApiKeyError extends Error {
constructor(
public code: "invalid" | "not_found" | "conflict",
message: string,
public status: number,
) {
super(message);
}
}
// No whitespace or commas: llama.cpp takes several keys as one comma-separated list.
export const ApiKeyBody = z.object({
name: z.string().trim().min(1).max(80),
key: z
.string()
.trim()
.min(16, "at least 16 characters")
.max(256)
.regex(/^[\x21-\x7e]+$/, "printable characters without spaces")
.refine((k) => !k.includes(","), "no commas")
.optional(),
});
export const generateApiKey = () => `sk-kaname-${randomBytes(24).toString("base64url")}`;
/** "…" plus the last 4 characters: enough to tell keys apart without showing them. */
const mask = (key: string) => `…${key.slice(-4)}`;
export type ApiKeyRow = { id: string; name: string; hint: string; createdAt: number };
export async function listApiKeys(): Promise<ApiKeyRow[]> {
const rows = await db().select().from(apiKeys).orderBy(asc(apiKeys.createdAt));
return rows.map((r) => ({ id: r.id, name: r.name, hint: mask(r.key), createdAt: r.createdAt.getTime() }));
}
/** Returns the full key once, so the user can copy it. */
export async function createApiKey(input: z.infer<typeof ApiKeyBody>) {
const key = input.key ?? generateApiKey();
const clash = await db().query.apiKeys.findFirst({ columns: { id: true }, where: eq(apiKeys.key, key) });
if (clash) throw new ApiKeyError("conflict", "This key already exists.", 409);
const [row] = await db().insert(apiKeys).values({ name: input.name, key }).returning();
return { id: row.id, name: row.name, key, hint: mask(key), createdAt: row.createdAt.getTime() };
}
export async function deleteApiKey(id: string) {
const res = await db().delete(apiKeys).where(eq(apiKeys.id, id)).returning({ id: apiKeys.id });
if (res.length === 0) throw new ApiKeyError("not_found", "API key not found.", 404);
}
/** All key values (for runtime containers and Kaname's own requests to them). */
export async function apiKeyValues(): Promise<string[]> {
return (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt))).map((r) => r.key);
}
/** One key's value, for "show key" in Settings. */
export async function revealApiKey(id: string): Promise<string> {
const row = await db().query.apiKeys.findFirst({ columns: { key: true }, where: eq(apiKeys.id, id) });
if (!row) throw new ApiKeyError("not_found", "API key not found.", 404);
return row.key;
}
+164
View File
@@ -3,6 +3,7 @@ import {
index,
integer,
primaryKey,
real,
sqliteTable,
text,
uniqueIndex,
@@ -342,6 +343,69 @@ export const workerState = sqliteTable("worker_state", {
heartbeatAt: ts("heartbeat_at").notNull(),
/** Set by the web app ("Rescan"); the worker scans MODELS_DIR when this is newer than its last scan. */
scanRequestedAt: ts("scan_requested_at"),
/** Docker connection and host facts, reported by the worker (null: no DOCKER_HOST). */
docker: text("docker", { mode: "json" }).$type<DockerHostInfo>(),
});
export type DockerHostInfo = {
connected: boolean;
error: string | null;
serverVersion: string | null;
os: string | null;
architecture: string | null;
cpus: number | null;
memoryBytes: number | null;
cpuModel: string | null;
/** Relevant CPU features (avx2, avx512f, avx512_bf16, amx_bf16, …). */
cpuFeatures: string[];
/** Docker network inference containers join, so the worker can reach them. */
network: string | null;
/** Where the models come from on the Docker host (bind path or volume name), mounted read-only. */
modelsSource: { type: "bind" | "volume"; source: string } | null;
checkedAt: string;
};
// ---------------------------------------------------------------------------
// Runtimes: container images that serve models (llama.cpp, vLLM, forks, …)
// ---------------------------------------------------------------------------
/** How Kaname builds the command line and talks to the server. */
export const RUNTIME_ENGINES = ["llama.cpp", "vllm"] as const;
export type RuntimeEngine = (typeof RUNTIME_ENGINES)[number];
export const IMAGE_STATES = ["unknown", "missing", "pulling", "present", "failed"] as const;
export type ImageState = (typeof IMAGE_STATES)[number];
export const runtimes = sqliteTable("runtimes", {
id: id(),
name: text("name").notNull(),
engine: text("engine", { enum: RUNTIME_ENGINES }).notNull(),
/** Full image reference, e.g. "ghcr.io/ggml-org/llama.cpp:server". */
image: text("image").notNull(),
description: text("description"),
/** Environment variables for the container. */
env: text("env", { mode: "json" }).$type<Record<string, string>>().notNull().default(sql`'{}'`),
/** Appended to the generated command line (fork-specific flags). */
extraArgs: text("extra_args", { mode: "json" }).$type<string[]>().notNull().default(sql`'[]'`),
/** Host devices to pass through, e.g. "/dev/dri" (later: Intel GPUs). */
devices: text("devices", { mode: "json" }).$type<string[]>().notNull().default(sql`'[]'`),
shmSizeMb: integer("shm_size_mb"),
/** vLLM's NUMA optimizations: adds CAP_SYS_NICE and seccomp=unconfined. Off unless enabled. */
numaTuning: integer("numa_tuning", { mode: "boolean" }).notNull().default(false),
/** Preset this runtime was created from, if any. */
preset: text("preset"),
imageState: text("image_state", { enum: IMAGE_STATES }).notNull().default("unknown"),
imageId: text("image_id"),
imageSize: integer("image_size"),
imageCreated: text("image_created"),
/** Set by "Pull"; the worker pulls when this is newer than the last pull. */
pullRequestedAt: ts("pull_requested_at"),
pullStartedAt: ts("pull_started_at"),
pullProgress: text("pull_progress", { mode: "json" }).$type<{ doneBytes: number; totalBytes: number; status: string }>(),
pullError: text("pull_error"),
imageCheckedAt: ts("image_checked_at"),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
/**
@@ -359,3 +423,103 @@ export const localFolders = sqliteTable("local_folders", {
commit: text("commit"),
scannedAt: ts("scanned_at").notNull(),
});
// ---------------------------------------------------------------------------
// Deployments: a model served by a runtime container
// ---------------------------------------------------------------------------
/** What the worker is doing with the container. */
export const DEPLOYMENT_STATES = ["stopped", "starting", "running", "stopping", "failed"] as const;
export type DeploymentState = (typeof DEPLOYMENT_STATES)[number];
/** Launch options. Engine-specific fields are ignored by the other engine. */
export type DeploymentOptions = {
/** Model file (llama.cpp: the GGUF, first part of a split) or "" for the repo folder (vLLM). */
modelFile: string;
/** llama.cpp: multimodal projector. */
mmproj?: string | null;
/** llama.cpp: draft model (MTP head or a small draft model) for speculative decoding. */
draftFile?: string | null;
draftType?: "draft-mtp" | "draft-simple" | null;
contextSize: number;
threads?: number | null;
batchSize?: number | null;
ubatchSize?: number | null;
parallel?: number | null;
cacheTypeK?: string | null;
cacheTypeV?: string | null;
flashAttn?: "auto" | "on" | "off" | null;
/** llama.cpp: serve the built-in web UI at / (llama-server's default; false passes --no-webui). */
webui?: boolean | null;
/** Only accept requests with one of the API keys from Settings → API keys. */
requireApiKey?: boolean | null;
/** vLLM */
dtype?: string | null;
maxNumSeqs?: number | null;
kvCacheGb?: number | null;
extraArgs: string[];
};
export type DeploymentStats = { cpuPercent: number; memoryBytes: number; memoryLimitBytes: number; at: string };
export const deployments = sqliteTable("deployments", {
id: id(),
name: text("name").notNull(),
runtimeId: text("runtime_id")
.notNull()
.references(() => runtimes.id),
modelId: text("model_id")
.notNull()
.references(() => models.id),
options: text("options", { mode: "json" }).$type<DeploymentOptions>().notNull(),
/** CPU limit in cores (fractions allowed) and memory limit; null = no limit. */
cpus: real("cpus"),
memoryMb: integer("memory_mb"),
/** Publish the API on this host port (optional; Kaname itself uses the Docker network). */
hostPort: integer("host_port"),
/** Set by the web app; the worker starts/stops the container to match. */
desiredState: text("desired_state", { enum: ["running", "stopped"] }).notNull().default("stopped"),
state: text("state", { enum: DEPLOYMENT_STATES }).notNull().default("stopped"),
/** Delete requested: the worker removes the container, then the row. */
deleteRequestedAt: ts("delete_requested_at"),
containerId: text("container_id"),
containerName: text("container_name"),
/** Command line the container was started with (for display and reproducibility). */
command: text("command", { mode: "json" }).$type<string[]>(),
imageId: text("image_id"),
startedAt: ts("started_at"),
readyAt: ts("ready_at"),
stoppedAt: ts("stopped_at"),
exitCode: integer("exit_code"),
error: text("error"),
stats: text("stats", { mode: "json" }).$type<DeploymentStats>(),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
export const deploymentLogs = sqliteTable(
"deployment_logs",
{
id: integer("id").primaryKey({ autoIncrement: true }),
deploymentId: text("deployment_id")
.notNull()
.references(() => deployments.id),
ts: ts("ts")
.notNull()
.$defaultFn(() => new Date()),
stream: text("stream", { enum: LOG_STREAMS }).notNull(),
line: text("line").notNull(),
},
(t) => [index("deployment_logs_idx").on(t.deploymentId, t.id)],
);
/**
* API keys that deployments with `requireApiKey` accept. Stored in plain text because the worker
* hands them to the runtime container; never logged or written into a stored command line.
*/
export const apiKeys = sqliteTable("api_keys", {
id: id(),
name: text("name").notNull(),
key: text("key").notNull().unique(),
createdAt: createdAt(),
});
+36
View File
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { modelCandidates, servableBy } from "./deploy-candidates";
const f = (path: string, size = 10) => ({ path, size });
describe("modelCandidates", () => {
it("lists GGUF weights (split as first part), mmproj and MTP/draft files", () => {
const c = modelCandidates([
f("Qwen3.8-27B-UD-Q4_K_XL.gguf"),
f("BF16/Qwen3.8-27B-BF16-00001-of-00002.gguf"),
f("BF16/Qwen3.8-27B-BF16-00002-of-00002.gguf"),
f("mmproj-F16.gguf"),
f("MTP/mtp-Qwen3.8-27B-Q4_0.gguf"),
f("imatrix_unsloth.gguf"),
f("config.json"),
]);
assert.deepEqual(
c.gguf.map((g) => [g.path, g.parts]),
[
["Qwen3.8-27B-UD-Q4_K_XL.gguf", 1],
["BF16/Qwen3.8-27B-BF16-00001-of-00002.gguf", 2],
],
);
assert.deepEqual(c.mmproj.map((m) => m.path), ["mmproj-F16.gguf"]);
assert.deepEqual(c.drafts.map((d) => [d.path, d.type]), [["MTP/mtp-Qwen3.8-27B-Q4_0.gguf", "draft-mtp"]]);
assert.equal(c.vllm, null);
assert.ok(servableBy(c, "llama.cpp") && !servableBy(c, "vllm"));
});
it("recognizes a safetensors repo for vLLM", () => {
const c = modelCandidates([f("config.json", 1), f("model.safetensors", 100), f("tokenizer.json", 5)]);
assert.deepEqual(c.vllm, { size: 106 });
assert.equal(c.gguf.length, 0);
});
});
+41
View File
@@ -0,0 +1,41 @@
// Which downloaded files a runtime can serve. Pure; shared by the server and the deployment form.
import type { RuntimeEngine } from "@/lib/db/schema";
import { groupSplitFiles } from "@/lib/file-groups";
import { fileRole } from "@/lib/file-roles";
export type LocalFile = { path: string; size: number };
export type CandidateFile = { path: string; size: number; parts: number };
export type DraftFile = CandidateFile & { type: "draft-mtp" | "draft-simple" };
export type ModelCandidates = {
/** llama.cpp: loadable GGUF weights (split files as their first part), plus optional extras. */
gguf: CandidateFile[];
mmproj: CandidateFile[];
drafts: DraftFile[];
/** vLLM: the repo folder has a config.json and safetensors weights. */
vllm: { size: number } | null;
};
const isGguf = (p: string) => p.toLowerCase().endsWith(".gguf");
/** `files`: the model's files that are on disk (present or verified). */
export function modelCandidates(files: LocalFile[]): ModelCandidates {
const entries = (pred: (p: string) => boolean) =>
groupSplitFiles(files.filter((f) => pred(f.path))).map((g) => ({ path: g.parts[0].path, size: g.size, parts: g.totalParts }));
const gguf = entries((p) => isGguf(p) && fileRole(p) === "model");
const mmproj = entries((p) => isGguf(p) && fileRole(p) === "vision");
const drafts: DraftFile[] = [
...entries((p) => isGguf(p) && fileRole(p) === "mtp").map((f) => ({ ...f, type: "draft-mtp" as const })),
...entries((p) => isGguf(p) && fileRole(p) === "draft").map((f) => ({ ...f, type: "draft-simple" as const })),
];
const hasConfig = files.some((f) => f.path === "config.json");
const safetensors = files.filter((f) => f.path.endsWith(".safetensors") && fileRole(f.path) === "model");
const vllm = hasConfig && safetensors.length > 0 ? { size: files.reduce((s, f) => s + f.size, 0) } : null;
return { gguf, mmproj, drafts, vllm };
}
export function servableBy(c: ModelCandidates, engine: RuntimeEngine): boolean {
return engine === "llama.cpp" ? c.gguf.length > 0 : c.vllm !== null;
}
+86
View File
@@ -0,0 +1,86 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { buildCommand, redactCommand, renderCommand } from "./deploy-command";
const model = { repoId: "unsloth/Qwen3-0.6B-GGUF", localPath: "unsloth/Qwen3-0.6B-GGUF" };
describe("buildCommand", () => {
it("builds llama-server arguments with mmproj and MTP draft", () => {
const cmd = buildCommand({
engine: "llama.cpp",
model,
runtime: { env: {}, extraArgs: ["--jinja"] },
options: {
modelFile: "Qwen3-0.6B-Q4_K_M.gguf",
mmproj: "mmproj-F16.gguf",
draftFile: "MTP/mtp-Q4_0.gguf",
draftType: "draft-mtp",
contextSize: 4096,
threads: 8,
parallel: 1,
cacheTypeK: "q8_0",
extraArgs: ["--temp", "0.7"],
},
});
assert.equal(cmd.port, 8080);
assert.deepEqual(cmd.args.slice(0, 2), ["-m", "/models/unsloth/Qwen3-0.6B-GGUF/Qwen3-0.6B-Q4_K_M.gguf"]);
const s = cmd.args.join(" ");
assert.match(s, /-c 4096 -t 8 -tb 8 -np 1 -ctk q8_0/);
assert.match(s, /--mmproj \/models\/unsloth\/Qwen3-0\.6B-GGUF\/mmproj-F16\.gguf/);
assert.match(s, /-md \/models\/unsloth\/Qwen3-0\.6B-GGUF\/MTP\/mtp-Q4_0\.gguf --spec-type draft-mtp/);
assert.ok(s.endsWith("--metrics --jinja --temp 0.7"));
assert.ok(!s.includes("-b "), "unset options are left out");
});
it("builds vllm serve arguments; deployment dtype and KV cache override the runtime", () => {
const cmd = buildCommand({
engine: "vllm",
model: { repoId: "HuggingFaceTB/SmolLM2-135M-Instruct", localPath: "HuggingFaceTB/SmolLM2-135M-Instruct" },
runtime: { env: { VLLM_CPU_KVCACHE_SPACE: "4" }, extraArgs: ["--dtype=bfloat16", "--enforce-eager"] },
options: { modelFile: "", contextSize: 2048, maxNumSeqs: 4, dtype: "float32", kvCacheGb: 2, extraArgs: [] },
});
assert.equal(cmd.port, 8000);
assert.equal(cmd.args[0], "/models/HuggingFaceTB/SmolLM2-135M-Instruct");
assert.equal(cmd.env.VLLM_CPU_KVCACHE_SPACE, "2");
const s = cmd.args.join(" ");
assert.ok(!s.includes("bfloat16") && s.includes("--dtype float32") && s.includes("--enforce-eager"));
assert.match(renderCommand("vllm/vllm-openai-cpu:v0.31.0", cmd), /^docker run -e VLLM_CPU_KVCACHE_SPACE=2 /);
const keep = buildCommand({
engine: "vllm",
model: { repoId: "a/b", localPath: "a/b" },
runtime: { env: {}, extraArgs: ["--dtype", "bfloat16"] },
options: { modelFile: "", contextSize: 2048, extraArgs: [] },
});
assert.ok(keep.args.join(" ").includes("--dtype bfloat16"));
});
it("turns llama.cpp's web UI off only when asked", () => {
const args = (webui?: boolean | null) =>
buildCommand({
engine: "llama.cpp",
model: { repoId: "a/b", localPath: "a/b" },
runtime: { env: {}, extraArgs: [] },
options: { modelFile: "m.gguf", contextSize: 2048, webui, extraArgs: [] },
}).args;
assert.ok(!args().includes("--no-webui") && !args(true).includes("--no-webui"));
assert.ok(args(false).includes("--no-webui"));
});
it("passes API keys via the environment and redacts them", () => {
const base = { model: { repoId: "a/b", localPath: "a/b" }, runtime: { env: {}, extraArgs: [] } };
const opts = { modelFile: "m.gguf", contextSize: 2048, requireApiKey: true, extraArgs: [] };
const llama = buildCommand({ ...base, engine: "llama.cpp", options: opts, apiKeys: ["sk-one-1234567890", "sk-two-1234567890"] });
assert.equal(llama.env.LLAMA_API_KEY, "sk-one-1234567890,sk-two-1234567890");
assert.ok(!llama.args.join(" ").includes("sk-"));
const shown = renderCommand("img", redactCommand(llama, ["sk-one-1234567890", "sk-two-1234567890"]));
assert.ok(!shown.includes("sk-") && shown.includes("<api-key>,<api-key>"));
const one = buildCommand({ ...base, engine: "vllm", options: { ...opts, modelFile: "" }, apiKeys: ["sk-one-1234567890"] });
assert.equal(one.env.VLLM_API_KEY, "sk-one-1234567890");
const two = buildCommand({ ...base, engine: "vllm", options: { ...opts, modelFile: "" }, apiKeys: ["k1-1234567890123456", "k2-1234567890123456"] });
assert.deepEqual(two.args.slice(two.args.indexOf("--api-key"), two.args.indexOf("--api-key") + 3), ["--api-key", "k1-1234567890123456", "k2-1234567890123456"]);
const off = buildCommand({ ...base, engine: "llama.cpp", options: { ...opts, requireApiKey: false }, apiKeys: ["sk-one-1234567890"] });
assert.equal(off.env.LLAMA_API_KEY, undefined);
});
});
+122
View File
@@ -0,0 +1,122 @@
// Container command lines for deployments, per engine type. Pure: used by the worker to start
// containers and by the UI for the live preview. Flags verified against llama.cpp build 11429
// (`llama-server --help`) and vLLM v0.31.0 (`vllm serve --help=all`).
import type { DeploymentOptions, RuntimeEngine } from "@/lib/db/schema";
/** Where the models folder is mounted inside every runtime container (read-only). */
export const CONTAINER_MODELS_DIR = "/models";
export const ENGINE_PORT: Record<RuntimeEngine, number> = { "llama.cpp": 8080, vllm: 8000 };
export type CommandInput = {
engine: RuntimeEngine;
options: DeploymentOptions;
model: { repoId: string; localPath: string };
runtime: { env: Record<string, string>; extraArgs: string[] };
/** Keys from Settings → API keys; used when `options.requireApiKey` is set. */
apiKeys?: string[];
};
/** Stands in for key values in everything Kaname shows or stores. */
export const API_KEY_PLACEHOLDER = "<api-key>";
export type ContainerCommand = { args: string[]; env: Record<string, string>; port: number };
const inModels = (localPath: string, file?: string | null) =>
[CONTAINER_MODELS_DIR, localPath, file].filter(Boolean).join("/").replace(/\/+/g, "/");
const num = (flag: string, v: number | null | undefined) => (v != null && Number.isFinite(v) ? [flag, String(v)] : []);
const str = (flag: string, v: string | null | undefined) => (v ? [flag, v] : []);
/** `args` without `flag` ("--flag value" or "--flag=value"). */
function withoutFlag(args: string[], flag: string): string[] {
const out: string[] = [];
for (let i = 0; i < args.length; i++) {
if (args[i] === flag) i++;
else if (!args[i].startsWith(`${flag}=`)) out.push(args[i]);
}
return out;
}
export function buildCommand({ engine, options: o, model, runtime, apiKeys = [] }: CommandInput): ContainerCommand {
const port = ENGINE_PORT[engine];
const keys = o.requireApiKey ? apiKeys : [];
if (engine === "llama.cpp") {
// The image's entrypoint is llama-server, so these are its arguments.
const args = [
"-m",
inModels(model.localPath, o.modelFile),
"--host",
"0.0.0.0",
"--port",
String(port),
"-a",
model.repoId,
...num("-c", o.contextSize),
...num("-t", o.threads),
...num("-tb", o.threads),
...num("-b", o.batchSize),
...num("-ub", o.ubatchSize),
...num("-np", o.parallel),
...str("-ctk", o.cacheTypeK),
...str("-ctv", o.cacheTypeV),
...str("-fa", o.flashAttn),
...(o.mmproj ? ["--mmproj", inModels(model.localPath, o.mmproj)] : []),
...(o.draftFile ? ["-md", inModels(model.localPath, o.draftFile), "--spec-type", o.draftType ?? "draft-simple"] : []),
...(o.webui === false ? ["--no-webui"] : []),
"--metrics",
...runtime.extraArgs,
...o.extraArgs,
];
// Via the environment, not the command line; several keys as one comma-separated list.
const env = { ...runtime.env, ...(keys.length ? { LLAMA_API_KEY: keys.join(",") } : {}) };
return { args, env, port };
}
// vLLM: the image's entrypoint is `vllm serve`; the model is the repo folder.
const env = { ...runtime.env };
if (o.kvCacheGb != null) env.VLLM_CPU_KVCACHE_SPACE = String(o.kvCacheGb);
// VLLM_API_KEY holds a single key; more than one needs --api-key.
if (keys.length === 1) env.VLLM_API_KEY = keys[0];
const args = [
inModels(model.localPath, o.modelFile || null),
"--host",
"0.0.0.0",
"--port",
String(port),
"--served-model-name",
model.repoId,
...num("--max-model-len", o.contextSize),
...num("--max-num-seqs", o.maxNumSeqs),
...(keys.length > 1 ? ["--api-key", ...keys] : []),
// A deployment's dtype replaces the runtime's default instead of repeating the flag.
...(o.dtype ? withoutFlag(runtime.extraArgs, "--dtype") : runtime.extraArgs),
...str("--dtype", o.dtype),
...o.extraArgs,
];
return { args, env, port };
}
/** The command with every key replaced by {@link API_KEY_PLACEHOLDER}. */
export function redactCommand(cmd: ContainerCommand, keys: string[]): ContainerCommand {
const hide = (v: string) => keys.filter(Boolean).reduce((acc, k) => acc.split(k).join(API_KEY_PLACEHOLDER), v);
return { ...cmd, args: cmd.args.map(hide), env: Object.fromEntries(Object.entries(cmd.env).map(([k, v]) => [k, hide(v)])) };
}
/** Shell-style rendering for display ("docker run … image args"). */
export function renderCommand(image: string, cmd: ContainerCommand): string {
const q = (s: string) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
const env = Object.entries(cmd.env).map(([k, v]) => `-e ${q(`${k}=${v}`)}`);
return ["docker run", ...env, `-v <models>:${CONTAINER_MODELS_DIR}:ro`, q(image), ...cmd.args.map(q)].join(" ");
}
/** Rough memory need: model files plus KV cache and runtime overhead. */
export function estimateMemoryMb(fileBytes: number, contextSize: number, engine: RuntimeEngine, kvCacheGb?: number | null): number {
const model = fileBytes / 2 ** 20;
// vLLM CPU: API server, engine core and worker each load torch (~3 GiB measured with v0.31.0).
if (engine === "vllm") return Math.ceil(model + (kvCacheGb ?? 4) * 1024 + 3072);
// llama.cpp: ~ctx/8 MiB of f16 KV cache per 4k tokens for small models is too model-specific to
// compute without the GGUF header; a margin that scales with context is a safe default.
return Math.ceil(model * 1.1 + 512 + contextSize / 16);
}
+285
View File
@@ -0,0 +1,285 @@
import "server-only";
import { and, asc, desc, eq, gt, inArray, isNull, ne } from "drizzle-orm";
import { z } from "zod";
import { db } from "@/lib/db/client";
import { apiKeys, deploymentLogs, deployments, type DeploymentOptions, modelFiles, models, runtimes } from "@/lib/db/schema";
import { type ModelCandidates, modelCandidates, servableBy } from "@/lib/deploy-candidates";
import { quantGroup } from "@/lib/selection";
export class DeploymentError extends Error {
constructor(
public code: "invalid" | "not_found" | "busy",
message: string,
public status: number,
) {
super(message);
}
}
const int = (min: number, max: number) => z.number().int().min(min).max(max);
export const DeploymentBody = z.object({
name: z.string().trim().min(1).max(80),
runtimeId: z.string().min(1),
modelId: z.string().min(1),
options: z.object({
modelFile: z.string().max(1024),
mmproj: z.string().max(1024).nullable().optional(),
draftFile: z.string().max(1024).nullable().optional(),
draftType: z.enum(["draft-mtp", "draft-simple"]).nullable().optional(),
contextSize: int(128, 1_048_576),
threads: int(1, 1024).nullable().optional(),
batchSize: int(1, 65_536).nullable().optional(),
ubatchSize: int(1, 65_536).nullable().optional(),
parallel: int(1, 256).nullable().optional(),
cacheTypeK: z.enum(["f32", "f16", "bf16", "q8_0", "q4_0", "q4_1", "iq4_nl", "q5_0", "q5_1"]).nullable().optional(),
cacheTypeV: z.enum(["f32", "f16", "bf16", "q8_0", "q4_0", "q4_1", "iq4_nl", "q5_0", "q5_1"]).nullable().optional(),
flashAttn: z.enum(["auto", "on", "off"]).nullable().optional(),
webui: z.boolean().nullable().optional(),
requireApiKey: z.boolean().nullable().optional(),
dtype: z.enum(["auto", "bfloat16", "float16", "float32"]).nullable().optional(),
maxNumSeqs: int(1, 1024).nullable().optional(),
kvCacheGb: z.number().min(0.25).max(1024).nullable().optional(),
extraArgs: z.array(z.string().max(4000).refine((a) => !/[\r\n\0]/.test(a), "single line")).max(100),
}),
cpus: z.number().min(0.1).max(1024).nullable().optional(),
memoryMb: int(256, 4_194_304).nullable().optional(),
hostPort: int(1024, 65_535).nullable().optional(),
});
export type DeploymentInput = z.infer<typeof DeploymentBody>;
/** Downloaded files of a model (selected and on disk). */
async function localFiles(modelId: string) {
return db()
.select({ path: modelFiles.path, size: modelFiles.size })
.from(modelFiles)
.where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true), inArray(modelFiles.state, ["present", "verified"])));
}
export type DeployableModel = { id: string; repoId: string; localPath: string; candidates: ModelCandidates };
/** Library models with something a runtime can serve. */
export async function listDeployableModels(): Promise<DeployableModel[]> {
const rows = await db().select({ id: models.id, repoId: models.repoId, localPath: models.localPath }).from(models).orderBy(asc(models.repoId));
const files = await db()
.select({ modelId: modelFiles.modelId, path: modelFiles.path, size: modelFiles.size })
.from(modelFiles)
.where(and(eq(modelFiles.selected, true), inArray(modelFiles.state, ["present", "verified"])));
const byModel = new Map<string, { path: string; size: number }[]>();
for (const f of files) byModel.set(f.modelId, [...(byModel.get(f.modelId) ?? []), f]);
return rows
.map((m) => ({ ...m, candidates: modelCandidates(byModel.get(m.id) ?? []) }))
.filter((m) => m.candidates.gguf.length > 0 || m.candidates.vllm);
}
/** Check that runtime, model and files fit together; returns normalized options. */
async function validate(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) });
if (!model) throw new DeploymentError("invalid", "Model not found.", 400);
const c = modelCandidates(await localFiles(model.id));
if (!servableBy(c, runtime.engine)) {
throw new DeploymentError("invalid", `${model.repoId} has no downloaded files ${runtime.name} can serve.`, 400);
}
const o = input.options;
const options: DeploymentOptions = { ...o, extraArgs: o.extraArgs.map((a) => a.trim()).filter(Boolean) };
if (runtime.engine === "llama.cpp") {
if (!c.gguf.some((g) => g.path === o.modelFile)) throw new DeploymentError("invalid", "Pick one of the model's downloaded GGUF files.", 400);
if (o.mmproj && !c.mmproj.some((m) => m.path === o.mmproj)) throw new DeploymentError("invalid", "Unknown mmproj file.", 400);
const draft = o.draftFile ? c.drafts.find((d) => d.path === o.draftFile) : null;
if (o.draftFile && !draft) throw new DeploymentError("invalid", "Unknown draft/MTP file.", 400);
options.draftType = draft?.type ?? null;
Object.assign(options, { dtype: null, maxNumSeqs: null, kvCacheGb: null });
} else {
Object.assign(options, { modelFile: "", mmproj: null, draftFile: null, draftType: null, batchSize: null, ubatchSize: null, cacheTypeK: null, cacheTypeV: null, flashAttn: null, webui: null });
}
if (o.requireApiKey && (await db().select({ id: apiKeys.id }).from(apiKeys).limit(1)).length === 0) {
throw new DeploymentError("invalid", "Add an API key under Settings → API keys first.", 400);
}
if (input.hostPort) {
const clash = await db().query.deployments.findFirst({
columns: { name: true },
where: and(eq(deployments.hostPort, input.hostPort), selfId ? ne(deployments.id, selfId) : undefined, isNull(deployments.deleteRequestedAt)),
});
if (clash) throw new DeploymentError("invalid", `Port ${input.hostPort} is already used by "${clash.name}".`, 409);
}
return options;
}
export async function createDeployment(input: DeploymentInput, startNow: boolean) {
const options = await validate(input);
const [row] = await db()
.insert(deployments)
.values({
name: input.name,
runtimeId: input.runtimeId,
modelId: input.modelId,
options,
cpus: input.cpus ?? null,
memoryMb: input.memoryMb ?? null,
hostPort: input.hostPort ?? null,
desiredState: startNow ? "running" : "stopped",
})
.returning({ id: deployments.id });
return row;
}
async function get(id: string) {
const d = await db().query.deployments.findFirst({ where: and(eq(deployments.id, id), isNull(deployments.deleteRequestedAt)) });
if (!d) throw new DeploymentError("not_found", "Deployment not found.", 404);
return d;
}
/** Change launch options; only while stopped (a running container keeps its command). */
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);
await db()
.update(deployments)
.set({
name: input.name,
runtimeId: input.runtimeId,
modelId: input.modelId,
options,
cpus: input.cpus ?? null,
memoryMb: input.memoryMb ?? null,
hostPort: input.hostPort ?? null,
})
.where(eq(deployments.id, id));
}
export async function setDesiredState(id: string, desired: "running" | "stopped") {
const d = await get(id);
if (d.desiredState === desired) return;
await db()
.update(deployments)
.set({ desiredState: desired, ...(desired === "running" ? { error: null } : {}) })
.where(eq(deployments.id, id));
}
/** The worker stops the container and deletes the row. */
export async function requestDelete(id: string) {
await get(id);
await db().update(deployments).set({ deleteRequestedAt: new Date(), desiredState: "stopped" }).where(eq(deployments.id, id));
}
const listColumns = {
id: deployments.id,
name: deployments.name,
state: deployments.state,
desiredState: deployments.desiredState,
options: deployments.options,
cpus: deployments.cpus,
memoryMb: deployments.memoryMb,
hostPort: deployments.hostPort,
containerName: deployments.containerName,
command: deployments.command,
startedAt: deployments.startedAt,
readyAt: deployments.readyAt,
stoppedAt: deployments.stoppedAt,
exitCode: deployments.exitCode,
error: deployments.error,
stats: deployments.stats,
createdAt: deployments.createdAt,
runtimeId: deployments.runtimeId,
runtimeName: runtimes.name,
runtimeImage: runtimes.image,
engine: runtimes.engine,
modelId: deployments.modelId,
repoId: models.repoId,
};
export type DeploymentRow = Awaited<ReturnType<typeof listDeployments>>[number];
export async function listDeployments() {
return db()
.select(listColumns)
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.innerJoin(models, eq(models.id, deployments.modelId))
.where(isNull(deployments.deleteRequestedAt))
.orderBy(desc(deployments.createdAt));
}
export async function getDeployment(id: string) {
const [row] = await db()
.select(listColumns)
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.innerJoin(models, eq(models.id, deployments.modelId))
.where(and(eq(deployments.id, id), isNull(deployments.deleteRequestedAt)));
return row ?? null;
}
export async function listDeploymentLogs(id: string, afterId: number, tail = 500) {
const rows =
afterId > 0
? await db()
.select()
.from(deploymentLogs)
.where(and(eq(deploymentLogs.deploymentId, id), gt(deploymentLogs.id, afterId)))
.orderBy(asc(deploymentLogs.id))
.limit(2000)
: (
await db().select().from(deploymentLogs).where(eq(deploymentLogs.deploymentId, id)).orderBy(desc(deploymentLogs.id)).limit(tail)
).reverse();
return rows.map((r) => ({ id: r.id, ts: r.ts.getTime(), stream: r.stream, line: r.line }));
}
/** Deployments that use a model or runtime (deleting those is refused while any exist). */
export async function deploymentsUsing(by: { modelId?: string; runtimeId?: string }) {
return db()
.select({ id: deployments.id, name: deployments.name })
.from(deployments)
.where(
and(
isNull(deployments.deleteRequestedAt),
by.modelId ? eq(deployments.modelId, by.modelId) : undefined,
by.runtimeId ? eq(deployments.runtimeId, by.runtimeId) : undefined,
),
);
}
export type ModelDeployment = { id: string; name: string; state: DeploymentRow["state"]; desiredState: DeploymentRow["desiredState"]; runtimeName: string };
/** Deployments per model id (for links from the library and model pages). */
export async function deploymentsByModel(): Promise<Map<string, ModelDeployment[]>> {
const rows = await db()
.select({
modelId: deployments.modelId,
id: deployments.id,
name: deployments.name,
state: deployments.state,
desiredState: deployments.desiredState,
runtimeName: runtimes.name,
})
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.where(isNull(deployments.deleteRequestedAt))
.orderBy(asc(deployments.name));
const out = new Map<string, ModelDeployment[]>();
for (const { modelId, ...d } of rows) out.set(modelId, [...(out.get(modelId) ?? []), d]);
return out;
}
/** Form defaults for "Deploy" from the library: the first runtime with a pulled image that can serve the model. */
export async function deployPreset(modelId: string) {
const model = (await listDeployableModels()).find((m) => m.id === modelId);
if (!model) return null;
const rts = await db().select({ id: runtimes.id, engine: runtimes.engine }).from(runtimes).where(eq(runtimes.imageState, "present")).orderBy(asc(runtimes.createdAt));
const runtime = rts.find((r) => servableBy(model.candidates, r.engine));
if (!runtime) return null;
const gguf = runtime.engine === "llama.cpp" ? model.candidates.gguf[0] : undefined;
const quant = gguf ? quantGroup(gguf.path) : null;
return {
name: `${model.repoId.split("/")[1]}${quant ? ` ${quant}` : ""}`,
runtimeId: runtime.id,
modelId: model.id,
options: { modelFile: gguf?.path ?? "", mmproj: gguf ? (model.candidates.mmproj[0]?.path ?? null) : null, contextSize: 4096, extraArgs: [] },
cpus: null,
memoryMb: null,
hostPort: null,
};
}
+8
View File
@@ -22,6 +22,14 @@ const coreSchema = z.object({
),
/** hf CLI home (token cache, Xet logs/cache). Not the model storage. */
HF_HOME: z.preprocess(emptyToUndefined, z.string().optional()),
/**
* Docker API for runtimes (worker only), e.g. tcp://docker-proxy:2375 or unix:///var/run/docker.sock.
* Unset: runtimes are disabled.
*/
DOCKER_HOST: z.preprocess(emptyToUndefined, z.string().regex(/^(tcp|unix):\/\//, "must start with tcp:// or unix://").optional()),
/** Override the auto-detected Docker network / models source (needed when the worker isn't a container). */
KANAME_DOCKER_NETWORK: z.preprocess(emptyToUndefined, z.string().optional()),
KANAME_MODELS_SOURCE: z.preprocess(emptyToUndefined, z.string().optional()),
});
const authSchema = z.object({
+22
View File
@@ -0,0 +1,22 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { argsToRows, rowsToArgs } from "./extra-args";
describe("extra args rows", () => {
it("pairs flags with their values", () => {
const tokens = ["--temp", "0.7", "--no-mmap", "--dtype=bfloat16", "--seed", "-1", "positional"];
const rows = argsToRows(tokens);
assert.deepEqual(rows, [
{ flag: "--temp", value: "0.7" },
{ flag: "--no-mmap", value: "" },
{ flag: "--dtype=bfloat16", value: "" },
{ flag: "--seed", value: "-1" },
{ flag: "", value: "positional" },
]);
assert.deepEqual(rowsToArgs(rows), tokens);
});
it("drops empty rows and trims", () => {
assert.deepEqual(rowsToArgs([{ flag: " --top-k ", value: " 40 " }, { flag: "", value: "" }]), ["--top-k", "40"]);
});
});
+24
View File
@@ -0,0 +1,24 @@
// Extra command-line arguments as editable flag/value rows. Pure; shared by the runtime and
// deployment forms. The stored form stays a token list (one argv entry per item).
export type ArgRow = { flag: string; value: string };
const isFlag = (t: string) => t.startsWith("-") && !/^-\d/.test(t);
/** Tokens → rows: a flag takes the following non-flag token as its value. */
export function argsToRows(tokens: string[]): ArgRow[] {
const rows: ArgRow[] = [];
for (const t of tokens) {
const last = rows.at(-1);
// "--flag=value" stays one token, so it is shown (and passed) exactly as written.
if (!isFlag(t) && last && last.flag && !last.value && !last.flag.includes("=")) last.value = t;
else if (isFlag(t)) rows.push({ flag: t, value: "" });
else rows.push({ flag: "", value: t });
}
return rows;
}
/** Rows → tokens, skipping empty rows. */
export function rowsToArgs(rows: ArgRow[]): string[] {
return rows.flatMap((r) => [r.flag.trim(), r.value.trim()].filter(Boolean));
}
+6
View File
@@ -1,6 +1,7 @@
import "server-only";
import { and, asc, desc, eq, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { deploymentsByModel, listDeployableModels } from "@/lib/deployments";
import { modelFiles, models, modelTags, tags } from "@/lib/db/schema";
import { modelFamilies } from "@/lib/hub/metadata";
import { fileRole } from "@/lib/file-roles";
@@ -52,6 +53,9 @@ export async function listLibrary() {
const tagsByModel = new Map<string, Tag[]>();
for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name, color: t.color }]);
const [byModel, deployable] = await Promise.all([deploymentsByModel(), listDeployableModels()]);
const deployableIds = new Set(deployable.map((m) => m.id));
return rows.map(({ updateDiff, ...r }) => ({
...r,
updateAvailable: !!updateDiff && updateDiff.sha === r.remoteSha && r.remoteSha !== r.pinnedSha,
@@ -61,6 +65,8 @@ export async function listLibrary() {
hubTags: r.hubTags ?? [],
quants: [...(quants.get(r.id) ?? [])].sort(),
tags: tagsByModel.get(r.id) ?? [],
deployable: deployableIds.has(r.id),
deployments: byModel.get(r.id) ?? [],
}));
}
+5
View File
@@ -6,6 +6,7 @@ import { jobFiles, jobs, localFolders, modelFiles, modelRevisions, models } from
import { hubMissingMessage } from "@/lib/hub/availability";
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
import { metadataColumns } from "@/lib/hub/refresh";
import { deploymentsUsing } from "@/lib/deployments";
import { hasOpenJob, queueDownload } from "@/lib/jobs";
import { getLocalFolder, requestFolderScan } from "@/lib/local-folders";
import { purgeModelRows } from "@/lib/model-purge";
@@ -102,6 +103,10 @@ export async function deleteModel(id: string, options: { deleteFiles: boolean })
if (await hasOpenJob(id)) {
throw new ModelError("busy", "A job for this model is still queued or running. Cancel it first.", 409);
}
const using = await deploymentsUsing({ modelId: id });
if (using.length > 0) {
throw new ModelError("busy", `Deployments use this model (${using.map((u) => u.name).join(", ")}). Delete them first.`, 409);
}
const [{ n }] = await d.select({ n: sql<number>`count(*)` }).from(jobs).where(eq(jobs.modelId, id));
const neverDownloaded = model.status === "pending" && n === 0;
if (!options.deleteFiles || neverDownloaded) {
+42
View File
@@ -0,0 +1,42 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { parseEnvLines, RUNTIME_PRESETS, RuntimeValidationError, validateRuntime } from "./runtimes-shared";
const base = { name: "x", engine: "vllm" as const, image: "vllm/vllm-openai-cpu:v0.31.0" };
describe("validateRuntime", () => {
it("accepts the presets and common image references", () => {
for (const p of RUNTIME_PRESETS) assert.doesNotThrow(() => validateRuntime(p));
for (const image of [
"ghcr.io/ggml-org/llama.cpp:server",
"git.linxweiler.xyz/me/vllm-arc:0.9-patched",
"localhost:5000/vllm",
`vllm/vllm-openai-xpu@sha256:${"a".repeat(64)}`,
]) {
assert.equal(validateRuntime({ ...base, image }).image, image);
}
});
it("rejects bad images, env names, devices and multi-line values", () => {
const bad = (patch: object) => assert.throws(() => validateRuntime({ ...base, ...patch }), RuntimeValidationError);
bad({ image: "Vllm/Upper:tag" });
bad({ image: "vllm/vllm --privileged" });
bad({ env: { "BAD-KEY": "1" } });
bad({ env: { OK: "a\nb" } });
bad({ devices: ["/dev/sda"] });
bad({ devices: ["/"] });
bad({ extraArgs: ["--a\n--b"] });
bad({ name: " " });
assert.deepEqual(validateRuntime({ ...base, devices: ["/dev/dri", "/dev/dri/renderD128"] }).devices, [
"/dev/dri",
"/dev/dri/renderD128",
]);
});
});
describe("parseEnvLines", () => {
it("parses KEY=value lines, skipping blanks and comments", () => {
assert.deepEqual(parseEnvLines("A=1\n\n# note\nB = x=y \n"), { A: "1", B: "x=y" });
assert.throws(() => parseEnvLines("novalue"), RuntimeValidationError);
});
});
+105
View File
@@ -0,0 +1,105 @@
// Runtime presets and validation. Pure (no DB), shared by the web app, the worker and tests.
import type { RuntimeEngine } from "@/lib/db/schema";
export type RuntimeInput = {
name: string;
engine: RuntimeEngine;
image: string;
description?: string | null;
env?: Record<string, string>;
extraArgs?: string[];
devices?: string[];
shmSizeMb?: number | null;
numaTuning?: boolean;
};
export type RuntimePreset = RuntimeInput & { id: string; summary: string };
/** Starting points; verified against the images (llama.cpp build 11429, vLLM v0.31.0). */
export const RUNTIME_PRESETS: RuntimePreset[] = [
{
id: "llama.cpp-cpu",
name: "llama.cpp (CPU)",
engine: "llama.cpp",
image: "ghcr.io/ggml-org/llama.cpp:server",
summary: "Official llama-server image, CPU build. Serves GGUF models.",
description: "Official llama.cpp server, CPU build. Pin a build tag (e.g. server-b11429) for reproducible tests.",
},
{
id: "vllm-cpu",
name: "vLLM (CPU)",
engine: "vllm",
image: "vllm/vllm-openai-cpu:v0.31.0",
summary: "Official vLLM CPU image. Serves safetensors models (BF16 recommended on AMD Zen).",
description: "Official vLLM CPU build. VLLM_CPU_KVCACHE_SPACE is the KV cache size in GiB.",
env: { VLLM_CPU_KVCACHE_SPACE: "4" },
extraArgs: ["--dtype=bfloat16"],
shmSizeMb: 4096,
},
];
export const RUNTIME_NAME_MAX = 60;
// [registry[:port]/]path[:tag][@sha256:digest], lowercase path components as Docker requires.
const IMAGE_RE =
/^(?:[a-z0-9]+(?:[.-][a-z0-9]+)*(?::\d+)?\/)?[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)*(?::[\w][\w.-]{0,127})?(?:@sha256:[a-f0-9]{64})?$/;
const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
/** Device passthrough is limited to GPU device nodes (Intel/AMD: /dev/dri, AMD: /dev/kfd). */
const DEVICE_RE = /^\/dev\/(dri(\/[\w.-]+)?|kfd)$/;
export class RuntimeValidationError extends Error {}
/** Normalize and validate a runtime definition; throws RuntimeValidationError with a readable message. */
export function validateRuntime(input: RuntimeInput): Required<RuntimeInput> {
const name = input.name.trim().replace(/\s+/g, " ");
if (!name || name.length > RUNTIME_NAME_MAX) throw new RuntimeValidationError(`Name must be 1–${RUNTIME_NAME_MAX} characters.`);
if (input.engine !== "llama.cpp" && input.engine !== "vllm") throw new RuntimeValidationError("Unknown engine type.");
const image = input.image.trim();
if (!IMAGE_RE.test(image)) throw new RuntimeValidationError(`"${image}" is not a valid image reference (e.g. ghcr.io/org/image:tag).`);
const env: Record<string, string> = {};
for (const [k, v] of Object.entries(input.env ?? {})) {
if (!ENV_KEY_RE.test(k)) throw new RuntimeValidationError(`Invalid environment variable name "${k}".`);
if (/[\r\n\0]/.test(v)) throw new RuntimeValidationError(`Value of ${k} must be a single line.`);
env[k] = v;
}
const extraArgs = (input.extraArgs ?? []).map((a) => a.trim()).filter(Boolean);
for (const a of extraArgs) if (/[\r\n\0]/.test(a)) throw new RuntimeValidationError("Arguments must be single lines.");
const devices = (input.devices ?? []).map((d) => d.trim()).filter(Boolean);
for (const d of devices) {
if (!DEVICE_RE.test(d)) throw new RuntimeValidationError(`Device "${d}" isn't allowed (only /dev/dri… and /dev/kfd).`);
}
const shm = input.shmSizeMb ?? null;
if (shm != null && (!Number.isInteger(shm) || shm < 64 || shm > 262_144)) {
throw new RuntimeValidationError("Shared memory must be between 64 MiB and 256 GiB.");
}
return {
name,
engine: input.engine,
image,
description: input.description?.trim() || null,
env,
extraArgs,
devices,
shmSizeMb: shm,
numaTuning: !!input.numaTuning,
};
}
/** "KEY=value" lines ⇄ env object (for the editor). */
export function parseEnvLines(text: string): Record<string, string> {
const out: Record<string, string> = {};
for (const raw of text.split(/\r?\n/)) {
const line = raw.trim();
if (!line || line.startsWith("#")) continue;
const eq = line.indexOf("=");
if (eq <= 0) throw new RuntimeValidationError(`"${line}" isn't KEY=value.`);
out[line.slice(0, eq).trim()] = line.slice(eq + 1).trim();
}
return out;
}
export const formatEnvLines = (env: Record<string, string>) =>
Object.entries(env)
.map(([k, v]) => `${k}=${v}`)
.join("\n");
+102
View File
@@ -0,0 +1,102 @@
import "server-only";
import { asc, eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "@/lib/db/client";
import { type DockerHostInfo, runtimes, workerState } from "@/lib/db/schema";
import { deploymentsUsing } from "@/lib/deployments";
import { type RuntimeInput, RUNTIME_PRESETS, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
export type Runtime = typeof runtimes.$inferSelect;
/** Request body for creating/updating a runtime (validated further by validateRuntime). */
export const RuntimeBody = z.object({
name: z.string().max(200),
engine: z.enum(["llama.cpp", "vllm"]),
image: z.string().max(512),
description: z.string().max(2000).nullable().optional(),
env: z.record(z.string(), z.string().max(4000)).optional(),
extraArgs: z.array(z.string().max(4000)).max(200).optional(),
devices: z.array(z.string().max(200)).max(20).optional(),
shmSizeMb: z.number().int().nullable().optional(),
numaTuning: z.boolean().optional(),
});
export class RuntimeError extends Error {
constructor(
public code: "invalid" | "not_found",
message: string,
public status: number,
) {
super(message);
}
}
function validated(input: RuntimeInput) {
try {
return validateRuntime(input);
} catch (err) {
if (err instanceof RuntimeValidationError) throw new RuntimeError("invalid", err.message, 400);
throw err;
}
}
export async function listRuntimes(): Promise<Runtime[]> {
return db().select().from(runtimes).orderBy(asc(runtimes.createdAt));
}
export async function getRuntime(id: string): Promise<Runtime> {
const r = await db().query.runtimes.findFirst({ where: eq(runtimes.id, id) });
if (!r) throw new RuntimeError("not_found", "Runtime not found.", 404);
return r;
}
export async function createRuntime(input: RuntimeInput & { preset?: string }): Promise<Runtime> {
const v = validated(input);
const preset = input.preset && RUNTIME_PRESETS.some((p) => p.id === input.preset) ? input.preset : null;
const [row] = await db()
.insert(runtimes)
.values({ ...v, preset })
.returning();
return row;
}
export async function updateRuntime(id: string, input: RuntimeInput): Promise<Runtime> {
const current = await getRuntime(id);
const v = validated(input);
const imageChanged = v.image !== current.image;
const [row] = await db()
.update(runtimes)
.set({
...v,
// A different image has to be looked up (and maybe pulled) again.
...(imageChanged ? { imageState: "unknown", imageId: null, imageSize: null, imageCreated: null, pullError: null } : {}),
})
.where(eq(runtimes.id, id))
.returning();
return row;
}
export async function deleteRuntime(id: string): Promise<void> {
await getRuntime(id);
const using = await deploymentsUsing({ runtimeId: id });
if (using.length > 0) {
throw new RuntimeError("invalid", `Deployments use this runtime (${using.map((u) => u.name).join(", ")}). Delete them first.`, 409);
}
await db().delete(runtimes).where(eq(runtimes.id, id));
}
/** Ask the worker to pull (or re-pull, to update a moving tag) the runtime's image. */
export async function requestPull(id: string): Promise<void> {
await getRuntime(id);
await db().update(runtimes).set({ pullRequestedAt: new Date(), pullError: null }).where(eq(runtimes.id, id));
}
/** Docker facts as last reported by the worker; null when DOCKER_HOST isn't configured. */
export async function getDockerInfo(): Promise<DockerHostInfo | null> {
try {
const row = await db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") });
return row?.docker ?? null;
} catch {
return null;
}
}
+328
View File
@@ -0,0 +1,328 @@
// Deployments: the worker keeps runtime containers in line with what the web app asked for
// (desiredState), follows their logs, checks health and samples CPU/memory. Containers keep running
// across worker restarts; the worker re-attaches to them.
import { stat } from "node:fs/promises";
import { join } from "node:path";
import { and, asc, desc, eq, inArray, lt } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { apiKeys, deploymentLogs, deployments, type LogStream, models, runtimes, workerState } from "@/lib/db/schema";
import { buildCommand, CONTAINER_MODELS_DIR, ENGINE_PORT, redactCommand, renderCommand } from "@/lib/deploy-command";
import { coreEnv } from "@/lib/env";
import { formatBytes } from "@/lib/format";
import { sanitizeLine } from "./job-log";
import { log } from "./log";
import { errorCauses } from "./log-causes";
import { docker } from "./runtimes";
import type { DockerClient } from "./docker/client";
type Deployment = typeof deployments.$inferSelect;
const LABEL = "kaname.deployment";
const STATS_MS = 5_000;
const LOG_FLUSH_MS = 1_000;
const LOG_KEEP = 5_000;
/** Give up on a container that isn't healthy after this long (big models load slowly on CPU). */
const START_TIMEOUT_MS = 30 * 60_000;
/** Leave this much of the host's memory to the system and other containers. */
const MEMORY_RESERVE_MB = 2048;
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
const slug = (s: string) =>
s
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "")
.slice(0, 40) || "model";
// --- logs ------------------------------------------------------------------------------------
const followers = new Map<string, AbortController>();
const pending: { deploymentId: string; stream: LogStream; line: string; ts: Date }[] = [];
// API key values, refreshed every reconcile pass: hidden in every log line (vLLM prints its
// arguments, including --api-key, at startup).
let apiKeySecrets: string[] = [];
async function loadApiKeys(): Promise<string[]> {
apiKeySecrets = (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt))).map((r) => r.key);
return apiKeySecrets;
}
function addLog(deploymentId: string, stream: LogStream, line: string) {
pending.push({ deploymentId, stream, line: sanitizeLine(line, [coreEnv().HF_TOKEN ?? "", ...apiKeySecrets]).slice(0, 4000), ts: new Date() });
}
export async function flushDeploymentLogs(): Promise<void> {
if (pending.length === 0) return;
const batch = pending.splice(0, pending.length);
for (let i = 0; i < batch.length; i += 500) await db().insert(deploymentLogs).values(batch.slice(i, i + 500));
// Keep the newest LOG_KEEP lines per deployment.
for (const id of new Set(batch.map((b) => b.deploymentId))) {
const [cut] = await db()
.select({ id: deploymentLogs.id })
.from(deploymentLogs)
.where(eq(deploymentLogs.deploymentId, id))
.orderBy(desc(deploymentLogs.id))
.limit(1)
.offset(LOG_KEEP);
if (cut) await db().delete(deploymentLogs).where(and(eq(deploymentLogs.deploymentId, id), lt(deploymentLogs.id, cut.id)));
}
}
function follow(c: DockerClient, d: { id: string; containerId: string }, tail: number | "all" = 0) {
followers.get(d.id)?.abort();
const ctl = new AbortController();
followers.set(d.id, ctl);
c.followLogs(d.containerId, (stream, line) => addLog(d.id, stream, line), { tail, signal: ctl.signal })
.catch((err) => !ctl.signal.aborted && log.warn(`logs of deployment ${d.id}: ${message(err)}`))
.finally(() => followers.get(d.id) === ctl && followers.delete(d.id));
}
function unfollow(id: string) {
followers.get(id)?.abort();
followers.delete(id);
}
// --- start / stop ------------------------------------------------------------------------------
async function update(id: string, set: Partial<Deployment>) {
await db().update(deployments).set(set).where(eq(deployments.id, id));
}
async function fail(d: Deployment, error: string, exitCode: number | null = null) {
addLog(d.id, "system", `Failed: ${error}`);
log.warn(`deployment ${d.name}: ${error}`);
// desiredState stopped, so the worker doesn't retry in a loop.
await update(d.id, { state: "failed", desiredState: "stopped", error, exitCode, stoppedAt: new Date(), stats: null });
}
async function start(c: DockerClient, d: Deployment) {
const [runtime, model, ws] = await Promise.all([
db().query.runtimes.findFirst({ where: eq(runtimes.id, d.runtimeId) }),
db().query.models.findFirst({ where: eq(models.id, d.modelId) }),
db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") }),
]);
if (!runtime) return fail(d, "The runtime was deleted.");
if (!model) return fail(d, "The model was deleted.");
const host = ws?.docker;
if (!host?.connected) return fail(d, "Docker isn't connected.");
if (!host.network || !host.modelsSource) {
return fail(d, "The Docker network or the models source wasn't detected (see Settings → Runtimes).");
}
const image = await c.inspectImage(runtime.image);
if (!image) return fail(d, `Image ${runtime.image} isn't pulled yet (Settings → Runtimes → Pull).`);
// The files must be there (the worker sees the same models folder the container gets).
for (const f of [d.options.modelFile, d.options.mmproj, d.options.draftFile]) {
if (f == null || (f === "" && runtime.engine !== "vllm")) continue;
const path = join(coreEnv().MODELS_DIR, model.localPath, f);
if (!(await stat(path).catch(() => null))) return fail(d, `File not found: ${model.localPath}/${f}. Is the model downloaded?`);
}
// Memory: what the other running deployments reserve plus this one must fit.
if (d.memoryMb && host.memoryBytes) {
const others = await db()
.select({ memoryMb: deployments.memoryMb })
.from(deployments)
.where(and(inArray(deployments.state, ["starting", "running"])));
const used = others.reduce((s, o) => s + (o.memoryMb ?? 0), 0);
const available = host.memoryBytes / 2 ** 20 - MEMORY_RESERVE_MB - used;
if (d.memoryMb > available) {
return fail(
d,
`Not enough memory: ${formatBytes(d.memoryMb * 2 ** 20)} requested, ${formatBytes(Math.max(0, available) * 2 ** 20)} left for deployments (running ones reserve ${formatBytes(used * 2 ** 20)}).`,
);
}
}
const keys = d.options.requireApiKey ? await loadApiKeys() : [];
if (d.options.requireApiKey && keys.length === 0) return fail(d, "This deployment requires an API key, but there are none. Add one under Settings → API keys.");
const cmd = buildCommand({ engine: runtime.engine, options: d.options, model, runtime, apiKeys: keys });
// What Kaname shows and stores: never the key values.
const shown = redactCommand(cmd, keys);
const name = `kaname-${slug(d.name)}-${d.id.slice(-6).toLowerCase()}`;
const portKey = `${cmd.port}/tcp`;
const spec = {
Image: runtime.image,
Cmd: cmd.args,
Env: Object.entries(cmd.env).map(([k, v]) => `${k}=${v}`),
Labels: { [LABEL]: d.id, "kaname.managed": "true" },
ExposedPorts: { [portKey]: {} },
HostConfig: {
Mounts: [{ Type: host.modelsSource.type, Source: host.modelsSource.source, Target: CONTAINER_MODELS_DIR, ReadOnly: true }],
NanoCpus: d.cpus ? Math.round(d.cpus * 1e9) : 0,
Memory: d.memoryMb ? d.memoryMb * 2 ** 20 : 0,
ShmSize: runtime.shmSizeMb ? runtime.shmSizeMb * 2 ** 20 : undefined,
Devices: runtime.devices.map((p) => ({ PathOnHost: p, PathInContainer: p, CgroupPermissions: "rwm" })),
CapAdd: runtime.numaTuning ? ["SYS_NICE"] : [],
SecurityOpt: runtime.numaTuning ? ["seccomp=unconfined"] : [],
PortBindings: d.hostPort ? { [portKey]: [{ HostPort: String(d.hostPort) }] } : {},
Privileged: false,
Init: true,
RestartPolicy: { Name: "no" },
},
NetworkingConfig: { EndpointsConfig: { [host.network]: {} } },
};
addLog(d.id, "system", `Starting ${runtime.name} (${runtime.image})`);
addLog(d.id, "system", `$ ${renderCommand(runtime.image, shown)}`);
try {
await c.removeContainer(name); // leftover from a crash
const created = await c.createContainer(name, spec);
for (const w of created.Warnings ?? []) addLog(d.id, "system", `Docker: ${w}`);
await update(d.id, {
state: "starting",
containerId: created.Id,
containerName: name,
command: shown.args,
imageId: image.Id,
startedAt: new Date(),
readyAt: null,
stoppedAt: null,
error: null,
exitCode: null,
stats: null,
});
await c.startContainer(created.Id);
// A fresh container: everything it printed belongs to this run. (Following before the start
// returns an empty, already-closed stream.)
follow(c, { id: d.id, containerId: created.Id }, "all");
log.info(`deployment ${d.name}: started ${name}`);
} catch (err) {
await c.removeContainer(name).catch(() => {});
await fail(d, `Docker: ${message(err)}`);
}
}
async function stopContainer(c: DockerClient, d: Deployment) {
if (d.containerId) {
await update(d.id, { state: "stopping" });
await c.stopContainer(d.containerId, 15);
await c.removeContainer(d.containerId);
}
unfollow(d.id);
addLog(d.id, "system", "Stopped.");
await update(d.id, { state: "stopped", stoppedAt: new Date(), stats: null, containerId: null });
}
/** Likely causes plus the tail of the log, for error messages. */
async function failureDetails(id: string, tail = 15): Promise<string> {
await flushDeploymentLogs();
const lines = (
await db().select({ line: deploymentLogs.line }).from(deploymentLogs).where(eq(deploymentLogs.deploymentId, id)).orderBy(desc(deploymentLogs.id)).limit(2000)
)
.reverse()
.map((r) => r.line);
const causes = errorCauses(lines);
const last = lines.slice(-tail).join("\n");
return [causes.join("\n"), last && (causes.length ? `Last output:\n${last}` : last)].filter(Boolean).join("\n\n");
}
async function healthy(name: string, port: number): Promise<boolean> {
try {
const res = await fetch(`http://${name}:${port}/health`, { signal: AbortSignal.timeout(2_000) });
return res.ok;
} catch {
return false;
}
}
// --- reconcile -----------------------------------------------------------------------------------
const lastStats = new Map<string, number>();
async function reconcileOne(c: DockerClient, d: Deployment) {
if (d.deleteRequestedAt) {
if (d.containerId) {
await c.stopContainer(d.containerId, 15).catch(() => {});
await c.removeContainer(d.containerId).catch(() => {});
}
unfollow(d.id);
pending.splice(0, pending.length, ...pending.filter((p) => p.deploymentId !== d.id));
await db().batch([db().delete(deploymentLogs).where(eq(deploymentLogs.deploymentId, d.id)), db().delete(deployments).where(eq(deployments.id, d.id))]);
log.info(`deployment ${d.name} deleted`);
return;
}
if (d.desiredState === "stopped") {
if (d.state === "starting" || d.state === "running" || d.state === "stopping") await stopContainer(c, d);
return;
}
// desired: running
if (d.state === "stopped" || d.state === "failed") return start(c, d);
if (!d.containerId || !d.containerName) return fail(d, "Container is missing.");
const st = await c.containerState(d.containerId);
if (!st || !st.Running) {
const why = st?.OOMKilled ? "out of memory (raise the memory limit)" : `exit code ${st?.ExitCode ?? "?"}`;
unfollow(d.id);
const tail = await failureDetails(d.id);
await c.removeContainer(d.containerId).catch(() => {});
return fail(d, `The container stopped (${why}).${tail ? `\n${tail}` : ""}`, st?.ExitCode ?? null);
}
if (!followers.has(d.id)) follow(c, { id: d.id, containerId: d.containerId });
const runtime = await db().query.runtimes.findFirst({ columns: { engine: true }, where: eq(runtimes.id, d.runtimeId) });
const port = ENGINE_PORT[runtime?.engine ?? "llama.cpp"];
if (d.state === "starting") {
if (await healthy(d.containerName, port)) {
const now = new Date();
const secs = d.startedAt ? ((now.getTime() - d.startedAt.getTime()) / 1000).toFixed(1) : "?";
addLog(d.id, "system", `Ready after ${secs} s.`);
await update(d.id, { state: "running", readyAt: now });
} else if (d.startedAt && Date.now() - d.startedAt.getTime() > START_TIMEOUT_MS) {
await c.stopContainer(d.containerId).catch(() => {});
await c.removeContainer(d.containerId).catch(() => {});
return fail(d, "Not healthy after 30 minutes.");
}
}
if (Date.now() - (lastStats.get(d.id) ?? 0) >= STATS_MS) {
lastStats.set(d.id, Date.now());
const s = await c.containerStats(d.containerId).catch(() => null);
if (s) await update(d.id, { stats: { ...s, at: new Date().toISOString() } });
}
}
let reconciling = false;
export async function reconcileDeployments(): Promise<void> {
const c = docker();
if (!c || reconciling) return;
reconciling = true;
try {
await loadApiKeys();
for (const d of await db().select().from(deployments)) {
await reconcileOne(c, d).catch((err) => log.error(`deployment ${d.name}`, err));
}
} finally {
reconciling = false;
}
}
/** After a worker restart: re-attach to running containers, remove ones no deployment owns. */
export async function adoptContainers(): Promise<void> {
const c = docker();
if (!c) return;
try {
const rows = await db().select({ id: deployments.id, containerId: deployments.containerId, state: deployments.state }).from(deployments);
const byId = new Map(rows.map((r) => [r.id, r]));
for (const ct of await c.listContainers(LABEL)) {
const owner = byId.get(ct.Labels[LABEL]);
if (!owner || owner.containerId !== ct.Id) {
await c.removeContainer(ct.Id);
log.info(`removed orphaned container ${ct.Names[0] ?? ct.Id}`);
} else if (ct.State === "running") {
follow(c, { id: owner.id, containerId: ct.Id });
}
}
} catch (err) {
log.warn(`adopting deployment containers failed: ${message(err)}`);
}
}
export function stopFollowingLogs() {
for (const id of [...followers.keys()]) unfollow(id);
}
export const LOG_FLUSH_INTERVAL_MS = LOG_FLUSH_MS;
+270
View File
@@ -0,0 +1,270 @@
// Minimal Docker Engine API client (no dependencies): HTTP over TCP (socket proxy) or a unix socket.
// Only the endpoints Kaname needs. Paths are unversioned, so the daemon's own API version is used.
import http from "node:http";
export class DockerError extends Error {
constructor(
message: string,
public status: number | null,
) {
super(message);
this.name = "DockerError";
}
}
type Target = { socketPath: string } | { host: string; port: number };
function parseHost(dockerHost: string): Target {
if (dockerHost.startsWith("unix://")) return { socketPath: dockerHost.slice("unix://".length) };
const url = new URL(dockerHost.replace(/^tcp:/, "http:"));
return { host: url.hostname, port: Number(url.port || 2375) };
}
export class DockerClient {
private target: Target;
constructor(dockerHost: string) {
this.target = parseHost(dockerHost);
}
private raw(method: string, path: string, body?: unknown, timeoutMs = 30_000): Promise<http.IncomingMessage> {
return new Promise((resolve, reject) => {
const payload = body === undefined ? undefined : JSON.stringify(body);
const req = http.request(
{
...this.target,
method,
path,
headers: { Host: "docker", ...(payload ? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) } : {}) },
timeout: timeoutMs,
},
resolve,
);
req.on("timeout", () => req.destroy(new DockerError(`Docker API ${method} ${path} timed out`, null)));
req.on("error", (err) =>
reject(err instanceof DockerError ? err : new DockerError(`Can't reach Docker (${err.message})`, null)),
);
if (payload) req.write(payload);
req.end();
});
}
private async json<T>(method: string, path: string, body?: unknown): Promise<T> {
const res = await this.raw(method, path, body);
const chunks: Buffer[] = [];
for await (const c of res) chunks.push(c as Buffer);
const text = Buffer.concat(chunks).toString("utf8");
if ((res.statusCode ?? 500) >= 400) {
let message = text;
try {
message = JSON.parse(text).message ?? text;
} catch {}
if (res.statusCode === 403) message = `Docker API refused ${method} ${path} (socket proxy permissions?): ${message}`;
throw new DockerError(message.trim() || `HTTP ${res.statusCode}`, res.statusCode ?? null);
}
return (text ? JSON.parse(text) : null) as T;
}
version() {
return this.json<{ Version: string; ApiVersion: string; Os: string; Arch: string }>("GET", "/version");
}
info() {
return this.json<{ NCPU: number; MemTotal: number; OperatingSystem: string; Architecture: string; ServerVersion: string }>(
"GET",
"/info",
);
}
/** Inspect a container; null if it doesn't exist. */
async inspectContainer(id: string) {
try {
return await this.json<{
Id: string;
Name: string;
Mounts: { Type: string; Source: string; Destination: string; Name?: string }[];
NetworkSettings: { Networks: Record<string, unknown> };
}>("GET", `/containers/${encodeURIComponent(id)}/json`);
} catch (err) {
if (err instanceof DockerError && err.status === 404) return null;
throw err;
}
}
/** Containers with a label (e.g. "kaname.deployment"), running or not. */
listContainers(label: string) {
const filters = encodeURIComponent(JSON.stringify({ label: [label] }));
return this.json<{ Id: string; Names: string[]; State: string; Labels: Record<string, string> }[]>(
"GET",
`/containers/json?all=1&filters=${filters}`,
);
}
createContainer(name: string, spec: unknown) {
return this.json<{ Id: string; Warnings: string[] }>("POST", `/containers/create?name=${encodeURIComponent(name)}`, spec);
}
async startContainer(id: string) {
await this.json("POST", `/containers/${encodeURIComponent(id)}/start`);
}
/** Stop (SIGTERM, SIGKILL after `timeout` s); ignores "already stopped". */
async stopContainer(id: string, timeout = 10) {
try {
await this.json("POST", `/containers/${encodeURIComponent(id)}/stop?t=${timeout}`);
} catch (err) {
if (!(err instanceof DockerError && (err.status === 304 || err.status === 404))) throw err;
}
}
/** Remove a container (forced); ignores "no such container". */
async removeContainer(id: string) {
try {
await this.json("DELETE", `/containers/${encodeURIComponent(id)}?force=1`);
} catch (err) {
if (!(err instanceof DockerError && err.status === 404)) throw err;
}
}
async containerState(id: string) {
const c = await this.json<{ State: { Status: string; Running: boolean; ExitCode: number; Error: string; OOMKilled: boolean } } | null>(
"GET",
`/containers/${encodeURIComponent(id)}/json`,
).catch((err) => {
if (err instanceof DockerError && err.status === 404) return null;
throw err;
});
return c?.State ?? null;
}
/** One stats sample: CPU % (of one core = 100) and memory. */
async containerStats(id: string): Promise<{ cpuPercent: number; memoryBytes: number; memoryLimitBytes: number }> {
const s = await this.json<{
cpu_stats: { cpu_usage: { total_usage: number }; system_cpu_usage: number; online_cpus: number };
precpu_stats: { cpu_usage: { total_usage: number }; system_cpu_usage: number };
memory_stats: { usage?: number; limit?: number; stats?: { inactive_file?: number; cache?: number } };
}>("GET", `/containers/${encodeURIComponent(id)}/stats?stream=false`);
const cpuDelta = s.cpu_stats.cpu_usage.total_usage - (s.precpu_stats.cpu_usage?.total_usage ?? 0);
const sysDelta = s.cpu_stats.system_cpu_usage - (s.precpu_stats.system_cpu_usage ?? 0);
const cpuPercent = sysDelta > 0 ? (cpuDelta / sysDelta) * (s.cpu_stats.online_cpus || 1) * 100 : 0;
// Like `docker stats`: usage minus page cache.
const cache = s.memory_stats.stats?.inactive_file ?? s.memory_stats.stats?.cache ?? 0;
return {
cpuPercent: Math.round(cpuPercent * 10) / 10,
memoryBytes: Math.max(0, (s.memory_stats.usage ?? 0) - cache),
memoryLimitBytes: s.memory_stats.limit ?? 0,
};
}
/**
* Follow a container's stdout/stderr (from now, plus the last `tail` lines or "all"). The stream uses
* Docker's multiplexed format (8-byte frame headers) for containers without a TTY. Resolves when
* the container stops or `signal` aborts.
*/
async followLogs(
id: string,
onLine: (stream: "stdout" | "stderr", line: string) => void,
options: { tail?: number | "all"; signal?: AbortSignal } = {},
): Promise<void> {
const res = await this.raw(
"GET",
`/containers/${encodeURIComponent(id)}/logs?follow=1&stdout=1&stderr=1&tail=${options.tail ?? 0}`,
undefined,
0,
);
if ((res.statusCode ?? 500) >= 400) throw new DockerError(`logs: HTTP ${res.statusCode}`, res.statusCode ?? null);
options.signal?.addEventListener("abort", () => res.destroy());
let buf = Buffer.alloc(0);
const partial = { stdout: "", stderr: "" };
const emit = (stream: "stdout" | "stderr", text: string) => {
const parts = (partial[stream] + text).split(/\r?\n|\r/);
partial[stream] = parts.pop() ?? "";
for (const p of parts) if (p.trim()) onLine(stream, p);
};
try {
for await (const chunk of res) {
buf = Buffer.concat([buf, chunk as Buffer]);
while (buf.length >= 8) {
const size = buf.readUInt32BE(4);
if (buf.length < 8 + size) break;
emit(buf[0] === 2 ? "stderr" : "stdout", buf.subarray(8, 8 + size).toString("utf8"));
buf = buf.subarray(8 + size);
}
}
} catch (err) {
if (!options.signal?.aborted) throw err;
}
for (const s of ["stdout", "stderr"] as const) if (partial[s].trim()) onLine(s, partial[s]);
}
/** Inspect a local image; null if it isn't pulled. */
async inspectImage(ref: string) {
try {
return await this.json<{ Id: string; Size: number; Created: string; RepoDigests: string[] }>(
"GET",
`/images/${encodeURIComponent(ref)}/json`,
);
} catch (err) {
if (err instanceof DockerError && err.status === 404) return null;
throw err;
}
}
/**
* Pull an image. The daemon streams JSON lines per layer; `onProgress` gets the summed bytes of
* all layers seen so far. Resolves when the pull finished, rejects on an error line.
*/
async pullImage(ref: string, onProgress: (p: { doneBytes: number; totalBytes: number; status: string }) => void): Promise<void> {
const at = ref.lastIndexOf("@") > 0 ? ref.lastIndexOf("@") : -1;
const colon = ref.lastIndexOf(":");
const hasTag = at === -1 && colon > ref.lastIndexOf("/");
const fromImage = at !== -1 ? ref : hasTag ? ref.slice(0, colon) : ref;
const tag = at !== -1 ? "" : hasTag ? ref.slice(colon + 1) : "latest";
const query = new URLSearchParams({ fromImage, ...(tag ? { tag } : {}) });
const res = await this.raw("POST", `/images/create?${query}`, undefined, 60 * 60_000);
if ((res.statusCode ?? 500) >= 400) {
const chunks: Buffer[] = [];
for await (const c of res) chunks.push(c as Buffer);
const text = Buffer.concat(chunks).toString("utf8");
let message = text;
try {
message = JSON.parse(text).message ?? text;
} catch {}
throw new DockerError(message.trim(), res.statusCode ?? null);
}
const layers = new Map<string, { current: number; total: number }>();
let buffer = "";
let status = "Pulling";
for await (const chunk of res) {
buffer += (chunk as Buffer).toString("utf8");
let nl: number;
while ((nl = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, nl).trim();
buffer = buffer.slice(nl + 1);
if (!line) continue;
const msg = JSON.parse(line) as {
id?: string;
status?: string;
error?: string;
progressDetail?: { current?: number; total?: number };
};
if (msg.error) throw new DockerError(msg.error, null);
if (msg.status) status = msg.status;
if (msg.id && msg.status === "Downloading" && msg.progressDetail?.total) {
layers.set(msg.id, { current: msg.progressDetail.current ?? 0, total: msg.progressDetail.total });
} else if (msg.id && (msg.status === "Download complete" || msg.status === "Pull complete" || msg.status === "Already exists")) {
const l = layers.get(msg.id);
if (l) l.current = l.total;
}
let done = 0;
let total = 0;
for (const l of layers.values()) {
done += l.current;
total += l.total;
}
onProgress({ doneBytes: done, totalBytes: total, status });
}
}
}
}
+27
View File
@@ -12,9 +12,11 @@ import { coreEnv } from "@/lib/env";
import { checkHub, modelsDueForHubCheck } from "@/lib/hub/availability";
import { backfillMetadata } from "@/lib/hub/refresh";
import { DeleteRunner } from "./delete";
import { adoptContainers, flushDeploymentLogs, LOG_FLUSH_INTERVAL_MS, reconcileDeployments, stopFollowingLogs } from "./deployments";
import { DownloadRunner } from "./download";
import { log } from "./log";
import type { Runner } from "./runner";
import { docker, handlePullRequests, refreshDockerInfo, resetStalePulls, seedRuntimePresets, syncImageStates } from "./runtimes";
import { scanModelsDir } from "./scan";
import { VerifyRunner } from "./verify";
import { settleModelStatus } from "./model-status";
@@ -28,6 +30,10 @@ const SHUTDOWN_GRACE_MS = 8_000;
const HUB_CHECK_SCAN_MS = 10 * 60_000;
/** How often MODELS_DIR is scanned for folders that could be imported (plus on request). */
const FOLDER_SCAN_MS = 2 * 60_000;
const DOCKER_INFO_MS = 5 * 60_000;
const IMAGE_SYNC_MS = 60_000;
const PULL_CHECK_MS = 3_000;
const DEPLOYMENT_TICK_MS = 2_000;
/** Touched on every heartbeat; the Docker healthcheck checks its age. */
const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive");
@@ -339,6 +345,9 @@ async function shutdown(reason: string, code = 0) {
stopping = true;
log.info(`shutting down (${reason})`);
timers.forEach(clearInterval);
// Deployment containers keep running; the next worker re-attaches to them.
stopFollowingLogs();
await flushDeploymentLogs().catch(() => {});
if (runners.size > 0) {
for (const r of runners.values()) r.interrupt();
const deadline = Date.now() + SHUTDOWN_GRACE_MS;
@@ -377,6 +386,24 @@ async function main() {
timers.push(setInterval(() => void tick(), TICK_MS));
timers.push(setInterval(() => void checkHubDue(), HUB_CHECK_SCAN_MS));
timers.push(setInterval(() => void scanFolders(), FOLDER_SCAN_MS));
// Runtimes (Docker): presets, host facts, image states, pulls.
await resetStalePulls();
await seedRuntimePresets().catch((err) => log.error("seeding runtime presets failed", err));
if (docker()) log.info(`Docker API: ${coreEnv().DOCKER_HOST}`);
else log.info("DOCKER_HOST not set; runtimes are disabled");
const dockerInfo = () => refreshDockerInfo(instanceId).catch((err) => log.error("Docker info failed", err));
const imageSync = () => syncImageStates().catch((err) => log.error("image sync failed", err));
await dockerInfo();
void imageSync();
timers.push(setInterval(() => void dockerInfo(), DOCKER_INFO_MS));
timers.push(setInterval(() => void imageSync(), IMAGE_SYNC_MS));
timers.push(setInterval(() => void handlePullRequests().catch((err) => log.error("pull failed", err)), PULL_CHECK_MS));
// Deployments: re-attach to running containers, then keep them in line with the desired state.
await adoptContainers();
timers.push(setInterval(() => void reconcileDeployments().catch((err) => log.error("deployments failed", err)), DEPLOYMENT_TICK_MS));
timers.push(setInterval(() => void flushDeploymentLogs().catch((err) => log.error("deployment logs failed", err)), LOG_FLUSH_INTERVAL_MS));
void scanFolders();
void tick();
setTimeout(() => void checkHubDue(), 15_000);
+25
View File
@@ -0,0 +1,25 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { errorCauses } from "./log-causes";
describe("errorCauses", () => {
it("finds vLLM's root cause and skips the wrapper error", () => {
const lines = [
"(Worker pid=171) INFO 10-06 09:49:26 [model_runner.py:16] Warming up done.",
"(Worker pid=171) ERROR 10-06 09:50:06 [multiproc_executor.py:1058] Traceback (most recent call last):",
"(Worker pid=171) ERROR 10-06 09:50:06 [multiproc_executor.py:1058] ValueError: Available memory on node 0 (3.33/8.0 GiB) is too low.",
"(Worker pid=171) ERROR 10-06 09:50:06 [multiproc_executor.py:1058] ValueError: Available memory on node 0 (3.33/8.0 GiB) is too low.",
"RuntimeError: Engine core initialization failed. See root cause above. Failed core proc(s): {}",
];
assert.deepEqual(errorCauses(lines), ["ValueError: Available memory on node 0 (3.33/8.0 GiB) is too low."]);
});
it("finds llama.cpp load errors", () => {
const lines = ["0.00.012 I srv load_model: loading model '/models/x.gguf'", "0.00.013 E llama_model_load: error: unknown model architecture: 'foo'", "0.00.014 E srv load_model: failed to load model, '/models/x.gguf'"];
assert.equal(errorCauses(lines).length, 2);
});
it("returns nothing for a clean log", () => {
assert.deepEqual(errorCauses(["listening on http://0.0.0.0:8080"]), []);
});
});
+20
View File
@@ -0,0 +1,20 @@
// Picks the likely cause of a failed start out of a container log. Pure, for tests.
// "(Worker pid=171) ERROR 10-06 09:50:06 [multiproc_executor.py:1058] " and similar vLLM prefixes.
const VLLM_PREFIX = /^\([\w ]+pid=\d+\)\s+(?:[A-Z]+\s+\d\d-\d\d \d\d:\d\d:\d\d\s+\[[^\]]*\]\s*)?/;
// A Python exception line ("ValueError: …"), llama.cpp's "error:"/"failed to" lines.
const CAUSE = /^(?:[\w.]*(?:Error|Exception): \S|.*\berror: \S|.*\bfailed to (?:load|open|allocate)\b)/i;
// Generic wrappers that only say "see above".
const WRAPPER = /Engine core initialization failed|See root cause above|exiting due to/i;
/** Distinct cause lines in order of first appearance (at most `max`). */
export function errorCauses(lines: string[], max = 3): string[] {
const out: string[] = [];
for (const raw of lines) {
const line = raw.replace(VLLM_PREFIX, "").trim();
if (!CAUSE.test(line) || WRAPPER.test(line) || out.includes(line)) continue;
out.push(line.length > 500 ? `${line.slice(0, 500)}…` : line);
if (out.length >= max) break;
}
return out;
}
+210
View File
@@ -0,0 +1,210 @@
// Worker side of runtimes: Docker host facts, image state per runtime, pulling images.
// The web app never talks to Docker; it reads what the worker reports in the DB.
import { readFile } from "node:fs/promises";
import { hostname } from "node:os";
import { resolve } from "node:path";
import { and, eq, isNotNull, ne } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { type DockerHostInfo, runtimes, settings, workerState } from "@/lib/db/schema";
import { coreEnv } from "@/lib/env";
import { RUNTIME_PRESETS } from "@/lib/runtimes-shared";
import { DockerClient, DockerError } from "./docker/client";
import { log } from "./log";
const PROGRESS_MS = 1_000;
/** CPU flags that matter for inference engines. */
const CPU_FEATURES = ["avx2", "avx512f", "avx512_bf16", "avx512_vnni", "avx512bw", "amx_bf16", "amx_int8", "f16c", "fma"];
let client: DockerClient | null | undefined;
export function docker(): DockerClient | null {
if (client === undefined) {
const host = coreEnv().DOCKER_HOST;
client = host ? new DockerClient(host) : null;
}
return client;
}
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
/** CPU model and features from /proc/cpuinfo (the host's, also inside a container). */
async function cpuFacts(): Promise<{ model: string | null; features: string[] }> {
try {
const text = await readFile("/proc/cpuinfo", "utf8");
const model = text.match(/^model name\s*:\s*(.+)$/m)?.[1]?.trim() ?? null;
const flags = new Set(text.match(/^flags\s*:\s*(.+)$/m)?.[1]?.split(/\s+/) ?? []);
return { model, features: CPU_FEATURES.filter((f) => flags.has(f)) };
} catch {
return { model: null, features: [] }; // not Linux (dev on Windows/macOS)
}
}
/** Find our own container to learn the network and where MODELS_DIR comes from on the host. */
async function selfDetect(c: DockerClient): Promise<Pick<DockerHostInfo, "network" | "modelsSource">> {
const env = coreEnv();
let network: string | null = env.KANAME_DOCKER_NETWORK ?? null;
let modelsSource: DockerHostInfo["modelsSource"] = env.KANAME_MODELS_SOURCE
? { type: env.KANAME_MODELS_SOURCE.startsWith("/") ? "bind" : "volume", source: env.KANAME_MODELS_SOURCE }
: null;
if (network && modelsSource) return { network, modelsSource };
const self = await c.inspectContainer(hostname()).catch(() => null);
if (self) {
network ??= Object.keys(self.NetworkSettings.Networks).find((n) => !["bridge", "host", "none"].includes(n)) ?? null;
const mount = self.Mounts.find((m) => resolve(m.Destination) === resolve(env.MODELS_DIR));
if (!modelsSource && mount) {
modelsSource = mount.Type === "volume" ? { type: "volume", source: mount.Name ?? mount.Source } : { type: "bind", source: mount.Source };
}
}
return { network, modelsSource };
}
/** Report Docker connectivity and host facts in worker_state (null when DOCKER_HOST isn't set). */
export async function refreshDockerInfo(instanceId: string): Promise<void> {
const c = docker();
let info: DockerHostInfo | null = null;
if (c) {
const cpu = await cpuFacts();
const base = {
cpuModel: cpu.model,
cpuFeatures: cpu.features,
checkedAt: new Date().toISOString(),
};
try {
const [v, i] = await Promise.all([c.version(), c.info()]);
info = {
connected: true,
error: null,
serverVersion: v.Version,
os: i.OperatingSystem,
architecture: i.Architecture,
cpus: i.NCPU,
memoryBytes: i.MemTotal,
...base,
...(await selfDetect(c)),
};
} catch (err) {
info = {
connected: false,
error: message(err),
serverVersion: null,
os: null,
architecture: null,
cpus: null,
memoryBytes: null,
network: null,
modelsSource: null,
...base,
};
}
}
await db().update(workerState).set({ docker: info }).where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId)));
}
const SEEDED_KEY = "runtimes.presetsSeeded";
/** Create the preset runtimes once (deleted presets don't come back). */
export async function seedRuntimePresets(): Promise<void> {
const d = db();
const seeded = await d.query.settings.findFirst({ where: eq(settings.key, SEEDED_KEY) });
if (seeded) return;
const existing = await d.select({ id: runtimes.id }).from(runtimes).limit(1);
if (existing.length === 0) {
await d.insert(runtimes).values(
RUNTIME_PRESETS.map((p) => ({
name: p.name,
engine: p.engine,
image: p.image,
description: p.description ?? null,
env: p.env ?? {},
extraArgs: p.extraArgs ?? [],
devices: p.devices ?? [],
shmSizeMb: p.shmSizeMb ?? null,
numaTuning: p.numaTuning ?? false,
preset: p.id,
})),
);
log.info(`created ${RUNTIME_PRESETS.length} preset runtime(s)`);
}
await d.insert(settings).values({ key: SEEDED_KEY, value: true }).onConflictDoNothing();
}
/** Look up every runtime's image locally (present / missing), except ones being pulled. */
export async function syncImageStates(): Promise<void> {
const c = docker();
if (!c) return;
const rows = await db().select().from(runtimes).where(ne(runtimes.imageState, "pulling"));
for (const r of rows) {
try {
const img = await c.inspectImage(r.image);
await db()
.update(runtimes)
.set(
img
? { imageState: "present", imageId: img.Id, imageSize: img.Size, imageCreated: img.Created, imageCheckedAt: new Date() }
: { imageState: r.imageState === "failed" ? "failed" : "missing", imageId: null, imageSize: null, imageCreated: null, imageCheckedAt: new Date() },
)
.where(eq(runtimes.id, r.id));
} catch (err) {
log.warn(`image check for ${r.image} failed: ${message(err)}`);
}
}
}
/** Pulls interrupted by a worker restart can't still be running. */
export async function resetStalePulls(): Promise<void> {
await db().update(runtimes).set({ imageState: "unknown", pullProgress: null }).where(eq(runtimes.imageState, "pulling"));
}
let pulling = false;
/** Pull images whose "Pull" was requested after the last pull started. One at a time. */
export async function handlePullRequests(): Promise<void> {
const c = docker();
if (!c || pulling) return;
const rows = await db().select().from(runtimes).where(isNotNull(runtimes.pullRequestedAt));
const next = rows.find((r) => r.imageState !== "pulling" && (!r.pullStartedAt || r.pullRequestedAt! > r.pullStartedAt));
if (!next) return;
pulling = true;
const d = db();
await d
.update(runtimes)
.set({ imageState: "pulling", pullStartedAt: new Date(), pullError: null, pullProgress: { doneBytes: 0, totalBytes: 0, status: "Starting" } })
.where(eq(runtimes.id, next.id));
log.info(`pulling ${next.image}`);
let lastWrite = 0;
try {
await c.pullImage(next.image, (p) => {
if (Date.now() - lastWrite < PROGRESS_MS) return;
lastWrite = Date.now();
// Drizzle queries only run when awaited/then'd; `void query` would never execute.
d.update(runtimes)
.set({ pullProgress: p })
.where(eq(runtimes.id, next.id))
.then(
() => {},
(err) => log.warn(`pull progress update failed: ${message(err)}`),
);
});
const img = await c.inspectImage(next.image);
await d
.update(runtimes)
.set({
imageState: img ? "present" : "failed",
imageId: img?.Id ?? null,
imageSize: img?.Size ?? null,
imageCreated: img?.Created ?? null,
pullProgress: null,
pullError: img ? null : "Pull finished but the image isn't there.",
imageCheckedAt: new Date(),
})
.where(eq(runtimes.id, next.id));
log.info(`pulled ${next.image}`);
} catch (err) {
const msg = err instanceof DockerError ? err.message : message(err);
await d.update(runtimes).set({ imageState: "failed", pullProgress: null, pullError: msg }).where(eq(runtimes.id, next.id));
log.warn(`pulling ${next.image} failed: ${msg}`);
} finally {
pulling = false;
}
}