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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:11:06 +02:00

294 lines
16 KiB
TypeScript

import "server-only";
import { and, eq, inArray, isNotNull, isNull, ne, or, sql } from "drizzle-orm";
import { z } from "zod";
import { checkArgs, checkHostPort, checkLimits, checkStart, checkVram, type GpuLoad, TuningError, type TuningGuardrails } from "@/lib/agent-tuning";
import type { TokenIdentity } from "@/lib/api-tokens";
import { effectiveHardware } from "@/lib/benchmark-snapshot";
import { db } from "@/lib/db/client";
import { benchmarkRuns, benchmarkSweeps, type DeploymentOptions, deployments, models, type RuntimeAccelerator, runtimes } from "@/lib/db/schema";
import { API_KEY_PLACEHOLDER, buildCommand, ENGINE_PORT, estimateMemoryMb, estimateVramMb, renderCommand } from "@/lib/deploy-command";
import {
createDeployment,
DeploymentBody,
DeploymentError,
type DeploymentInput,
type DeploymentRow,
deploymentFileBytes,
getDeployment,
requestDelete,
setDesiredState,
updateDeployment,
validateDeployment,
} from "@/lib/deployments";
import { getDockerInfo } from "@/lib/runtimes";
import { getTuning } from "@/lib/settings";
// Deployments through the API: the same validation, estimates and command as the UI, plus the agent
// guardrails (runtime allowlist, argument allowlist, ports, caps, one GPU job at a time, protected
// deployments, approval). Agents only change deployments their own token created.
const RUN_OPEN = ["pending_approval", "queued", "running"] as const;
/** Stored (already validated) options as request input; they're validated again on the way in. */
const asInput = (o: DeploymentOptions) => o as DeploymentInput["options"];
export const AgentDeploymentBody = z
.object({
name: z.string().trim().min(1).max(80).optional(),
runtimeId: z.string().min(1),
modelId: z.string().min(1),
options: DeploymentBody.shape.options.strict(),
cpus: z.number().min(0.1).max(1024).nullable().optional(),
memoryMb: z.number().int().min(256).max(4_194_304).nullable().optional(),
hostPort: z.number().int().min(1024).max(65_535).nullable().optional(),
/** Start right away (default); with approval mode "approve" the start waits for the user. */
start: z.boolean().default(true),
/** Only validate and return the command and estimates; nothing is created. */
dryRun: z.boolean().default(false),
})
.strict();
export type AgentDeploymentInput = z.infer<typeof AgentDeploymentBody>;
export const AgentDeploymentPatch = z
.object({
name: z.string().trim().min(1).max(80).optional(),
options: DeploymentBody.shape.options.partial().strict().optional(),
cpus: z.number().min(0.1).max(1024).nullable().optional(),
memoryMb: z.number().int().min(256).max(4_194_304).nullable().optional(),
hostPort: z.number().int().min(1024).max(65_535).nullable().optional(),
})
.strict();
/** Agent deployments, runs and sweeps that keep the GPU busy right now (all tokens). */
export async function gpuLoad(selfId?: string): Promise<GpuLoad> {
const notSelf = selfId ? ne(deployments.id, selfId) : undefined;
const agentDep = and(isNotNull(deployments.requestedByTokenId), isNull(deployments.deleteRequestedAt), notSelf);
const [[dep], [starting], [runs], [sweeps]] = await Promise.all([
db()
.select({ n: sql<number>`count(*)` })
.from(deployments)
.where(and(agentDep, or(eq(deployments.desiredState, "running"), isNotNull(deployments.startRequestedAt), inArray(deployments.state, ["starting", "running"])))),
db()
.select({ n: sql<number>`count(*)` })
.from(deployments)
.where(and(agentDep, eq(deployments.state, "starting"))),
db()
.select({ n: sql<number>`count(*)` })
.from(benchmarkRuns)
.where(and(isNotNull(benchmarkRuns.requestedByTokenId), inArray(benchmarkRuns.state, [...RUN_OPEN]))),
db()
.select({ n: sql<number>`count(*)` })
.from(benchmarkSweeps)
.where(and(isNotNull(benchmarkSweeps.requestedByTokenId), inArray(benchmarkSweeps.state, [...RUN_OPEN]))),
]);
return { agentDeployments: Number(dep.n), agentStarting: Number(starting.n), agentRuns: Number(runs.n) + Number(sweeps.n) };
}
type Pool = { accelerator: RuntimeAccelerator; gpus: string[] | null };
const sharesGpus = (a: Pool, b: Pool) =>
a.accelerator !== "cpu" &&
b.accelerator !== "cpu" &&
(a.accelerator === "nvidia") === (b.accelerator === "nvidia") &&
(a.accelerator !== "nvidia" || !a.gpus?.length || !b.gpus?.length || a.gpus.some((g) => b.gpus!.includes(g)));
/** VRAM of the GPUs a deployment gets (NVIDIA: the picked ones or all; /dev/dri: Intel and AMD). */
async function poolVramMb(pool: Pool): Promise<number | null> {
const { hardware, nvidia } = await effectiveHardware();
if (pool.accelerator === "nvidia") {
const gs = pool.gpus?.length ? nvidia.filter((g) => pool.gpus!.includes(g.uuid)) : nvidia;
return gs.length ? gs.reduce((s, g) => s + g.memoryMb, 0) : null;
}
const gs = (hardware?.gpus ?? []).filter((g) => (pool.accelerator === "rocm" ? g.vendor === "amd" : g.vendor !== "nvidia"));
return gs.length && gs.every((g) => g.vramMb) ? gs.reduce((s, g) => s + (g.vramMb ?? 0), 0) : null;
}
/** Estimated VRAM (null: can't tell) of a deployment's options. */
async function vramOf(modelId: string, engine: "llama.cpp" | "vllm", options: DeploymentOptions, totalMb: number | null) {
return estimateVramMb(await deploymentFileBytes(modelId, options, engine), options.contextSize, engine, options, totalMb);
}
/** Refuse a start that would crowd a running protected deployment on the same GPUs out of VRAM. */
async function checkProtectedVram(self: { id?: string; modelId: string; engine: "llama.cpp" | "vllm"; accelerator: RuntimeAccelerator; options: DeploymentOptions }) {
if (self.accelerator === "cpu") return;
const pool: Pool = { accelerator: self.accelerator, gpus: self.options.gpus ?? null };
const running = (
await db()
.select({ id: deployments.id, name: deployments.name, protected: deployments.protected, modelId: deployments.modelId, options: deployments.options, engine: runtimes.engine, accelerator: runtimes.accelerator })
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.where(and(isNull(deployments.deleteRequestedAt), inArray(deployments.state, ["starting", "running"]), self.id ? ne(deployments.id, self.id) : undefined))
).filter((d) => sharesGpus(pool, { accelerator: d.accelerator, gpus: d.options.gpus ?? null }));
const protectedNames = running.filter((d) => d.protected).map((d) => d.name);
if (protectedNames.length === 0) return;
const totalMb = await poolVramMb(pool);
checkVram({
protectedNames,
newMb: await vramOf(self.modelId, self.engine, self.options, totalMb),
runningMb: await Promise.all(running.map(async (d) => (await vramOf(d.modelId, d.engine, d.options, totalMb)) ?? -1)),
totalMb,
});
}
async function runtimeFor(g: TuningGuardrails, runtimeId: string) {
const rt = await db().query.runtimes.findFirst({ where: eq(runtimes.id, runtimeId) });
if (!rt) throw new DeploymentError("not_found", "Runtime not found. List them with GET /api/v1/runtimes.", 404);
if (g.allowedRuntimeIds.length && !g.allowedRuntimeIds.includes(rt.id)) {
throw new TuningError("runtime_not_allowed", `runtime "${rt.name}" isn't on the agents' allowlist. Pick one from GET /api/v1/runtimes with "allowed": true.`, 403);
}
if (rt.imageState !== "present") throw new TuningError("runtime_not_pulled", `runtime "${rt.name}" has no pulled image; ask the user to pull it in Settings → Runtimes.`, 409);
return rt;
}
/** The checked deployment: validated options, memory limit, estimates and the command it would run. */
async function prepare(g: TuningGuardrails, input: { name: string; runtimeId: string; modelId: string; options: z.infer<typeof DeploymentBody>["options"]; cpus?: number | null; memoryMb?: number | null; hostPort?: number | null }, selfId?: string) {
const rt = await runtimeFor(g, input.runtimeId);
checkArgs(g, rt.engine, input.options.extraArgs);
checkHostPort(g, input.hostPort);
const options = await validateDeployment({ ...input, cpus: input.cpus ?? null, memoryMb: input.memoryMb ?? null, hostPort: input.hostPort ?? null }, selfId);
const model = await db().query.models.findFirst({ columns: { repoId: true, localPath: true }, where: eq(models.id, input.modelId) });
const fileBytes = await deploymentFileBytes(input.modelId, options, rt.engine);
const docker = await getDockerInfo();
const estimateMb = estimateMemoryMb(fileBytes, options.contextSize, rt.engine, { ...options, accelerator: rt.accelerator });
const { memoryMb, cpus } = checkLimits(g, { memoryMb: input.memoryMb, cpus: input.cpus, estimateMb, hostMemoryMb: docker?.memoryBytes ? docker.memoryBytes / 2 ** 20 : null, hostCpus: docker?.cpus ?? null });
const totalVram = rt.accelerator === "cpu" ? null : await poolVramMb({ accelerator: rt.accelerator, gpus: options.gpus ?? null });
const vramMb = rt.accelerator === "cpu" ? null : estimateVramMb(fileBytes, options.contextSize, rt.engine, options, totalVram);
const cmd = buildCommand({
engine: rt.engine,
options,
model: { repoId: model?.repoId ?? "", localPath: model?.localPath ?? "" },
runtime: rt,
apiKeys: options.requireApiKey ? [API_KEY_PLACEHOLDER] : [],
});
return {
rt,
options,
memoryMb,
cpus,
preview: {
command: renderCommand(rt.image, cmd),
estimates: { memoryMb: estimateMb, vramMb, gpuVramMb: totalVram },
limits: { memoryMb, cpus },
},
};
}
/** Create (and by default start) a deployment for a token. */
export async function createAgentDeployment(token: TokenIdentity, body: AgentDeploymentInput, g?: TuningGuardrails) {
const guard = g ?? (await getTuning());
const name = body.name ?? `${token.name} ${new Date().toISOString().slice(0, 16).replace("T", " ")}`;
const p = await prepare(guard, { ...body, name });
if (body.start) {
checkStart(guard, await gpuLoad());
await checkProtectedVram({ modelId: body.modelId, engine: p.rt.engine, accelerator: p.rt.accelerator, options: p.options });
}
if (body.dryRun) return { dryRun: true as const, created: false, id: null, state: "dry_run", ...p.preview };
const pending = body.start && guard.approvalMode === "approve";
const { id } = await createDeployment(
{ name, runtimeId: body.runtimeId, modelId: body.modelId, options: asInput(p.options), cpus: p.cpus, memoryMb: p.memoryMb, hostPort: body.hostPort ?? null },
body.start,
{ requestedBy: { tokenId: token.id, name: token.name }, startPendingApproval: pending },
);
return { dryRun: false as const, created: true, id, state: pending ? "pending_approval" : body.start ? "starting" : "stopped", ...p.preview };
}
/** A deployment this token may change: its own, and not protected. */
async function ownDeployment(token: TokenIdentity, id: string): Promise<DeploymentRow> {
const d = await getDeployment(id);
if (!d) throw new DeploymentError("not_found", "No deployment with this id.", 404);
if (d.protected) throw new TuningError("protected", `"${d.name}" is protected; agents can't change, stop, delete or benchmark it.`, 403);
if (d.requestedByTokenId !== token.id) throw new TuningError("not_owner", `"${d.name}" wasn't created by this token; agents only change their own deployments.`, 403);
return d;
}
/** Change an own, stopped deployment's launch options (fields left out stay). */
export async function updateAgentDeployment(token: TokenIdentity, id: string, patch: z.infer<typeof AgentDeploymentPatch>) {
const guard = await getTuning();
const d = await ownDeployment(token, id);
if (d.state !== "stopped" && d.state !== "failed") throw new DeploymentError("busy", "Stop the deployment first (POST …/stop), then change it.", 409);
const input = {
name: patch.name ?? d.name,
runtimeId: d.runtimeId,
modelId: d.modelId,
options: asInput({ ...d.options, ...patch.options }),
cpus: patch.cpus !== undefined ? patch.cpus : d.cpus,
memoryMb: patch.memoryMb !== undefined ? patch.memoryMb : d.memoryMb,
hostPort: patch.hostPort !== undefined ? patch.hostPort : d.hostPort,
};
// The memory limit follows the options unless the agent sets one: re-estimate when it was implicit.
const p = await prepare(guard, { ...input, memoryMb: patch.memoryMb !== undefined ? patch.memoryMb : patch.options ? null : d.memoryMb }, id);
await updateDeployment(id, { ...input, options: asInput(p.options), memoryMb: p.memoryMb, cpus: p.cpus });
return p.preview;
}
/** Start an own deployment (waits for approval in mode "approve"). */
export async function startAgentDeployment(token: TokenIdentity, id: string): Promise<{ state: string }> {
const guard = await getTuning();
const d = await ownDeployment(token, id);
if (d.desiredState === "running") return { state: d.state };
if (d.startRequestedAt) return { state: "pending_approval" };
await runtimeFor(guard, d.runtimeId);
checkStart(guard, await gpuLoad(id));
await checkProtectedVram({ id, modelId: d.modelId, engine: d.engine, accelerator: d.accelerator, options: d.options });
if (guard.approvalMode === "approve") {
await db().update(deployments).set({ startRequestedAt: new Date() }).where(eq(deployments.id, id));
return { state: "pending_approval" };
}
await setDesiredState(id, "running");
return { state: "starting" };
}
export async function stopAgentDeployment(token: TokenIdentity, id: string): Promise<void> {
await ownDeployment(token, id);
await setDesiredState(id, "stopped");
}
export async function deleteAgentDeployment(token: TokenIdentity, id: string): Promise<void> {
await ownDeployment(token, id);
await requestDelete(id);
}
/** Compact deployment state for agents; the log only on request. */
export function deploymentView(d: DeploymentRow, token: TokenIdentity) {
const port = ENGINE_PORT[d.engine];
const pending = !!d.startRequestedAt;
const state = pending ? "pending_approval" : d.state;
return {
id: d.id,
name: d.name,
state,
desiredState: d.desiredState,
protected: d.protected,
requestedBy: d.requestedBy,
mine: d.requestedByTokenId === token.id,
runtime: { id: d.runtimeId, name: d.runtimeName, engine: d.engine, accelerator: d.accelerator, image: d.runtimeImage },
model: { id: d.modelId, repoId: d.repoId },
options: d.options,
limits: { cpus: d.cpus, memoryMb: d.memoryMb },
hostPort: d.hostPort,
endpoint: d.state === "running" && d.containerName ? `http://${d.containerName}:${port}/v1` : null,
engine: d.engineInfo ? { version: d.engineInfo.version, slots: d.engineInfo.slots, contextSize: d.engineInfo.contextSize } : null,
usage: d.stats ? { cpuPercent: Math.round(d.stats.cpuPercent), memoryBytes: d.stats.memoryBytes, memoryLimitBytes: d.stats.memoryLimitBytes, at: d.stats.at } : null,
error: d.error,
startedAt: d.startedAt?.toISOString() ?? null,
readyAt: d.readyAt?.toISOString() ?? null,
next: deploymentNext(state, d.desiredState),
};
}
function deploymentNext(state: string, desired: string): string {
if (state === "pending_approval") return "The start waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop.";
if (state === "starting" || (desired === "running" && state === "stopped")) return "Starting (loading the model); GET this deployment with ?wait=600 instead of polling.";
if (state === "running") return "Ready: benchmark it with POST /api/v1/benchmarks.";
if (state === "failed") return "Failed to start; see error (and ?log=50). Change the options (PATCH) and start again, or tell the user.";
if (state === "stopping") return "Stopping.";
return "Stopped.";
}
/** Settled for ?wait=: not on the way between states. */
export function deploymentSettled(v: { state: string; desiredState: string }): boolean {
if (v.state === "starting" || v.state === "stopping") return false;
if (v.desiredState === "running" && v.state === "stopped") return false;
if (v.desiredState === "stopped" && v.state === "running") return false;
return true;
}