import "server-only"; import { NextResponse } from "next/server"; import { z } from "zod"; import { GuardrailError } from "@/lib/agent-guardrails"; import { SelectionError } from "@/lib/agent-selection"; import { HubError } from "@/lib/hub/client"; import { JobError } from "@/lib/jobs"; import { ModelError } from "@/lib/models"; import { TagError } from "@/lib/tags"; // Shared by the /api/v1 routes: compact JSON for an agent to read, errors as // { error: { code, message } } with a message that says what to do next. export function v1Json(data: unknown, status = 200) { return NextResponse.json(data, { status, headers: { "Cache-Control": "no-store" } }); } export function v1Error(status: number, code: string, message: string) { return v1Json({ error: { code, message } }, status); } const HUB_STATUS: Partial> = { invalid_repo_id: 400, repo_not_found: 404, revision_not_found: 404, gated_no_token: 403, gated_no_access: 403, rate_limited: 429, network: 502, }; /** Known errors → JSON; anything else is logged and becomes a generic 500 (no stack traces). */ export function v1Catch(err: unknown) { if (err instanceof GuardrailError) return v1Error(err.status, err.code, err.message); if (err instanceof SelectionError) return v1Error(err.status, err.code, err.message); if (err instanceof ModelError || err instanceof JobError || err instanceof TagError) return v1Error(err.status, err.code, err.message); if (err instanceof HubError) return v1Error(HUB_STATUS[err.code] ?? 502, err.code, err.message); if (err instanceof z.ZodError) { return v1Error(400, "invalid_request", err.issues.map((i) => `${i.path.join(".") || "body"}: ${i.message}`).join("; ")); } if (err instanceof SyntaxError) return v1Error(400, "invalid_json", "The request body is not valid JSON."); console.error("[api/v1]", err); return v1Error(500, "internal", "Internal error in Kaname. Tell the user; retrying won't help."); } /** "74.2 GB" next to byte counts, so a reader doesn't have to convert. */ export function size(bytes: number | null | undefined): string | null { return bytes == null ? null : `${(bytes / 1e9).toFixed(1)} GB`; }