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(), cacheRamMb: int(-1, 1_048_576).nullable().optional(), gpus: z.array(z.string().regex(/^GPU-[0-9a-f-]{36}$/i, "a GPU UUID")).max(64).nullable().optional(), gpuLayers: z .string() .regex(/^(auto|all|\d{1,4})$/, "auto, all or a number") .nullable() .optional(), splitMode: z.enum(["none", "layer", "row", "tensor"]).nullable().optional(), tensorSplit: z .string() .regex(/^\d+(\.\d+)?(,\d+(\.\d+)?)*$/, "proportions like 3,1") .nullable() .optional(), cpuMoe: z.boolean().nullable().optional(), nCpuMoe: int(0, 1000).nullable().optional(), tensorParallel: int(1, 64).nullable().optional(), gpuMemoryUtilization: z.number().min(0.05).max(1).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; /** 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 { 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(); 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); } /** Bytes of the files a deployment loads (llama.cpp: the GGUF, mmproj and draft; vLLM: the repo's files). */ export async function deploymentFileBytes(modelId: string, options: Pick, engine: "llama.cpp" | "vllm"): Promise { const files = await localFiles(modelId); if (engine === "vllm") return modelCandidates(files).vllm?.size ?? files.reduce((s, f) => s + f.size, 0); const want = [options.modelFile, options.mmproj, options.draftFile].filter(Boolean); // A split GGUF is named by its first part; the other parts belong to it. const first = files.find((f) => f.path === options.modelFile); const group = first ? quantGroup(first.path) : null; return files .filter((f) => want.includes(f.path) || (group != null && f.path !== options.modelFile && quantGroup(f.path) === group && f.path.toLowerCase().endsWith(".gguf") && !f.path.toLowerCase().includes("mmproj"))) .reduce((s, f) => s + f.size, 0); } /** Check that runtime, model and files fit together; returns normalized options. */ export async function validateDeployment(input: DeploymentInput, selfId?: string): Promise { 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, tensorParallel: null, gpuMemoryUtilization: null }); } else { Object.assign(options, { modelFile: "", mmproj: null, draftFile: null, draftType: null, batchSize: null, ubatchSize: null, cacheTypeK: null, cacheTypeV: null, flashAttn: null, webui: null, cacheRamMb: null, gpuLayers: null, splitMode: null, tensorSplit: null, cpuMoe: null, nCpuMoe: null, }); } // GPU settings only mean something on a GPU runtime; GPU picking only on NVIDIA. if (runtime.accelerator === "cpu") { Object.assign(options, { gpus: null, gpuLayers: null, splitMode: null, tensorSplit: null, cpuMoe: null, nCpuMoe: null, tensorParallel: null, gpuMemoryUtilization: null }); } else { if (runtime.accelerator !== "nvidia") options.gpus = null; options.kvCacheGb = 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, agent?: { requestedBy: { tokenId: string; name: string }; startPendingApproval: boolean }, ) { const options = await validateDeployment(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 && !agent?.startPendingApproval ? "running" : "stopped", ...(agent ? { requestedByTokenId: agent.requestedBy.tokenId, requestedBy: agent.requestedBy.name, startRequestedAt: startNow && agent.startPendingApproval ? new Date() : null } : {}), }) .returning({ id: deployments.id }); return row; } 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 validateDeployment(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 && !d.startRequestedAt) return; await db() .update(deployments) // Starting or stopping it by hand settles a start an agent asked for. .set({ desiredState: desired, startRequestedAt: null, ...(desired === "running" ? { error: null } : {}) }) .where(eq(deployments.id, id)); } /** Mark a deployment as protected: agents can't touch it or crowd it out of VRAM. */ export async function setProtected(id: string, value: boolean) { await get(id); await db().update(deployments).set({ protected: value }).where(eq(deployments.id, id)); } /** Turn down a start an agent asked for (the deployment stays stopped). */ export async function rejectStart(id: string) { const d = await get(id); if (!d.startRequestedAt) throw new DeploymentError("invalid", "This deployment doesn't wait for a start approval.", 409); await db().update(deployments).set({ startRequestedAt: null }).where(eq(deployments.id, id)); } /** The worker stops the container and deletes the row. */ export async function requestDelete(id: string) { await get(id); 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, accelerator: runtimes.accelerator, sweepId: deployments.sweepId, protected: deployments.protected, requestedBy: deployments.requestedBy, requestedByTokenId: deployments.requestedByTokenId, startRequestedAt: deployments.startRequestedAt, engineInfo: deployments.engineInfo, engine: runtimes.engine, modelId: deployments.modelId, repoId: models.repoId, }; export type DeploymentRow = Awaited>[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> { 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(); 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, }; }