Files
Kaname/src/lib/api-v1-agent.test.ts
T
Pascal LinxweilerandClaude Opus 5.5 6b67c653b5
Release / release (push) Successful in 3m17s
Release 0.14.0: quality eval
A deterministic quality eval as a run type next to BetterBench: tool
calling (12 requests), coding (8 Python functions checked by unit tests
in a locked-down sandbox container) and long-context retrieval (needle at
3 depths in 3 lengths up to the context). Versioned eval set in
src/evals/v1, score stored per run, shown on the run page, in compare
views, the benchmark list and sweep tables (optional eval per variant);
API kind "eval", quality in run/sweep/compare answers; skill updated.

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

582 lines
29 KiB
TypeScript

// /api/v1 deployments and benchmarks end to end against a temporary SQLite database (no worker, no
// Docker: deployment states are set directly). Scopes, ownership, protected deployments, every
// guardrail rejection, approval, the activity log and ?wait=.
// Runs with `--conditions=react-server` (see package.json) so "server-only" modules load.
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, beforeEach, describe, it } from "node:test";
import { eq, isNotNull } from "drizzle-orm";
const dir = mkdtempSync(join(tmpdir(), "kaname-agent-"));
process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
process.env.MODELS_DIR = join(dir, "models");
const GiB = 2 ** 30;
type Mods = {
db: typeof import("./db/client");
schema: typeof import("./db/schema");
tokens: typeof import("./api-tokens");
settings: typeof import("./settings");
deployments: typeof import("./deployments");
v1: typeof import("../app/api/v1/route");
runtimes: typeof import("../app/api/v1/runtimes/route");
deps: typeof import("../app/api/v1/deployments/route");
dep: typeof import("../app/api/v1/deployments/[id]/route");
start: typeof import("../app/api/v1/deployments/[id]/start/route");
stop: typeof import("../app/api/v1/deployments/[id]/stop/route");
runs: typeof import("../app/api/v1/benchmarks/route");
run: typeof import("../app/api/v1/benchmarks/[id]/route");
cancel: typeof import("../app/api/v1/benchmarks/[id]/cancel/route");
compare: typeof import("../app/api/v1/benchmarks/compare/route");
sweeps: typeof import("../app/api/v1/sweeps/route");
};
let M: Mods;
let hermes: string; // all scopes
let other: string; // all scopes, another agent
let downloadsOnly: string; // the 0.10 scopes
let modelId: string;
let sycl: string; // llama.cpp on /dev/dri, pulled
let notPulled: string;
let userProtected: string; // the user's own, protected, running on the GPU
type Res = { status: number; body: Record<string, any> }; // eslint-disable-line @typescript-eslint/no-explicit-any
const call = async (handler: (req: Request, ctx: never) => Promise<Response>, path: string, opts: { token?: string; method?: string; body?: unknown; params?: Record<string, string> } = {}): Promise<Res> => {
const req = new Request(`http://kaname.test${path}`, {
method: opts.method ?? (opts.body ? "POST" : "GET"),
headers: { ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}), "Content-Type": "application/json" },
body: opts.body ? JSON.stringify(opts.body) : undefined,
});
const res = await handler(req, { params: Promise.resolve(opts.params ?? {}) } as never);
return { status: res.status, body: (await res.json()) as Res["body"] };
};
const deployBody = (o: Record<string, unknown> = {}) => ({
runtimeId: sycl,
modelId,
options: { modelFile: "Small-Q4_K_M.gguf", contextSize: 8192, extraArgs: [] as string[], ...((o.options as object) ?? {}) },
...Object.fromEntries(Object.entries(o).filter(([k]) => k !== "options")),
});
const create = (o: Record<string, unknown> = {}, token = hermes) => call(M.deps.POST, "/api/v1/deployments", { token, body: deployBody(o) });
const setState = async (id: string, state: "running" | "stopped" | "starting", desired: "running" | "stopped" = state === "stopped" ? "stopped" : "running") => {
await M.db
.db()
.update(M.schema.deployments)
.set({ state, desiredState: desired, startRequestedAt: null, containerName: state === "running" ? `kaname-test-${id.slice(-6)}` : null })
.where(eq(M.schema.deployments.id, id));
};
const tuning = (t: Record<string, unknown>) => M.settings.saveTuning(t);
before(async () => {
const { runMigrations } = await import("./db/migrate");
await runMigrations();
M = {
db: await import("./db/client"),
schema: await import("./db/schema"),
tokens: await import("./api-tokens"),
settings: await import("./settings"),
deployments: await import("./deployments"),
v1: await import("../app/api/v1/route"),
runtimes: await import("../app/api/v1/runtimes/route"),
deps: await import("../app/api/v1/deployments/route"),
dep: await import("../app/api/v1/deployments/[id]/route"),
start: await import("../app/api/v1/deployments/[id]/start/route"),
stop: await import("../app/api/v1/deployments/[id]/stop/route"),
runs: await import("../app/api/v1/benchmarks/route"),
run: await import("../app/api/v1/benchmarks/[id]/route"),
cancel: await import("../app/api/v1/benchmarks/[id]/cancel/route"),
compare: await import("../app/api/v1/benchmarks/compare/route"),
sweeps: await import("../app/api/v1/sweeps/route"),
} as Mods;
const scopes = ["models:read", "downloads:create", "deployments:read", "deployments:write", "benchmarks:read", "benchmarks:run"];
hermes = (await M.tokens.createToken("hermes", scopes)).token;
other = (await M.tokens.createToken("other", scopes)).token;
downloadsOnly = (await M.tokens.createToken("old", ["models:read", "downloads:create"])).token;
const d = M.db.db();
const s = M.schema;
const now = new Date();
await d.insert(s.workerState).values({
id: "worker",
startedAt: now,
heartbeatAt: now,
docker: {
connected: true,
error: null,
serverVersion: "29",
os: "Debian",
architecture: "x86_64",
cpus: 32,
memoryBytes: 64 * GiB,
cpuModel: null,
cpuFeatures: [],
network: "kaname_default",
modelsSource: { type: "bind", source: "/srv/models" },
hardware: {
gpus: [{ vendor: "intel", pciAddress: "0000:03:00.0", name: "Intel Arc Pro B65", vramMb: 32768, driver: "xe", driverVersion: null, linkCurrent: null, linkMax: null, barMb: 32768, rebar: true }],
p2p: null,
cpu: { model: null, cores: 16, threads: 32 },
memoryBytes: 64 * GiB,
kernel: null,
virtualization: { vm: true, hypervisor: "KVM/QEMU" },
storage: null,
checkedAt: now.toISOString(),
},
checkedAt: now.toISOString(),
},
});
const [model] = await d.insert(s.models).values({ repoId: "unsloth/Test-GGUF", pinnedSha: "a".repeat(40), localPath: "unsloth/Test-GGUF", status: "ready" }).returning();
modelId = model.id;
await d.insert(s.modelFiles).values([
{ modelId, path: "Small-Q4_K_M.gguf", size: 4 * GiB, selected: true, state: "present" },
{ modelId, path: "Big-Q8_0.gguf", size: 20 * GiB, selected: true, state: "present" },
]);
const [rt] = await d.insert(s.runtimes).values({ name: "llama.cpp (Intel SYCL)", engine: "llama.cpp", accelerator: "dri", image: "ghcr.io/ggml-org/llama.cpp:server-intel", imageState: "present" }).returning();
sycl = rt.id;
const [missing] = await d.insert(s.runtimes).values({ name: "vLLM (XPU)", engine: "vllm", accelerator: "dri", image: "vllm/vllm-openai-xpu:v0.31.0", imageState: "missing" }).returning();
notPulled = missing.id;
// The user's production deployment: 4 GiB model + KV at 32k ≈ 10 GiB of VRAM.
const [prod] = await d
.insert(s.deployments)
.values({ name: "prod", runtimeId: sycl, modelId, options: { modelFile: "Small-Q4_K_M.gguf", contextSize: 32768, extraArgs: [] }, state: "running", desiredState: "running", protected: true })
.returning();
userProtected = prod.id;
});
after(() => {
(globalThis as { __kanameDb?: { client?: { close(): void } } }).__kanameDb?.client?.close();
try {
rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
} catch {
// Windows may still hold the WAL file for a moment.
}
});
/** Each test starts from: approval "approve", default limits, no agent deployments or runs. */
beforeEach(async () => {
if (!M) return;
const d = M.db.db();
const s = M.schema;
await M.settings.saveTuning({ ...(await import("./agent-tuning")).DEFAULT_TUNING });
await d.delete(s.deployments).where(isNotNull(s.deployments.requestedByTokenId));
await d.delete(s.benchmarkRuns);
await d.delete(s.benchmarkSweeps);
});
describe("scopes", () => {
it("tokens from before 0.13 can't touch deployments or benchmarks", async () => {
assert.equal((await call(M.deps.GET, "/api/v1/deployments", { token: downloadsOnly })).status, 403);
assert.equal((await call(M.runtimes.GET, "/api/v1/runtimes", { token: downloadsOnly })).status, 403);
const r = await call(M.deps.POST, "/api/v1/deployments", { token: downloadsOnly, body: deployBody() });
assert.equal(r.status, 403);
assert.match(r.body.error.message, /deployments:write/);
assert.equal((await call(M.runs.GET, "/api/v1/benchmarks", { token: downloadsOnly })).status, 403);
assert.equal((await call(M.runs.POST, "/api/v1/benchmarks", { token: downloadsOnly, body: { deploymentId: "x" } })).status, 403);
assert.equal((await call(M.sweeps.POST, "/api/v1/sweeps", { token: downloadsOnly, body: {} })).status, 403);
});
it("read scopes don't allow writing", async () => {
const reader = (await M.tokens.createToken("reader", ["deployments:read", "benchmarks:read"])).token;
assert.equal((await call(M.deps.GET, "/api/v1/deployments", { token: reader })).status, 200);
assert.equal((await call(M.deps.POST, "/api/v1/deployments", { token: reader, body: deployBody() })).status, 403);
assert.equal((await call(M.start.POST, "/x", { token: reader, params: { id: userProtected } })).status, 403);
assert.equal((await call(M.runs.POST, "/api/v1/benchmarks", { token: reader, body: { deploymentId: userProtected } })).status, 403);
});
it("lists pulled runtimes with what agents may use", async () => {
const r = await call(M.runtimes.GET, "/api/v1/runtimes", { token: hermes });
assert.equal(r.status, 200);
assert.deepEqual(r.body.runtimes.map((x: { id: string }) => x.id), [sycl]);
assert.ok(r.body.runtimes[0].allowedExtraArgs.includes("--no-mmap"));
assert.equal(r.body.gpus[0].name, "Intel Arc Pro B65");
});
});
describe("creating deployments", () => {
it("dry run: the command and estimates, nothing created", async () => {
const r = await create({ dryRun: true, options: { cacheTypeK: "q8_0", cacheTypeV: "q8_0" } });
assert.equal(r.status, 200);
assert.equal(r.body.dryRun, true);
assert.match(r.body.command, /docker run .*llama\.cpp:server-intel .*-c 8192 .*-ctk q8_0/);
assert.ok(r.body.estimates.vramMb > 4096 && r.body.estimates.vramMb < 32768);
assert.equal(r.body.estimates.gpuVramMb, 32768);
assert.ok(r.body.limits.memoryMb > 0);
assert.equal((await call(M.deps.GET, "/api/v1/deployments?mine=1", { token: hermes })).body.count, 0);
});
it("waits for approval by default and records who asked", async () => {
const r = await create();
assert.equal(r.status, 201);
assert.equal(r.body.state, "pending_approval");
assert.match(r.body.message, /approval/);
const d = await M.deployments.getDeployment(r.body.id);
assert.equal(d?.desiredState, "stopped");
assert.ok(d?.startRequestedAt);
assert.equal(d?.requestedBy, "hermes");
assert.ok(d?.memoryMb, "agent deployments always get a memory limit");
const view = await call(M.dep.GET, "/x", { token: hermes, params: { id: r.body.id } });
assert.equal(view.body.state, "pending_approval");
assert.equal(view.body.mine, true);
// The user approves (Start in the UI): it starts.
await M.deployments.setDesiredState(r.body.id, "running");
assert.equal((await M.deployments.getDeployment(r.body.id))?.desiredState, "running");
});
it("starts right away in automatic mode", async () => {
await tuning({ approvalMode: "auto" });
const r = await create();
assert.equal(r.body.state, "starting");
assert.equal((await M.deployments.getDeployment(r.body.id))?.desiredState, "running");
});
it("can be created stopped", async () => {
const r = await create({ start: false });
assert.equal(r.body.state, "stopped");
});
it("rejects unknown fields instead of ignoring them", async () => {
const r = await create({ options: { gpuLayerz: "all" } });
assert.equal(r.status, 400);
assert.equal(r.body.error.code, "invalid_request");
assert.match(r.body.error.message, /gpuLayerz/);
});
});
describe("deployment guardrails", () => {
it("runtime not pulled / not on the allowlist", async () => {
const r = await create({ runtimeId: notPulled, options: { modelFile: "" } });
assert.equal(r.body.error.code, "runtime_not_pulled");
await tuning({ allowedRuntimeIds: ["something-else"] });
const a = await create();
assert.equal(a.status, 403);
assert.equal(a.body.error.code, "runtime_not_allowed");
});
it("extra arguments outside the allowlist, naming the argument", async () => {
const r = await create({ options: { extraArgs: ["--host", "0.0.0.0"] } });
assert.equal(r.status, 403);
assert.equal(r.body.error.code, "arg_not_allowed");
assert.match(r.body.error.message, /"--host"/);
const p = await create({ options: { extraArgs: ["--chat-template", "/models/../etc/passwd"] } });
assert.equal(p.body.error.code, "arg_not_allowed");
assert.equal((await create({ dryRun: true, options: { extraArgs: ["--no-mmap", "-ctk", "q8_0"] } })).status, 200);
});
it("host ports outside the configured range", async () => {
const r = await create({ hostPort: 18080 });
assert.equal(r.status, 403);
assert.equal(r.body.error.code, "port_not_allowed");
await tuning({ hostPortRange: { from: 18000, to: 18099 } });
assert.equal((await create({ hostPort: 18080, dryRun: true })).status, 200);
assert.equal((await create({ hostPort: 18100, dryRun: true })).body.error.code, "port_not_allowed");
});
it("memory and CPU caps", async () => {
await tuning({ maxMemoryMb: 4096, maxCpus: 4 });
const big = await create({ options: { modelFile: "Big-Q8_0.gguf" } });
assert.equal(big.body.error.code, "limit_exceeded");
assert.match(big.body.error.message, /the estimate/);
assert.equal((await create({ memoryMb: 8192 })).body.error.code, "limit_exceeded");
assert.equal((await create({ cpus: 8 })).body.error.code, "limit_exceeded");
});
it("one agent deployment at a time (pending ones count)", async () => {
assert.equal((await create()).status, 201);
const second = await create();
assert.equal(second.status, 429);
assert.equal(second.body.error.code, "too_many_deployments");
// Creating a stopped one is fine; starting it isn't.
const stopped = await create({ start: false });
assert.equal(stopped.status, 201);
const s = await call(M.start.POST, "/x", { token: hermes, params: { id: stopped.body.id } });
assert.equal(s.body.error.code, "too_many_deployments");
});
it("no start while an agent deployment is still loading or an agent run is open", async () => {
await tuning({ maxAgentDeployments: 3 });
const a = await create();
await setState(a.body.id, "starting");
assert.equal((await create()).body.error.code, "gpu_busy");
await setState(a.body.id, "running");
await M.db.db().insert(M.schema.benchmarkRuns).values({
deploymentId: a.body.id,
modelId,
settings: { quick: true, passes: null, warmup: null, phases: [] },
snapshot: { deploymentName: "x", repoId: "x", runtimeName: "x", engine: "llama.cpp", image: "x", imageId: null, options: { modelFile: "", contextSize: 1, extraArgs: [] }, cpus: null, memoryMb: null, command: "" },
state: "running",
requestedByTokenId: "someone",
requestedBy: "other",
});
const r = await create();
assert.equal(r.body.error.code, "gpu_busy");
assert.match(r.body.error.message, /benchmark or sweep/);
});
it("can't crowd a running protected deployment out of VRAM", async () => {
await tuning({ approvalMode: "auto" });
// prod ≈ 10 GiB; the 20 GB Q8_0 at 8k context needs ~22 GiB more: over 32 GiB.
const big = await create({ options: { modelFile: "Big-Q8_0.gguf" } });
assert.equal(big.status, 409);
assert.equal(big.body.error.code, "vram_protected");
assert.match(big.body.error.message, /prod/);
// Partial offload can't be estimated next to a protected deployment.
assert.equal((await create({ options: { gpuLayers: "20" } })).body.error.code, "vram_protected");
// The small one fits.
assert.equal((await create()).status, 201);
});
});
describe("ownership and protection", () => {
it("agents can't change, start, stop or delete the user's or another token's deployments", async () => {
for (const [handler, method] of [
[M.start.POST, "POST"],
[M.stop.POST, "POST"],
[M.dep.DELETE, "DELETE"],
] as const) {
const r = await call(handler, "/x", { token: hermes, method, params: { id: userProtected } });
assert.equal(r.status, 403);
assert.equal(r.body.error.code, "protected");
}
const theirs = await create({ start: false }, other);
const r = await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 4096 } }, params: { id: theirs.body.id } });
assert.equal(r.body.error.code, "not_owner");
assert.equal((await call(M.stop.POST, "/x", { token: hermes, params: { id: theirs.body.id } })).body.error.code, "not_owner");
});
it("not even their own once the user protects it", async () => {
const mine = await create({ start: false });
await M.deployments.setProtected(mine.body.id, true);
const r = await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 4096 } }, params: { id: mine.body.id } });
assert.equal(r.body.error.code, "protected");
});
it("edits, stops and deletes their own deployments", async () => {
const mine = await create({ start: false });
const p = await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 16384, extraArgs: ["--no-mmap"] } }, params: { id: mine.body.id } });
assert.equal(p.status, 200);
assert.equal(p.body.deployment.options.contextSize, 16384);
assert.match(p.body.command, /-c 16384 .*--no-mmap/);
// Changing a running deployment needs a stop first.
await setState(mine.body.id, "running");
assert.equal((await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 4096 } }, params: { id: mine.body.id } })).body.error.code, "busy");
assert.equal((await call(M.stop.POST, "/x", { token: hermes, params: { id: mine.body.id } })).status, 200);
assert.equal((await M.deployments.getDeployment(mine.body.id))?.desiredState, "stopped");
assert.equal((await call(M.dep.DELETE, "/x", { token: hermes, method: "DELETE", params: { id: mine.body.id } })).status, 200);
assert.equal(await M.deployments.getDeployment(mine.body.id), null);
});
});
describe("benchmark runs and sweeps", () => {
async function runningOwn(token = hermes) {
const d = await create({ start: false }, token);
await setState(d.body.id, "running");
return d.body.id as string;
}
it("only on the token's own, unprotected deployments", async () => {
const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: userProtected } });
assert.equal(r.body.error.code, "protected");
const theirs = await runningOwn(other);
assert.equal((await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: theirs } })).body.error.code, "not_owner");
});
it("waits for approval, with the time limit, and one at a time", async () => {
const id = await runningOwn();
const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: id, quick: true, description: "baseline" } });
assert.equal(r.status, 201);
assert.equal(r.body.state, "pending_approval");
const row = await M.db.db().query.benchmarkRuns.findFirst({ where: eq(M.schema.benchmarkRuns.id, r.body.id) });
assert.equal(row?.timeLimitS, 30 * 60);
assert.equal(row?.requestedBy, "hermes");
const second = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: id } });
assert.equal(second.status, 429);
assert.equal(second.body.error.code, "gpu_busy");
// Cancelling is for the token that started it.
assert.equal((await call(M.cancel.POST, "/x", { token: other, params: { id: r.body.id } })).body.error.code, "not_owner");
assert.equal((await call(M.cancel.POST, "/x", { token: hermes, params: { id: r.body.id } })).status, 200);
const view = await call(M.run.GET, "/x", { token: hermes, params: { id: r.body.id } });
assert.equal(view.body.state, "cancelled");
});
it("a stopped deployment can't be benchmarked", async () => {
const d = await create({ start: false });
const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: d.body.id } });
assert.equal(r.status, 409);
assert.match(r.body.error.message, /running server/);
});
it("sweeps: within the variant limit, with no agent deployment running", async () => {
const base = await create({ start: false });
const many = await call(M.sweeps.POST, "/api/v1/sweeps", {
token: hermes,
body: { baseDeploymentId: base.body.id, params: [{ key: "contextSize", values: ["1024", "2048", "4096"] }, { key: "kvCache", values: ["f16", "q8_0", "q4_0"] }] },
});
assert.equal(many.body.error.code, "too_many_variants");
const running = await runningOwn();
const busy = await call(M.sweeps.POST, "/api/v1/sweeps", { token: hermes, body: { baseDeploymentId: base.body.id, params: [{ key: "kvCache", values: ["f16", "q8_0"] }] } });
assert.equal(busy.body.error.code, "gpu_busy");
await setState(running, "stopped");
const ok = await call(M.sweeps.POST, "/api/v1/sweeps", { token: hermes, body: { baseDeploymentId: base.body.id, params: [{ key: "kvCache", values: ["f16", "q8_0"] }] } });
assert.equal(ok.status, 201);
assert.equal(ok.body.state, "pending_approval");
assert.equal(ok.body.variants, 2);
const row = await M.db.db().query.benchmarkSweeps.findFirst({ where: eq(M.schema.benchmarkSweeps.id, ok.body.id) });
assert.equal(row?.timeLimitS, 180 * 60);
assert.equal(row?.runTimeLimitS, 30 * 60);
});
it("compares runs: headline numbers and what differs", async () => {
const id = await runningOwn();
const ids: string[] = [];
for (const decode of [100, 120]) {
const [r] = await M.db
.db()
.insert(M.schema.benchmarkRuns)
.values({
deploymentId: id,
modelId,
settings: { quick: false, passes: null, warmup: null, phases: [] },
snapshot: { deploymentName: "x", repoId: "x", runtimeName: "x", engine: "llama.cpp", image: "x", imageId: null, options: { modelFile: "", contextSize: 1, extraArgs: [] }, cpus: null, memoryMb: null, command: "" },
state: "completed",
summary: { combined: { decode, ttft_p50: 50, itl_low1: null, update_p50: null, update_p99: null }, single: [], prefill: [], concurrency: [], phases: [], cacheHits: 0, betterbenchVersion: "0.6.1", corpusVersion: "1", passes: 20, quick: false },
meta: {
v: 1,
gpus: [],
p2p: "n/a",
rebar: null,
runtime: { image: "x", tag: null, digest: null, engine: "llama.cpp", engineName: "llama.cpp", engineVersion: "b1" },
model: { repoId: "a/b", file: null, quant: "Q4_K_M", kvCache: decode === 100 ? "f16" : "q8_0" },
contextSize: 8192,
concurrency: 4,
overridden: [],
},
})
.returning();
ids.push(r.id);
}
const c = await call(M.compare.GET, `/api/v1/benchmarks/compare?ids=${ids.join(",")}`, { token: hermes });
assert.equal(c.status, 200);
assert.deepEqual(c.body.runs.map((r: { headline: { decodeTps: number } }) => r.headline.decodeTps), [100, 120]);
assert.deepEqual(Object.keys(c.body.runs[0].differs), ["model"]);
assert.equal(c.body.same.ctx, "8,192");
});
});
describe("?wait=", () => {
it("returns as soon as a starting deployment is running", async () => {
await tuning({ approvalMode: "auto" });
const d = await create();
await setState(d.body.id, "starting");
setTimeout(() => void setState(d.body.id, "running"), 300);
const t0 = Date.now();
const r = await call(M.dep.GET, `/api/v1/deployments/${d.body.id}?wait=10`, { token: hermes, params: { id: d.body.id } });
assert.equal(r.body.state, "running");
assert.equal(r.body.timedOut, false);
assert.ok(Date.now() - t0 < 5000);
});
it("gives up after the wait and says so", async () => {
const d = await create({ start: false });
await setState(d.body.id, "starting");
const r = await call(M.dep.GET, `/api/v1/deployments/${d.body.id}?wait=1`, { token: hermes, params: { id: d.body.id } });
assert.equal(r.body.state, "starting");
assert.equal(r.body.timedOut, true);
assert.equal(r.body.waitedSeconds, 1);
});
it("doesn't wait on something that waits for approval", async () => {
const d = await create();
const t0 = Date.now();
const r = await call(M.dep.GET, `/api/v1/deployments/${d.body.id}?wait=60`, { token: hermes, params: { id: d.body.id } });
assert.equal(r.body.state, "pending_approval");
assert.ok(Date.now() - t0 < 2000);
});
it("waits on a run until it finishes", async () => {
const dep = await create({ start: false });
await setState(dep.body.id, "running");
await tuning({ approvalMode: "auto" });
const run = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: dep.body.id } });
assert.equal(run.body.state, "queued");
setTimeout(
// A drizzle query only runs once it is awaited.
async () => await M.db.db().update(M.schema.benchmarkRuns).set({ state: "completed", finishedAt: new Date() }).where(eq(M.schema.benchmarkRuns.id, run.body.id)),
300,
);
const r = await call(M.run.GET, `/api/v1/benchmarks/${run.body.id}?wait=10`, { token: hermes, params: { id: run.body.id } });
assert.equal(r.body.state, "completed");
});
});
describe("activity log", () => {
it("records requests and refusals with the error code", async () => {
await create();
await create({ options: { extraArgs: ["--host", "x"] } });
const tokenId = (await M.tokens.listTokens()).find((t) => t.name === "hermes")!.id;
const rows = await (await import("./agent-activity")).listActivity(tokenId, 10);
assert.equal(rows[0].outcome, "refused");
assert.equal(rows[0].code, "arg_not_allowed");
assert.equal(rows[1].action, "deployment.create");
assert.equal(rows[1].outcome, "pending_approval");
assert.equal(rows[1].targetType, "deployment");
});
});
describe("the index", () => {
it("shows the deployment guardrails and the new endpoints", async () => {
const r = await call(M.v1.GET, "/api/v1", { token: hermes });
assert.equal(r.body.deploymentGuardrails.maxAgentDeployments, 1);
assert.equal(r.body.deploymentGuardrails.maxRunMinutes, 30);
assert.ok(r.body.endpoints.some((e: string) => e.includes("/api/v1/deployments/{id}[?wait=600]")));
});
});
describe("quality eval through the API", () => {
it("requests an eval run on the token's own deployment and reads its score", async () => {
const d = await create({ start: false });
await setState(d.body.id, "running");
const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { kind: "eval", deploymentId: d.body.id, sections: ["tools", "retrieval"] } });
assert.equal(r.status, 201);
assert.equal(r.body.state, "pending_approval");
const row = await M.db.db().query.benchmarkRuns.findFirst({ where: eq(M.schema.benchmarkRuns.id, r.body.id) });
assert.equal(row?.kind, "eval");
assert.deepEqual(row?.settings.evalSections, ["tools", "retrieval"]);
await M.db
.db()
.update(M.schema.benchmarkRuns)
.set({
state: "completed",
quality: {
evalSet: "kaname-eval-1",
score: 75,
sections: [
{ section: "tools", passed: 9, total: 12, score: 75, seconds: 20 },
{ section: "retrieval", passed: 0, total: 0, score: null, unsupported: "the context length is unknown", seconds: 0 },
],
items: [{ section: "tools", id: "timer-12", pass: false, detail: "no tool call" }],
config: { temperature: 0, seed: 1, thinking: false, contextTokens: null },
},
})
.where(eq(M.schema.benchmarkRuns.id, r.body.id));
const v = await call(M.run.GET, "/x", { token: hermes, params: { id: r.body.id } });
assert.deepEqual(v.body.quality, { evalSet: "kaname-eval-1", score: 75, sections: { tools: "9/12", retrieval: "n/a (the context length is unknown)" } });
const full = await call(M.run.GET, `/api/v1/benchmarks/${r.body.id}?full=1`, { token: hermes, params: { id: r.body.id } });
assert.equal(full.body.failed[0].id, "timer-12");
});
it("refuses unknown sections, and sweeps can add the eval per variant", async () => {
const d = await create({ start: false });
await setState(d.body.id, "running");
const bad = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { kind: "eval", deploymentId: d.body.id, sections: ["vibes"] } });
assert.equal(bad.status, 400);
await setState(d.body.id, "stopped");
const s = await call(M.sweeps.POST, "/api/v1/sweeps", { token: hermes, body: { baseDeploymentId: d.body.id, quality: true, params: [{ key: "kvCache", values: ["f16", "q8_0"] }] } });
assert.equal(s.status, 201);
const row = await M.db.db().query.benchmarkSweeps.findFirst({ where: eq(M.schema.benchmarkSweeps.id, s.body.id) });
assert.equal(row?.settings.quality, true);
});
});