Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat: add support for OpenAI batch processing
Markus Hartung03769eb0ea5a
diff --git a/.gitignore b/.gitignoreindex 783740a7d7..cefb992363 100644--- a/.gitignore+++ b/.gitignore@@ -176,3 +176,6 @@ bin/omniroute.mjs.omc/audit-report.jsonbun.lock++# Private environment variables for .http-client+http-client.private.env.jsondiff --git a/open-sse/services/batchProcessor.ts b/open-sse/services/batchProcessor.tsnew file mode 100644index 0000000000..5d98fd3c8e--- /dev/null+++ b/open-sse/services/batchProcessor.ts@@ -0,0 +1,374 @@+import { v4 as uuidv4 } from "uuid";+import {+ getPendingBatches,+ updateBatch,+ getFileContent,+ createFile,+ getApiKeyById,+ getBatch,+ listBatches,+ listFiles,+ deleteFile,+ updateFileStatus,+} from "@/lib/localDb";+import { handleChat } from "@/sse/handlers/chat";++let isProcessing = false;+let pollInterval: NodeJS.Timeout | null = null;++export function initBatchProcessor() {+ if (pollInterval) return pollInterval;+ console.log("[BATCH] Initializing batch processor polling...");++ // Fail any batches that were in_progress when the server last shut down —+ // we cannot safely resume mid-batch without re-processing from scratch.+ recoverOrphanedBatches();++ pollInterval = setInterval(async () => {+ if (isProcessing) return;+ try {+ isProcessing = true;+ await processPendingBatches();+ } catch (err) {+ console.error("[BATCH] Polling error:", err);+ } finally {+ isProcessing = false;+ }+ }, 10000); // Poll every 10s+ return pollInterval;+}++export function stopBatchProcessor() {+ if (pollInterval) {+ clearInterval(pollInterval);+ pollInterval = null;+ console.log("[BATCH] Stopped batch processor polling.");+ }+}++/**+ * Mark any in_progress batches as failed on startup.+ * These were orphaned by a server crash or restart and cannot be safely resumed.+ */+function recoverOrphanedBatches() {+ try {+ const pending = getPendingBatches();+ for (const batch of pending) {+ if (batch.status === "in_progress") {+ console.warn(`[BATCH] Failing orphaned in_progress batch ${batch.id} (server restarted)`);+ updateBatch(batch.id, {+ status: "failed",+ failedAt: Math.floor(Date.now() / 1000),+ errors: [{ message: "Batch interrupted by server restart and cannot be resumed" }],+ });+ if (batch.inputFileId) {+ updateFileStatus(batch.inputFileId, "processed");+ }+ }+ }+ } catch (err) {+ console.error("[BATCH] Orphan recovery error:", err);+ }+}++export async function processPendingBatches() {+ const pending = getPendingBatches();+ for (const batch of pending) {+ if (batch.status === "validating") {+ await startBatch(batch);+ } else if (batch.status === "cancelling") {+ await cancelBatch(batch);+ }+ // in_progress: currently being processed by processBatchItems running in background;+ // orphaned in_progress batches are handled by recoverOrphanedBatches() at startup.+ }++ // Cleanup task: delete files for batches completed more than completionWindow ago+ await cleanupExpiredBatches();+}++async function cleanupExpiredBatches() {+ try {+ const now = Math.floor(Date.now() / 1000);+ const batches = listBatches(undefined, 200); // Check last 200 batches++ const parseWindow = (window: string): number => {+ if (!window) return 86400;+ const match = new RegExp(/^(\d+)([hdm])$/).exec(window);+ if (!match) return 86400;+ const val = Number.parseInt(match[1]);+ const unit = match[2];+ if (unit === "h") return val * 3600;+ if (unit === "d") return val * 86400;+ if (unit === "m") return val * 60;+ return 86400;+ };++ for (const batch of batches) {+ const windowSeconds = parseWindow(batch.completionWindow);++ // Cleanup completed/failed/cancelled batches after their completion window+ const completionTime =+ batch.completedAt || batch.failedAt || batch.cancelledAt || batch.expiredAt;+ if (completionTime && now - completionTime > windowSeconds) {+ if (batch.inputFileId) deleteFile(batch.inputFileId);+ if (batch.outputFileId) deleteFile(batch.outputFileId);+ if (batch.errorFileId) deleteFile(batch.errorFileId);+ }++ // Expire pending batches that have exceeded their completion window+ if (batch.status === "validating") {+ if (now - batch.createdAt > windowSeconds) {+ updateBatch(batch.id, { status: "expired", expiredAt: now });+ }+ }+ }++ // Cleanup orphan files (batch-purpose files stuck in validating after 48h)+ const allFiles = listFiles();+ for (const file of allFiles) {+ if (+ file.purpose === "batch" &&+ (file.status === "validating" || !file.status) &&+ now - file.createdAt > 172800+ ) {+ deleteFile(file.id);+ }+ }+ } catch (err) {+ console.error("[BATCH] Cleanup error:", err);+ }+}++async function startBatch(batch: any) {+ console.log(`[BATCH] Starting batch ${batch.id}`);++ const content = getFileContent(batch.inputFileId);+ if (!content) {+ failBatch(batch.id, "Input file content not found");+ return;+ }++ try {+ const lines = content.toString().split("\n").filter((l) => l.trim());+ const total = lines.length;++ updateFileStatus(batch.inputFileId, "validating");+ updateBatch(batch.id, {+ status: "in_progress",+ inProgressAt: Math.floor(Date.now() / 1000),+ requestCountsTotal: total,+ });++ // Fire-and-forget: process items in the background so the poll loop isn't blocked.+ // isProcessing prevents a second poll tick from overlapping.+ // noinspection ES6MissingAwait+ processBatchItems(batch, lines);+ } catch (err) {+ console.error(`[BATCH] Error starting batch ${batch.id}:`, err);+ failBatch(batch.id, err instanceof Error ? err.message : String(err));+ }+}++async function processBatchItems(batch: any, lines: string[]) {+ const results: any[] = [];+ const errors: any[] = [];+ let completedCount = 0;+ let failedCount = 0;+ let totalInputTokens = 0;+ let totalOutputTokens = 0;+ let totalReasoningTokens = 0;+ let usedModel = batch.model || null;++ const apiKeyRow = batch.apiKeyId ? await getApiKeyById(batch.apiKeyId) : null;++ for (const line of lines) {+ // Check if cancelled mid-process+ const current = getBatch(batch.id);+ if (!current || current.status === "cancelling" || current.status === "cancelled") {+ break;+ }++ try {+ const item = JSON.parse(line);+ const { custom_id: customId, url, body } = item;++ const headers = new Headers();+ if (apiKeyRow?.key) {+ headers.set("Authorization", `Bearer ${apiKeyRow.key}`);+ }+ headers.set("Content-Type", "application/json");++ // BATCH-SPECIFIC: Force stream: false — batches don't support SSE responses+ const batchItemBody = { ...body, stream: false };++ const response = await handleChat({+ json: async () => batchItemBody,+ url: `http://localhost${url}`,+ headers,+ method: "POST",+ } as any);++ let responseData: { error: any; id?: any; usage?: any; model?: any };+ let statusCode = 200;++ if (response instanceof Response) {+ statusCode = response.status;+ const contentType = response.headers.get("content-type") || "";+ if (contentType.includes("application/json")) {+ responseData = await response.json();+ } else {+ const text = await response.text();+ try {+ responseData = JSON.parse(text);+ } catch {+ responseData = { error: { message: text || "Unknown error", type: "invalid_response" } };+ }+ }+ } else {+ responseData = response;+ }++ const hasError = responseData?.error;+ const requestId = `batch_req_${uuidv4().replaceAll("-", "")}`;++ results.push({+ id: requestId,+ custom_id: customId,+ response: {+ status_code: statusCode,+ request_id: responseData?.id || "req_unknown",+ body: responseData,+ },+ error: null,+ });++ if (hasError || statusCode >= 400) {+ failedCount++;+ } else {+ completedCount++;+ if (responseData?.usage) {+ totalInputTokens += responseData.usage.prompt_tokens || 0;+ totalOutputTokens += responseData.usage.completion_tokens || 0;+ totalReasoningTokens +=+ responseData.usage.completion_tokens_details?.reasoning_tokens || 0;+ }+ if (!usedModel && responseData?.model) {+ usedModel = responseData.model;+ }+ }+ } catch (err) {+ console.error(`[BATCH] Item failed in ${batch.id}:`, err);+ let customId = "unknown";+ try {+ customId = JSON.parse(line).custom_id || "unknown";+ } catch {+ // line was malformed JSON+ }+ errors.push({+ custom_id: customId,+ error: err instanceof Error ? err.message : String(err),+ });+ failedCount++;+ }++ // Periodic progress update+ updateBatch(batch.id, {+ requestCountsCompleted: completedCount,+ requestCountsFailed: failedCount,+ model: usedModel,+ usage: {+ input_tokens: totalInputTokens,+ output_tokens: totalOutputTokens,+ total_tokens: totalInputTokens + totalOutputTokens,+ input_tokens_details: { cached_tokens: 0 },+ output_tokens_details: { reasoning_tokens: totalReasoningTokens },+ },+ });+ }++ // Finalize+ await finalizeBatch(batch.id, results, errors);+}++async function finalizeBatch(batchId: string, results: any[], itemsWithErrors: any[]) {+ const current = getBatch(batchId);+ if (current?.status === "cancelling") {+ updateBatch(batchId, { status: "cancelled", cancelledAt: Math.floor(Date.now() / 1000) });+ return;+ }++ updateBatch(batchId, { status: "finalizing", finalizingAt: Math.floor(Date.now() / 1000) });++ if (current?.inputFileId) {+ updateFileStatus(current.inputFileId, "processed");+ }++ let outputFileId: string | null = null;+ const successes = results.filter(+ (r) => r.response.status_code < 400 && !r.response.body?.error+ );+ if (successes.length > 0) {+ const outputContent = successes.map((r) => JSON.stringify(r)).join("\n");+ const file = createFile({+ bytes: Buffer.byteLength(outputContent),+ filename: `batch_${batchId}_output.jsonl`,+ purpose: "batch_output",+ content: Buffer.from(outputContent),+ apiKeyId: current?.apiKeyId,+ status: "completed",+ });+ outputFileId = file.id;+ }++ let errorFileId: string | null = null;+ const failures = results.filter(+ (r) => r.response.status_code >= 400 || r.response.body?.error+ );+ const allFailures = [+ ...failures,+ ...itemsWithErrors.map((e) => ({+ id: `batch_req_${uuidv4().replaceAll("-", "")}`,+ custom_id: e.custom_id,+ response: null,+ error: { message: e.error, type: "batch_process_error" },+ })),+ ];++ if (allFailures.length > 0) {+ const errorContent = allFailures.map((e) => JSON.stringify(e)).join("\n");+ const file = createFile({+ bytes: Buffer.byteLength(errorContent),+ filename: `batch_${batchId}_error.jsonl`,+ purpose: "batch_output",+ content: Buffer.from(errorContent),+ apiKeyId: current?.apiKeyId,+ status: "completed",+ });+ errorFileId = file.id;+ }++ updateBatch(batchId, {+ status: "completed",+ completedAt: Math.floor(Date.now() / 1000),+ outputFileId,+ errorFileId,+ });+ console.log(`[BATCH] Completed batch ${batchId}`);+}++async function cancelBatch(batch: any) {+ updateBatch(batch.id, {+ status: "cancelled",+ cancelledAt: Math.floor(Date.now() / 1000),+ });+ console.log(`[BATCH] Cancelled batch ${batch.id}`);+}++function failBatch(batchId: string, reason: string) {+ updateBatch(batchId, {+ status: "failed",+ failedAt: Math.floor(Date.now() / 1000),+ errors: [{ message: reason }],+ });+}diff --git a/src/app/api/v1/batches/[id]/cancel/route.ts b/src/app/api/v1/batches/[id]/cancel/route.tsnew file mode 100644index 0000000000..a83e406e1d--- /dev/null+++ b/src/app/api/v1/batches/[id]/cancel/route.ts@@ -0,0 +1,71 @@+import { CORS_HEADERS } from "@/shared/utils/cors";+import { extractApiKey } from "@/sse/services/auth";+import { getBatch, updateBatch, getApiKeyMetadata } from "@/lib/localDb";+import { NextResponse } from "next/server";++function formatBatchResponse(batch: any) {+ return {+ id: batch.id,+ object: "batch",+ endpoint: batch.endpoint,+ errors: batch.errors || null,+ input_file_id: batch.inputFileId,+ completion_window: batch.completionWindow,+ status: batch.status,+ output_file_id: batch.outputFileId || null,+ error_file_id: batch.errorFileId || null,+ created_at: batch.createdAt,+ in_progress_at: batch.inProgressAt || null,+ expires_at: batch.expiresAt || null,+ finalizing_at: batch.finalizingAt || null,+ completed_at: batch.completedAt || null,+ failed_at: batch.failedAt || null,+ expired_at: batch.expiredAt || null,+ cancelling_at: batch.cancellingAt || null,+ cancelled_at: batch.cancelledAt || null,+ request_counts: {+ total: batch.requestCountsTotal || 0,+ completed: batch.requestCountsCompleted || 0,+ failed: batch.requestCountsFailed || 0,+ },+ metadata: batch.metadata || null,+ model: batch.model || null,+ usage: batch.usage || null,+ };+}++export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {+ const apiKey = extractApiKey(request);+ const apiKeyMetadata = await getApiKeyMetadata(apiKey);+ const apiKeyId = apiKeyMetadata?.id || null;++ const { id } = await params;+ const batch = getBatch(id);++ if (!batch || (batch.apiKeyId !== null && batch.apiKeyId !== apiKeyId)) {+ return NextResponse.json(+ { error: { message: "Batch not found", type: "invalid_request_error" } },+ { status: 404, headers: CORS_HEADERS }+ );+ }++ if (["completed", "failed", "cancelled", "expired"].includes(batch.status)) {+ return NextResponse.json(+ { error: { message: `Batch ${id} is already ${batch.status}`, type: "invalid_request_error" } },+ { status: 400, headers: CORS_HEADERS }+ );+ }++ if (batch.status === "cancelling") {+ return NextResponse.json(formatBatchResponse(batch), { headers: CORS_HEADERS });+ }++ updateBatch(id, {+ status: "cancelling",+ cancellingAt: Math.floor(Date.now() / 1000)+ });++ const updatedBatch = getBatch(id);++ return NextResponse.json(formatBatchResponse(updatedBatch), { headers: CORS_HEADERS });+}diff --git a/src/app/api/v1/batches/[id]/route.ts b/src/app/api/v1/batches/[id]/route.tsnew file mode 100644index 0000000000..db1cc119fb--- /dev/null+++ b/src/app/api/v1/batches/[id]/route.ts@@ -0,0 +1,53 @@+import { CORS_HEADERS } from "@/shared/utils/cors";+import { extractApiKey } from "@/sse/services/auth";+import { getBatch, getApiKeyMetadata } from "@/lib/localDb";+import { NextResponse } from "next/server";++function formatBatchResponse(batch: any) {+ return {+ id: batch.id,+ object: "batch",+ endpoint: batch.endpoint,+ errors: batch.errors || null,+ input_file_id: batch.inputFileId,+ completion_window: batch.completionWindow,+ status: batch.status,+ output_file_id: batch.outputFileId || null,+ error_file_id: batch.errorFileId || null,+ created_at: batch.createdAt,+ in_progress_at: batch.inProgressAt || null,+ expires_at: batch.expiresAt || null,+ finalizing_at: batch.finalizingAt || null,+ completed_at: batch.completedAt || null,+ failed_at: batch.failedAt || null,+ expired_at: batch.expiredAt || null,+ cancelling_at: batch.cancellingAt || null,+ cancelled_at: batch.cancelledAt || null,+ request_counts: {+ total: batch.requestCountsTotal || 0,+ completed: batch.requestCountsCompleted || 0,+ failed: batch.requestCountsFailed || 0,+ },+ metadata: batch.metadata || null,+ model: batch.model || null,+ usage: batch.usage || null,+ };+}++export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {+ const apiKey = extractApiKey(request);+ const apiKeyMetadata = await getApiKeyMetadata(apiKey);+ const apiKeyId = apiKeyMetadata?.id || null;++ const { id } = await params;+ const batch = getBatch(id);++ if (!batch || (batch.apiKeyId !== null && batch.apiKeyId !== apiKeyId)) {+ return NextResponse.json(+ { error: { message: "Batch not found", type: "invalid_request_error" } },+ { status: 404, headers: CORS_HEADERS }+ );+ }++ return NextResponse.json(formatBatchResponse(batch), { headers: CORS_HEADERS });+}diff --git a/src/app/api/v1/batches/route.ts b/src/app/api/v1/batches/route.tsnew file mode 100644index 0000000000..14734a7d69--- /dev/null+++ b/src/app/api/v1/batches/route.ts@@ -0,0 +1,100 @@+import { CORS_HEADERS } from "@/shared/utils/cors";+import { extractApiKey } from "@/sse/services/auth";+import { createBatch, getApiKeyMetadata, getFile, listBatches } from "@/lib/localDb";+import { v1BatchCreateSchema } from "@/shared/validation/schemas";+import { NextResponse } from "next/server";++function formatBatchResponse(batch: any) {+ return {+ id: batch.id,+ object: "batch",+ endpoint: batch.endpoint,+ errors: batch.errors || null,+ input_file_id: batch.inputFileId,+ completion_window: batch.completionWindow,+ status: batch.status,+ output_file_id: batch.outputFileId || null,+ error_file_id: batch.errorFileId || null,+ created_at: batch.createdAt,+ in_progress_at: batch.inProgressAt || null,+ expires_at: batch.expiresAt || null,+ finalizing_at: batch.finalizingAt || null,+ completed_at: batch.completedAt || null,+ failed_at: batch.failedAt || null,+ expired_at: batch.expiredAt || null,+ cancelling_at: batch.cancellingAt || null,+ cancelled_at: batch.cancelledAt || null,+ request_counts: {+ total: batch.requestCountsTotal || 0,+ completed: batch.requestCountsCompleted || 0,+ failed: batch.requestCountsFailed || 0,+ },+ metadata: batch.metadata || null,+ model: batch.model || null,+ usage: batch.usage || null,+ };+}++export async function POST(request: Request) {+ const apiKey = extractApiKey(request);+ const apiKeyMetadata = await getApiKeyMetadata(apiKey);+ const apiKeyId = apiKeyMetadata?.id || null;++ try {+ const body = await request.json();+ const validated = v1BatchCreateSchema.parse(body);++ const inputFile = getFile(validated.input_file_id);+ if (!inputFile || (inputFile.apiKeyId !== null && inputFile.apiKeyId !== apiKeyId)) {+ return NextResponse.json(+ { error: { message: "Input file not found", type: "invalid_request_error" } },+ { status: 400, headers: CORS_HEADERS }+ );+ }++ const batch = createBatch({+ endpoint: validated.endpoint as any,+ completionWindow: validated.completion_window,+ inputFileId: validated.input_file_id,+ metadata: validated.metadata,+ apiKeyId,+ outputExpiresAfterSeconds: validated.output_expires_after?.seconds || null,+ outputExpiresAfterAnchor: validated.output_expires_after?.anchor || null,+ });++ return NextResponse.json(formatBatchResponse(batch), { headers: CORS_HEADERS });+ } catch (error) {+ console.error("[BATCHES] Create failed:", error);+ return NextResponse.json(+ { error: { message: error instanceof Error ? error.message : "Create failed", type: "invalid_request_error" } },+ { status: 400, headers: CORS_HEADERS }+ );+ }+}++export async function GET(request: Request) {+ const apiKey = extractApiKey(request);+ const apiKeyMetadata = await getApiKeyMetadata(apiKey);+ const apiKeyId = apiKeyMetadata?.id || null;++ const url = new URL(request.url);+ const limit = Number.parseInt(url.searchParams.get("limit") || "20");+ const after = url.searchParams.get("after") || undefined;++ const batches = listBatches(apiKeyId || undefined, limit + 1, after);+ const hasMore = batches.length > limit;+ const data = hasMore ? batches.slice(0, limit) : batches;++ const formattedData = data.map(b => formatBatchResponse(b));++ return NextResponse.json(+ {+ object: "list",+ data: formattedData,+ first_id: formattedData.length > 0 ? formattedData[0].id : null,+ last_id: formattedData.length > 0 ? formattedData.at(-1).id : null,+ has_more: hasMore,+ },+ { headers: CORS_HEADERS }+ );+}diff --git a/src/app/api/v1/files/[id]/content/route.ts b/src/app/api/v1/files/[id]/content/route.tsnew file mode 100644index 0000000000..b7a150bb75--- /dev/null+++ b/src/app/api/v1/files/[id]/content/route.ts@@ -0,0 +1,35 @@+import { CORS_HEADERS } from "@/shared/utils/cors";+import { extractApiKey } from "@/sse/services/auth";+import { getFile, getFileContent, getApiKeyMetadata } from "@/lib/localDb";+import { NextResponse } from "next/server";++export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {+ const apiKey = extractApiKey(request);+ const apiKeyMetadata = await getApiKeyMetadata(apiKey);+ const apiKeyId = apiKeyMetadata?.id || null;++ const { id } = await params;+ const file = getFile(id);++ if (!file || (file.apiKeyId !== null && file.apiKeyId !== apiKeyId)) {+ return NextResponse.json(+ { error: { message: "File not found", type: "invalid_request_error" } },+ { status: 404, headers: CORS_HEADERS }+ );+ }++ const content = getFileContent(id);+ if (!content) {+ return NextResponse.json(+ { error: { message: "File content not found", type: "invalid_request_error" } },+ { status: 404, headers: CORS_HEADERS }+ );+ }++ return new Response(content, {+ headers: {+ ...CORS_HEADERS,+ "Content-Type": file.mimeType || "application/octet-stream",+ },+ });+}diff --git a/src/app/api/v1/files/[id]/route.ts b/src/app/api/v1/files/[id]/route.tsnew file mode 100644index 0000000000..00baab6617--- /dev/null+++ b/src/app/api/v1/files/[id]/route.ts@@ -0,0 +1,46 @@+import { CORS_HEADERS } from "@/shared/utils/cors";+import { extractApiKey } from "@/sse/services/auth";+import { getFile, deleteFile, getApiKeyMetadata, formatFileResponse } from "@/lib/localDb";+import { NextResponse } from "next/server";++export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {+ const apiKey = extractApiKey(request);+ const apiKeyMetadata = await getApiKeyMetadata(apiKey);+ const apiKeyId = apiKeyMetadata?.id || null;++ const { id } = await params;+ const file = getFile(id);++ if (!file || (file.apiKeyId !== null && file.apiKeyId !== apiKeyId)) {+ return NextResponse.json(+ { error: { message: "File not found", type: "invalid_request_error" } },+ { status: 404, headers: CORS_HEADERS }+ );+ }++ return NextResponse.json(formatFileResponse(file), { headers: CORS_HEADERS });+}++export async function DELETE(request: Request, { params }: { params: Promise<{ id: string }> }) {+ const apiKey = extractApiKey(request);+ const apiKeyMetadata = await getApiKeyMetadata(apiKey);+ const apiKeyId = apiKeyMetadata?.id || null;++ const { id } = await params;+ const file = getFile(id);++ if (!file || (file.apiKeyId !== null && file.apiKeyId !== apiKeyId)) {+ return NextResponse.json(+ { error: { message: "File not found", type: "invalid_request_error" } },+ { status: 404, headers: CORS_HEADERS }+ );+ }++ deleteFile(id);++ return NextResponse.json({+ id,+ object: "file",+ deleted: true+ }, { headers: CORS_HEADERS });+}diff --git a/src/app/api/v1/files/route.ts b/src/app/api/v1/files/route.tsnew file mode 100644index 0000000000..4b5aa73355--- /dev/null+++ b/src/app/api/v1/files/route.ts@@ -0,0 +1,100 @@+import { CORS_HEADERS } from "@/shared/utils/cors";+import { extractApiKey } from "@/sse/services/auth";+import { createFile, listFiles, getApiKeyMetadata, formatFileResponse } from "@/lib/localDb";+import { NextResponse } from "next/server";++export async function POST(request: Request) {+ const apiKey = extractApiKey(request);+ const apiKeyMetadata = await getApiKeyMetadata(apiKey);+ const apiKeyId = apiKeyMetadata?.id || null;++ try {+ const formData = await request.formData();+ const file = formData.get("file") as File;+ const purpose = formData.get("purpose") as string;+ const expiresAfterAnchor = formData.get("expires_after[anchor]") as string;+ const expiresAfterSeconds = formData.get("expires_after[seconds]") as string;++ if (!file || !purpose) {+ return NextResponse.json(+ { error: { message: "Missing file or purpose", type: "invalid_request_error" } },+ { status: 400, headers: CORS_HEADERS }+ );+ }++ const MAX_FILE_BYTES = 512 * 1024 * 1024; // 512 MB+ if (file.size > MAX_FILE_BYTES) {+ return NextResponse.json(+ { error: { message: "File exceeds maximum allowed size of 512 MB", type: "invalid_request_error" } },+ { status: 400, headers: CORS_HEADERS }+ );+ }++ const bytes = file.size;+ const filename = file.name;+ const arrayBuffer = await file.arrayBuffer();+ const content = Buffer.from(arrayBuffer);+ const mimeType = file.type;++ let expiresAt: number | undefined;+ if (expiresAfterAnchor === "created_at" && expiresAfterSeconds) {+ const seconds = Number.parseInt(expiresAfterSeconds);+ if (!Number.isNaN(seconds)) {+ expiresAt = Math.floor(Date.now() / 1000) + seconds;+ }+ }++ const record = createFile({+ bytes,+ filename,+ purpose,+ content,+ mimeType,+ apiKeyId,+ expiresAt,+ });++ return NextResponse.json(formatFileResponse(record), { headers: CORS_HEADERS });+ } catch (error) {+ console.error("[FILES] Upload failed:", error);+ return NextResponse.json(+ { error: { message: "Upload failed", type: "server_error" } },+ { status: 500, headers: CORS_HEADERS }+ );+ }+}++export async function GET(request: Request) {+ const apiKey = extractApiKey(request);+ const apiKeyMetadata = await getApiKeyMetadata(apiKey);+ const apiKeyId = apiKeyMetadata?.id || null;++ const { searchParams } = new URL(request.url);+ const limit = Math.min(Number.parseInt(searchParams.get("limit") || "20") || 20, 10000);+ const after = searchParams.get("after") || undefined;+ const order = (searchParams.get("order") as "asc" | "desc") || "desc";+ const purpose = searchParams.get("purpose") || undefined;++ // We fetch limit + 1 to check if there are more items+ const files = listFiles({+ apiKeyId: apiKeyId || undefined,+ purpose,+ limit: limit + 1,+ after,+ order+ });++ const hasMore = files.length > limit;+ const data = files.slice(0, limit);++ return NextResponse.json(+ {+ object: "list",+ data: data.map((f) => formatFileResponse(f)),+ first_id: data.length > 0 ? data[0].id : null,+ last_id: data.length > 0 ? data.at(-1).id : null,+ has_more: hasMore,+ },+ { headers: CORS_HEADERS }+ );+}diff --git a/src/instrumentation-node.ts b/src/instrumentation-node.tsindex d67092f262..50cbd0e208 100755--- a/src/instrumentation-node.ts+++ b/src/instrumentation-node.ts@@ -13,7 +13,7 @@ function getRandomBytes(byteLength: number): Uint8Array {}function toBase64(bytes: Uint8Array): string {- return btoa(String.fromCharCode(...bytes));+ return btoa(String.fromCodePoint(...bytes));}function toHex(bytes: Uint8Array): string {@@ -130,6 +130,9 @@ export async function registerNodejs(): Promise<void> {console.log(`[STARTUP] Cloud/model sync background bootstrap ${cloudSyncInitialized ? "initialized" : "skipped"}`);+ const { initBatchProcessor } = await import("@omniroute/open-sse/services/batchProcessor");+ initBatchProcessor();+ console.log("[STARTUP] Batch processor started");}try {diff --git a/src/lib/db/apiKeys.ts b/src/lib/db/apiKeys.tsindex 34d7d3c5f1..3012ce7aa6 100644--- a/src/lib/db/apiKeys.ts+++ b/src/lib/db/apiKeys.ts@@ -604,6 +604,25 @@ export async function getApiKeyMetadata(const now = Date.now();+ // persistent env-var key support (persistent passthrough keys) (#1350)+ const envKey = process.env.OMNIROUTE_API_KEY || process.env.ROUTER_API_KEY;+ if (envKey && key === envKey) {+ return {+ id: "env-key",+ name: "Environment Key",+ machineId: "server-env",+ allowedModels: [],+ allowedConnections: [],+ noLog: false,+ autoResolve: true,+ isActive: true,+ accessSchedule: null,+ maxRequestsPerDay: null,+ maxRequestsPerMinute: null,+ maxSessions: 0,+ };+ }+// Check cache firstconst cached = _keyMetadataCache.get(key);if (cached && now - cached.timestamp < CACHE_TTL) {diff --git a/src/lib/db/batches.ts b/src/lib/db/batches.tsnew file mode 100644index 0000000000..6df156b4c5--- /dev/null+++ b/src/lib/db/batches.ts@@ -0,0 +1,142 @@+import { getDbInstance, rowToCamel, objToSnake } from "./core";+import { v4 as uuidv4 } from "uuid";++function parseBatchRow(row: any): BatchRecord {+ const camel = rowToCamel(row) as any;+ if (camel.metadata && typeof camel.metadata === "string") {+ try { camel.metadata = JSON.parse(camel.metadata); } catch { camel.metadata = null; }+ }+ if (camel.errors && typeof camel.errors === "string") {+ try { camel.errors = JSON.parse(camel.errors); } catch { camel.errors = null; }+ }+ if (camel.usage && typeof camel.usage === "string") {+ try { camel.usage = JSON.parse(camel.usage); } catch { camel.usage = null; }+ }+ return camel as BatchRecord;+}++export interface BatchRecord {+ id: string;+ endpoint: string;+ completionWindow: string;+ status: "validating" | "failed" | "in_progress" | "finalizing" | "completed" | "expired" | "cancelling" | "cancelled";+ inputFileId: string;+ outputFileId?: string | null;+ errorFileId?: string | null;+ createdAt: number;+ inProgressAt?: number | null;+ expiresAt?: number | null;+ finalizingAt?: number | null;+ completedAt?: number | null;+ failedAt?: number | null;+ expiredAt?: number | null;+ cancellingAt?: number | null;+ cancelledAt?: number | null;+ requestCountsTotal: number;+ requestCountsCompleted: number;+ requestCountsFailed: number;+ metadata?: Record<string, any> | null;+ apiKeyId?: string | null;+ errors?: any | null;+ model?: string | null;+ usage?: any | null;+ outputExpiresAfterSeconds?: number | null;+ outputExpiresAfterAnchor?: string | null;+}++export function createBatch(batch: Omit<BatchRecord, "id" | "createdAt" | "status" | "requestCountsTotal" | "requestCountsCompleted" | "requestCountsFailed">): BatchRecord {+ const db = getDbInstance();+ const id = "batch_" + uuidv4().replaceAll("-", "").substring(0, 24);+ const createdAt = Math.floor(Date.now() / 1000);+ const record: BatchRecord = {+ ...batch,+ id,+ createdAt,+ status: "validating",+ requestCountsTotal: 0,+ requestCountsCompleted: 0,+ requestCountsFailed: 0,+ errors: batch.errors || null,+ model: batch.model || null,+ usage: batch.usage || null,+ outputExpiresAfterSeconds: batch.outputExpiresAfterSeconds || null,+ outputExpiresAfterAnchor: batch.outputExpiresAfterAnchor || null,+ };++ const snakeRecord = objToSnake({+ ...record,+ metadata: record.metadata ? JSON.stringify(record.metadata) : null,+ errors: record.errors ? JSON.stringify(record.errors) : null,+ usage: record.usage ? JSON.stringify(record.usage) : null+ }) as any;+ const keys = Object.keys(snakeRecord);+ const values = Object.values(snakeRecord);+ const placeholders = keys.map(() => "?").join(", ");++ db.prepare(+ `INSERT INTO batches (${keys.join(", ")}) VALUES (${placeholders})`+ ).run(...values);++ return record;+}++export function getBatch(id: string): BatchRecord | null {+ const db = getDbInstance();+ const row = db.prepare("SELECT * FROM batches WHERE id = ?").get(id);+ if (!row) return null;+ return parseBatchRow(row);+}++export function updateBatch(id: string, updates: Partial<BatchRecord>): boolean {+ const db = getDbInstance();+ const snakeUpdates = objToSnake(updates) as any;+ if (snakeUpdates.metadata && typeof snakeUpdates.metadata !== "string") {+ snakeUpdates.metadata = JSON.stringify(snakeUpdates.metadata);+ }+ if (snakeUpdates.errors && typeof snakeUpdates.errors !== "string") {+ snakeUpdates.errors = JSON.stringify(snakeUpdates.errors);+ }+ if (snakeUpdates.usage && typeof snakeUpdates.usage !== "string") {+ snakeUpdates.usage = JSON.stringify(snakeUpdates.usage);+ }++ const keys = Object.keys(snakeUpdates);+ if (keys.length === 0) return false;++ const setClause = keys.map(k => `${k} = ?`).join(", ");+ const values = Object.values(snakeUpdates);++ const result = db.prepare(`UPDATE batches SET ${setClause} WHERE id = ?`).run(...values, id);+ return result.changes > 0;+}++export function listBatches(apiKeyId?: string, limit: number = 20, after?: string): BatchRecord[] {+ const db = getDbInstance();+ let rows: any[];+ if (apiKeyId) {+ if (after) {+ rows = db+ .prepare("SELECT * FROM batches WHERE api_key_id = ? AND id < ? ORDER BY id DESC LIMIT ?")+ .all(apiKeyId, after, limit);+ } else {+ rows = db+ .prepare("SELECT * FROM batches WHERE api_key_id = ? ORDER BY id DESC LIMIT ?")+ .all(apiKeyId, limit);+ }+ } else if (after) {+ rows = db+ .prepare("SELECT * FROM batches WHERE id < ? ORDER BY id DESC LIMIT ?")+ .all(after, limit);+ } else {+ rows = db.prepare("SELECT * FROM batches ORDER BY id DESC LIMIT ?").all(limit);+ }+ return rows.map(row => parseBatchRow(row));+}++export function getPendingBatches(): BatchRecord[] {+ const db = getDbInstance();+ const rows = db.prepare(+ "SELECT * FROM batches WHERE status IN ('validating', 'in_progress', 'cancelling')"+ ).all();+ return rows.map(row => parseBatchRow(row));+}diff --git a/src/lib/db/files.ts b/src/lib/db/files.tsnew file mode 100644index 0000000000..c6900fa5de--- /dev/null+++ b/src/lib/db/files.ts@@ -0,0 +1,115 @@+import { getDbInstance, rowToCamel, objToSnake } from "./core";+import { v4 as uuidv4 } from "uuid";++export interface FileRecord {+ id: string;+ bytes: number;+ createdAt: number;+ filename: string;+ purpose: string;+ content?: Buffer | null;+ mimeType?: string | null;+ apiKeyId?: string | null;+ status?: string | null;+ expiresAt?: number | null;+ deletedAt?: number | null;+}++export function createFile(file: Omit<FileRecord, "id" | "createdAt">): FileRecord {+ const db = getDbInstance();+ const id = "file-" + uuidv4().replaceAll("-", "").substring(0, 24);+ const createdAt = Math.floor(Date.now() / 1000);+ const record = { ...file, id, createdAt };++ const snakeRecord = objToSnake(record) as any;+ const keys = Object.keys(snakeRecord);+ const values = Object.values(snakeRecord);+ const placeholders = keys.map(() => "?").join(", ");++ db.prepare(+ `INSERT INTO files (${keys.join(", ")}) VALUES (${placeholders})`+ ).run(...values);++ return record;+}++export function getFile(id: string): FileRecord | null {+ const db = getDbInstance();+ const row = db.prepare("SELECT * FROM files WHERE id = ? AND deleted_at IS NULL").get(id);+ return row ? (rowToCamel(row) as unknown as FileRecord) : null;+}++export function getFileContent(id: string): Buffer | null {+ const db = getDbInstance();+ const row = db.prepare("SELECT content FROM files WHERE id = ? AND deleted_at IS NULL").get(id) as { content: Buffer } | undefined;+ return row?.content || null;+}++export function listFiles(options: {+ apiKeyId?: string,+ purpose?: string,+ limit?: number,+ after?: string,+ order?: "asc" | "desc"+} = {}): FileRecord[] {+ const db = getDbInstance();+ const { apiKeyId, purpose, limit = 20, after, order = "desc" } = options;++ let query = "SELECT * FROM files WHERE deleted_at IS NULL";+ const params: any[] = [];++ if (apiKeyId) {+ query += " AND api_key_id = ?";+ params.push(apiKeyId);+ }++ if (purpose) {+ query += " AND purpose = ?";+ params.push(purpose);+ }++ if (after) {+ // Get the creation time of the 'after' file to use for pagination+ const afterFile = getFile(after);+ if (afterFile) {+ if (order === "desc") {+ query += " AND (created_at < ? OR (created_at = ? AND id < ?))";+ } else {+ query += " AND (created_at > ? OR (created_at = ? AND id > ?))";+ }+ params.push(afterFile.createdAt, afterFile.createdAt, after);+ }+ }++ query += ` ORDER BY created_at ${order === "asc" ? "ASC" : "DESC"}, id ${order === "asc" ? "ASC" : "DESC"}`;+ query += " LIMIT ?";+ params.push(limit);++ const rows = db.prepare(query).all(...params);+ return rows.map(row => rowToCamel(row) as unknown as FileRecord);+}++export function updateFileStatus(id: string, status: string): boolean {+ const db = getDbInstance();+ const result = db.prepare("UPDATE files SET status = ? WHERE id = ?").run(status, id);+ return result.changes > 0;+}++export function formatFileResponse(file: FileRecord) {+ return {+ id: file.id,+ bytes: file.bytes,+ created_at: file.createdAt,+ filename: file.filename,+ object: "file",+ purpose: file.purpose,+ status: file.status || "validating",+ expires_at: file.expiresAt || null,+ };+}++export function deleteFile(id: string): boolean {+ const db = getDbInstance();+ const result = db.prepare("UPDATE files SET deleted_at = ?, content = NULL WHERE id = ?").run(Math.floor(Date.now() / 1000), id);+ return result.changes > 0;+}diff --git a/src/lib/db/migrations/027_create_files_and_batches.sql b/src/lib/db/migrations/027_create_files_and_batches.sqlnew file mode 100644index 0000000000..63f286e9d8--- /dev/null+++ b/src/lib/db/migrations/027_create_files_and_batches.sql@@ -0,0 +1,51 @@+-- 027_create_files_and_batches.sql+-- Creates the files and batches tables with their complete final schema.++CREATE TABLE IF NOT EXISTS files (+ id TEXT PRIMARY KEY,+ bytes INTEGER NOT NULL,+ created_at INTEGER NOT NULL,+ filename TEXT NOT NULL,+ purpose TEXT NOT NULL,+ content BLOB,+ mime_type TEXT,+ api_key_id TEXT,+ deleted_at INTEGER,+ status TEXT DEFAULT 'validating',+ expires_at INTEGER+);+CREATE INDEX IF NOT EXISTS idx_files_api_key ON files(api_key_id);++CREATE TABLE IF NOT EXISTS batches (+ id TEXT PRIMARY KEY,+ endpoint TEXT NOT NULL,+ completion_window TEXT NOT NULL,+ status TEXT NOT NULL,+ input_file_id TEXT NOT NULL,+ output_file_id TEXT,+ error_file_id TEXT,+ created_at INTEGER NOT NULL,+ in_progress_at INTEGER,+ expires_at INTEGER,+ finalizing_at INTEGER,+ completed_at INTEGER,+ failed_at INTEGER,+ expired_at INTEGER,+ cancelling_at INTEGER,+ cancelled_at INTEGER,+ request_counts_total INTEGER DEFAULT 0,+ request_counts_completed INTEGER DEFAULT 0,+ request_counts_failed INTEGER DEFAULT 0,+ metadata TEXT,+ api_key_id TEXT,+ errors TEXT,+ model TEXT,+ usage TEXT,+ output_expires_after_seconds INTEGER,+ output_expires_after_anchor TEXT,+ FOREIGN KEY(input_file_id) REFERENCES files(id),+ FOREIGN KEY(output_file_id) REFERENCES files(id),+ FOREIGN KEY(error_file_id) REFERENCES files(id)+);+CREATE INDEX IF NOT EXISTS idx_batches_api_key ON batches(api_key_id);+CREATE INDEX IF NOT EXISTS idx_batches_status ON batches(status);diff --git a/src/lib/localDb.ts b/src/lib/localDb.tsindex eebbc80604..08f809a737 100755--- a/src/lib/localDb.ts+++ b/src/lib/localDb.ts@@ -159,7 +159,7 @@ export {} from "./db/backup";export {- // Read Cache (cached wrappers for hot read paths)+ // Read Cache (cached wrappers for hot-read paths)getCachedSettings,getCachedPricing,getCachedProviderConnections,@@ -202,6 +202,29 @@ export {resolveComboForModel,} from "./db/modelComboMappings";+export {+ // Files+ createFile,+ getFile,+ getFileContent,+ listFiles,+ updateFileStatus,+ formatFileResponse,+ deleteFile,+} from "./db/files";++export {+ // Batches+ createBatch,+ getBatch,+ updateBatch,+ listBatches,+ getPendingBatches,+} from "./db/batches";++export type { FileRecord } from "./db/files";+export type { BatchRecord } from "./db/batches";+export type { ModelComboMapping } from "./db/modelComboMappings";export {diff --git a/src/shared/validation/schemas.ts b/src/shared/validation/schemas.tsindex ae120f3da7..8909229c78 100644--- a/src/shared/validation/schemas.ts+++ b/src/shared/validation/schemas.ts@@ -1744,3 +1744,28 @@ export const versionManagerToolSchema = z.object({export const versionManagerInstallSchema = versionManagerToolSchema.extend({version: z.string().trim().optional(),});++export const v1BatchCreateSchema = z.object({+ input_file_id: z.string().min(1),+ endpoint: z.enum([+ "/v1/responses",+ "/v1/chat/completions",+ "/v1/embeddings",+ "/v1/completions",+ "/v1/moderations",+ "/v1/images/generations",+ "/v1/images/edits",+ "/v1/videos",+ ]),+ completion_window: z.enum(["24h"]),+ metadata: z+ .record(z.string().max(64), z.string().max(512))+ .refine((m) => Object.keys(m).length <= 16, { message: "metadata may have at most 16 keys" })+ .optional(),+ output_expires_after: z+ .object({+ anchor: z.enum(["created_at"]),+ seconds: z.number().int().min(3600).max(2592000),+ })+ .optional(),+});diff --git a/tests/manual/batch.http b/tests/manual/batch.httpnew file mode 100644index 0000000000..131ae14f05--- /dev/null+++ b/tests/manual/batch.http@@ -0,0 +1,101 @@+###+# @name Upload a JSONL file for batch processing+POST {{omniroute-address}}/v1/files+Authorization: Bearer {{OMNIROUTE_API_KEY}}+Content-Type: multipart/form-data; boundary=boundary++--boundary+Content-Disposition: form-data; name="file"; filename="batch_input.jsonl"+Content-Type: application/jsonl++{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello world!"}], "max_tokens": 50}}+{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemini/gemma-4-31b-it", "messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is 2+2?"}], "max_tokens": 50}}++--boundary+Content-Disposition: form-data; name="purpose"++batch+--boundary--++> {%+ client.global.set("file_id", response.body.id);+%}++###+# @name List all uploaded files+GET {{omniroute-address}}/v1/files+Authorization: Bearer {{OMNIROUTE_API_KEY}}++> {%+ client.global.set("file_id", response.body.data[0].id);+%}++###+# @name Get file metadata of the uploaded file+GET {{omniroute-address}}/v1/files/{{file_id}}+Authorization: Bearer {{OMNIROUTE_API_KEY}}++###+# @name Create a new batch job+POST {{omniroute-address}}/v1/batches+Authorization: Bearer {{OMNIROUTE_API_KEY}}+Content-Type: application/json++{+ "input_file_id": "{{file_id}}",+ "endpoint": "/v1/chat/completions",+ "completion_window": "24h"+}++> {%+ client.global.set("batch_id", response.body.id);+%}++###+# @name List all batch jobs+GET {{omniroute-address}}/v1/batches+Authorization: Bearer {{OMNIROUTE_API_KEY}}++###+# @name Get status of batch job+GET {{omniroute-address}}/v1/batches/{{batch_id}}+Authorization: Bearer {{OMNIROUTE_API_KEY}}++> {%+ if (response.body.output_file_id) {+ client.global.set("output_file_id", response.body.output_file_id);+ }+ if (response.body.error_file_id) {+ client.global.set("error_file_id", response.body.error_file_id);+ }+%}++###+# @name Cancel batch job+POST {{omniroute-address}}/v1/batches/{{batch_id}}/cancel+Authorization: Bearer {{OMNIROUTE_API_KEY}}++###+# @name Get outputfile contents+GET {{omniroute-address}}/v1/files/{{output_file_id}}/content+Authorization: Bearer {{OMNIROUTE_API_KEY}}++###+# @name Get outputfile metadata+GET {{omniroute-address}}/v1/files/{{output_file_id}}+Authorization: Bearer {{OMNIROUTE_API_KEY}}++###+# @name Get errorfile contents+GET {{omniroute-address}}/v1/files/{{error_file_id}}/content+Authorization: Bearer {{OMNIROUTE_API_KEY}}++###+# @name Get errorfile metadata+GET {{omniroute-address}}/v1/files/{{error_file_id}}+Authorization: Bearer {{OMNIROUTE_API_KEY}}++###+# @name Delete File+DELETE {{omniroute-address}}/v1/files/{{file_id}}+Authorization: Bearer {{OMNIROUTE_API_KEY}}diff --git a/tests/unit/api-auth.test.ts b/tests/unit/api-auth.test.tsindex 4b1ec7540b..748de02bfb 100644--- a/tests/unit/api-auth.test.ts+++ b/tests/unit/api-auth.test.ts@@ -26,10 +26,10 @@ async function resetStorage() {delete process.env.INITIAL_PASSWORD;}-function makeCookieRequest(token) {+function makeCookieRequest(token: string) {return {cookies: {- get(name) {+ get(name: string) {return name === "auth_token" && token ? { value: token } : undefined;},},@@ -195,4 +195,31 @@ test("isAuthRequired stays enabled when INITIAL_PASSWORD is present", async () =const result = await apiAuth.isAuthRequired();assert.equal(result, true);++ delete process.env.INITIAL_PASSWORD;+});++test("getApiKeyMetadata recognizes OMNIROUTE_API_KEY environment variable", async () => {+ const envKey = "sk-test-env-key-" + Date.now();+ process.env.OMNIROUTE_API_KEY = envKey;++ const metadata = await apiKeysDb.getApiKeyMetadata(envKey);++ assert.ok(metadata);+ assert.equal(metadata.id, "env-key");+ assert.equal(metadata.name, "Environment Key");++ delete process.env.OMNIROUTE_API_KEY;+});++test("getApiKeyMetadata recognizes ROUTER_API_KEY environment variable", async () => {+ const envKey = "sk-test-router-key-" + Date.now();+ process.env.ROUTER_API_KEY = envKey;++ const metadata = await apiKeysDb.getApiKeyMetadata(envKey);++ assert.ok(metadata);+ assert.equal(metadata.id, "env-key");++ delete process.env.ROUTER_API_KEY;});diff --git a/tests/unit/batch_api.test.ts b/tests/unit/batch_api.test.tsnew file mode 100644index 0000000000..7b9920b643--- /dev/null+++ b/tests/unit/batch_api.test.ts@@ -0,0 +1,621 @@+import { test } from "node:test";+import assert from "node:assert";+import { createFile, createBatch, getBatch, getFileContent, updateBatch, createProviderConnection, createApiKey, getFile, listFiles, formatFileResponse, deleteFile } from "../../src/lib/localDb";+import { getDbInstance } from "@/lib/db/core.ts";+import { initBatchProcessor, stopBatchProcessor } from "../../open-sse/services/batchProcessor";++test("Batch API and Processing", async () => {+ // 0. Setup environment, mock provider and API key+ process.env.API_KEY_SECRET = "test-secret-123";++ await createProviderConnection({+ provider: "openai",+ authType: "apikey",+ name: "Mock OpenAI",+ apiKey: "sk-mock-key",+ isActive: true+ });++ const apiKey = await createApiKey("Test Key", "test-machine");++ // 1. Create a file with batch items+ const batchItems = [+ JSON.stringify({+ custom_id: "request-1",+ method: "POST",+ url: "/v1/chat/completions",+ body: { model: "gpt-4o-mini", messages: [{ role: "user", content: "Hello world" }] }+ }),+ JSON.stringify({+ custom_id: "request-2",+ method: "POST",+ url: "/v1/chat/completions",+ body: { model: "gpt-4o-mini", messages: [{ role: "user", content: "Goodbye world" }] }+ })+ ].join("\n");++ const file = createFile({+ bytes: Buffer.byteLength(batchItems),+ filename: "test_batch.jsonl",+ purpose: "batch",+ content: Buffer.from(batchItems),+ apiKeyId: apiKey.id+ });++ assert.ok(file.id.startsWith("file-"), "File ID should start with file-");+ assert.ok(file.status === "validating" || !file.status, "File status should be 'validating' by default or null");++ // 2. Create a batch+ const batch = createBatch({+ endpoint: "/v1/chat/completions",+ completionWindow: "24h",+ inputFileId: file.id,+ apiKeyId: apiKey.id+ });++ assert.ok(batch.id.startsWith("batch_"), "Batch ID should start with batch_");+ assert.strictEqual(batch.status, "validating");++ // 3. Start the processor manually for one tick (or wait if we used initBatchProcessor)+ // For testing, we might want to expose the processing functions or just wait.+ // We'll use a shorter interval in the processor if we want to test polling.+ // Here we'll just call processPendingBatches if it was exported, but it's not.++ // Instead of polling, let's just wait a bit if we started the processor+ initBatchProcessor();++ console.log("Waiting for batch processing...");++ // Poll for status change+ let maxAttempts = 30;+ let currentBatch = getBatch(batch.id);+ while (maxAttempts > 0 && currentBatch?.status !== "completed" && currentBatch?.status !== "failed" && currentBatch?.status !== "cancelled") {+ await new Promise(resolve => setTimeout(resolve, 2000));+ currentBatch = getBatch(batch.id);+ const progress = currentBatch?.requestCountsTotal ? `${currentBatch.requestCountsCompleted}/${currentBatch.requestCountsTotal}` : "not started";+ console.log(`[TEST] Current status: ${currentBatch?.status}, completed: ${progress}, failed: ${currentBatch?.requestCountsFailed || 0}`);+ maxAttempts--;+ }++ // Stop the processor so the test can exit+ stopBatchProcessor();++ if (maxAttempts === 0) {+ console.error("[TEST] Polling timed out. Final batch state:", JSON.stringify(currentBatch, null, 2));+ }++ assert.ok(currentBatch?.status === "completed" || currentBatch?.status === "failed", "Batch should reach a terminal state");++ // In test environment, the mock key might fail, which is fine for this test as long as it finishes+ if (currentBatch?.status === "failed" || currentBatch?.requestCountsFailed > 0) {+ console.warn("[TEST] Batch finished with failures (likely due to mock credentials). This is acceptable for this test.");+ assert.strictEqual(currentBatch?.requestCountsTotal, 2, "Total requests should be 2");+ assert.strictEqual((currentBatch?.requestCountsCompleted || 0) + (currentBatch?.requestCountsFailed || 0), 2, "Total processed should be 2");+ return;+ }++ assert.strictEqual(currentBatch?.status, "completed", "Batch should be completed");+ assert.strictEqual(currentBatch?.requestCountsTotal, 2);+ assert.strictEqual(currentBatch?.requestCountsCompleted, 2);+ assert.ok(currentBatch?.outputFileId, "Should have output file ID");++ // Check file statuses+ const inputFileAfter = getFile(file.id);+ assert.strictEqual(inputFileAfter?.status, "processed", "Input file should be 'processed' after batch completion");++ const outputFile = getFile(currentBatch.outputFileId!);+ assert.strictEqual(outputFile?.status, "completed", "Output file should be 'completed'");++ // 4. Check output file content+ if (currentBatch?.outputFileId) {+ const outputContent = getFileContent(currentBatch.outputFileId);+ assert.ok(outputContent, "Output file content should exist");+ const lines = outputContent.toString().split("\n").filter(l => l.trim());+ assert.strictEqual(lines.length, 2, "Should have 2 result lines");+ const firstResult = JSON.parse(lines[0]);+ assert.ok(firstResult.custom_id, "Result should have custom_id");+ assert.ok(firstResult.response, "Result should have response");+ }++ // 5. Check additional spec-compliant fields+ assert.ok(currentBatch.usage, "Batch should have usage populated");+ assert.strictEqual(typeof currentBatch.usage.total_tokens, "number", "usage.total_tokens should be a number");+ assert.ok(currentBatch.model || currentBatch.requestCountsFailed > 0, "Batch should have model populated if at least one request succeeded");+});++test("Batch handles and counts failures correctly", async () => {+ initBatchProcessor();+ try {+ // 1. Create a file with a request that will fail (invalid provider/model)+ const batchItems = [+ JSON.stringify({+ custom_id: "fail-request",+ method: "POST",+ url: "/v1/chat/completions",+ body: { model: "non-existent-provider/model", messages: [{ role: "user", content: "Fail me" }] }+ })+ ].join("\n");++ const file = createFile({+ bytes: Buffer.byteLength(batchItems),+ filename: "fail_batch.jsonl",+ purpose: "batch",+ content: Buffer.from(batchItems),+ apiKeyId: null+ });++ // 2. Create a batch+ const batch = createBatch({+ endpoint: "/v1/chat/completions",+ completionWindow: "24h",+ inputFileId: file.id,+ apiKeyId: null+ });++ // 3. Poll for completion+ let maxAttempts = 20;+ let currentBatch = getBatch(batch.id);+ while (maxAttempts > 0 && currentBatch?.status !== "completed" && currentBatch?.status !== "failed") {+ await new Promise(resolve => setTimeout(resolve, 1000));+ currentBatch = getBatch(batch.id);+ maxAttempts--;+ }++ // 4. Verify failure counts+ assert.strictEqual(currentBatch?.requestCountsTotal, 1, "Total should be 1");+ assert.strictEqual(currentBatch?.requestCountsCompleted, 0, "Completed should be 0");+ assert.strictEqual(currentBatch?.requestCountsFailed, 1, "Failed should be 1");+ assert.ok(currentBatch?.errorFileId, "Should have error file for failures");+ assert.ok(!currentBatch?.outputFileId, "Should NOT have output file if no successes");++ if (currentBatch?.errorFileId) {+ const errorContent = getFileContent(currentBatch.errorFileId);+ const result = JSON.parse(errorContent.toString());+ assert.ok(result.response.status_code >= 400, `Status code ${result.response.status_code} should be >= 400`);+ assert.ok(result.response.body.error, "Should contain error in body");+ }++ // Check file statuses+ const inputFile = getFile(file.id);+ assert.strictEqual(inputFile?.status, "processed", "Input file should be 'processed'");++ const errorFile = getFile(currentBatch.errorFileId!);+ assert.strictEqual(errorFile?.status, "completed", "Error file should be 'completed'");+ } finally {+ stopBatchProcessor();+ }+});++test("Batch forces stream: false for all requests", async () => {+ initBatchProcessor();+ try {+ const batchItems = [+ JSON.stringify({+ custom_id: "stream-request",+ method: "POST",+ url: "/v1/chat/completions",+ body: {+ model: "gpt-4o-mini",+ messages: [{ role: "user", content: "Hello" }],+ stream: true+ }+ })+ ].join("\n");++ const file = createFile({+ bytes: Buffer.byteLength(batchItems),+ filename: "stream_force_batch.jsonl",+ purpose: "batch",+ content: Buffer.from(batchItems),+ apiKeyId: null+ });++ const batch = createBatch({+ endpoint: "/v1/chat/completions",+ completionWindow: "24h",+ inputFileId: file.id,+ apiKeyId: null+ });++ let maxAttempts = 20;+ let currentBatch = getBatch(batch.id);+ while (maxAttempts > 0 && currentBatch?.status !== "completed" && currentBatch?.status !== "failed") {+ await new Promise(resolve => setTimeout(resolve, 1000));+ currentBatch = getBatch(batch.id);+ maxAttempts--;+ }++ assert.strictEqual(currentBatch?.status, "completed", "Batch should be completed");+ const outputFileId = currentBatch?.outputFileId || currentBatch?.errorFileId;+ assert.ok(outputFileId, "Should have output or error file ID");+ const outputContent = getFileContent(outputFileId!);+ const result = JSON.parse(outputContent.toString());++ // It shouldn't have "Unexpected token d" error which happens if it tries to parse SSE stream as JSON+ assert.ok(result.response.status_code !== 200 || result.response.body.choices, "Should be a valid chat completion response");+ if (result.response.body.error) {+ assert.ok(!result.response.body.error.message.includes("Unexpected token"), "Should not have JSON parsing error from SSE stream");+ }+ } finally {+ stopBatchProcessor();+ }+});++test("Batch API response format is spec-compliant", async () => {+ // This test doesn't need the processor to run as it checks the object structure returned by endpoints+ const apiKey = await createApiKey("Spec Test Key", "test-machine");++ // Create a mock file first to satisfy foreign key constraint+ const file = createFile({+ bytes: 10,+ filename: "mock.jsonl",+ purpose: "batch",+ content: Buffer.from("{}"),+ apiKeyId: apiKey.id+ });++ // Create a mock batch directly+ const batch = createBatch({+ endpoint: "/v1/chat/completions",+ completionWindow: "24h",+ inputFileId: file.id,+ apiKeyId: apiKey.id,+ metadata: { "test": "meta" }+ });++ // Mock an update with some counts and usage+ updateBatch(batch.id, {+ status: "completed",+ requestCountsTotal: 10,+ requestCountsCompleted: 8,+ requestCountsFailed: 2,+ model: "gpt-4o-mini",+ usage: {+ input_tokens: 100,+ output_tokens: 50,+ total_tokens: 150,+ input_tokens_details: { cached_tokens: 10 },+ output_tokens_details: { reasoning_tokens: 5 }+ }+ });++ const updatedBatch = getBatch(batch.id)!;++ // Test the formatter used in API routes (simulate the route's response)+ function formatBatchResponse(batch: any) {+ return {+ id: batch.id,+ object: "batch",+ endpoint: batch.endpoint,+ errors: batch.errors || null,+ input_file_id: batch.inputFileId,+ completion_window: batch.completionWindow,+ status: batch.status,+ output_file_id: batch.outputFileId || null,+ error_file_id: batch.errorFileId || null,+ created_at: batch.createdAt,+ in_progress_at: batch.inProgressAt || null,+ expires_at: batch.expiresAt || null,+ finalizing_at: batch.finalizingAt || null,+ completed_at: batch.completedAt || null,+ failed_at: batch.failedAt || null,+ expired_at: batch.expiredAt || null,+ cancelling_at: batch.cancellingAt || null,+ cancelled_at: batch.cancelledAt || null,+ request_counts: {+ total: batch.requestCountsTotal || 0,+ completed: batch.requestCountsCompleted || 0,+ failed: batch.requestCountsFailed || 0,+ },+ metadata: batch.metadata || null,+ model: batch.model || null,+ usage: batch.usage || null,+ };+ }++ const response = formatBatchResponse(updatedBatch);++ // Verify all required spec fields are present and structured correctly+ assert.strictEqual(response.id, batch.id);+ assert.strictEqual(response.object, "batch");+ assert.strictEqual(response.endpoint, "/v1/chat/completions");+ assert.strictEqual(response.completion_window, "24h");+ assert.strictEqual(response.status, "completed");+ assert.ok(response.request_counts, "Should have request_counts");+ assert.strictEqual(response.request_counts.total, 10);+ assert.strictEqual(response.request_counts.completed, 8);+ assert.strictEqual(response.request_counts.failed, 2);+ assert.ok(response.usage, "Should have usage");+ assert.strictEqual(response.usage.total_tokens, 150);+ assert.strictEqual(response.usage.input_tokens_details.cached_tokens, 10);+ assert.strictEqual(response.usage.output_tokens_details.reasoning_tokens, 5);+ assert.strictEqual(response.model, "gpt-4o-mini");+ assert.deepStrictEqual(response.metadata, { "test": "meta" });+});++test("List batches pagination and response format", async () => {+ const apiKey = await createApiKey("List Test Key", "test-machine");++ // 1. Create multiple batches+ const file = createFile({+ bytes: 10,+ filename: "list_mock.jsonl",+ purpose: "batch",+ content: Buffer.from("{}"),+ apiKeyId: apiKey.id+ });++ const batchIds: string[] = [];+ for (let i = 0; i < 5; i++) {+ const b = createBatch({+ endpoint: "/v1/chat/completions",+ completionWindow: "24h",+ inputFileId: file.id,+ apiKeyId: apiKey.id,+ metadata: { index: i }+ });+ batchIds.push(b.id);+ }++ // Sort batchIds in descending order as listBatches returns them by ID DESC+ batchIds.sort().reverse();++ // 2. Test listBatches logic (direct DB call)+ const { listBatches } = await import("../../src/lib/localDb");+ const allBatches = listBatches(apiKey.id, 10);+ assert.strictEqual(allBatches.length, 5);+ assert.strictEqual(allBatches[0].id, batchIds[0]);++ // 3. Test pagination logic (as implemented in the route)+ const limit = 2;+ const batchesPage1 = listBatches(apiKey.id, limit + 1);+ const hasMore1 = batchesPage1.length > limit;+ const data1 = hasMore1 ? batchesPage1.slice(0, limit) : batchesPage1;++ assert.strictEqual(data1.length, 2);+ assert.strictEqual(hasMore1, true);+ assert.strictEqual(data1[0].id, batchIds[0]);+ assert.strictEqual(data1[1].id, batchIds[1]);++ const after = data1[1].id;+ const batchesPage2 = listBatches(apiKey.id, limit + 1, after);+ const hasMore2 = batchesPage2.length > limit;+ const data2 = hasMore2 ? batchesPage2.slice(0, limit) : batchesPage2;++ assert.strictEqual(data2.length, 2);+ assert.strictEqual(hasMore2, true);+ assert.strictEqual(data2[0].id, batchIds[2]);+ assert.strictEqual(data2[1].id, batchIds[3]);++ const after2 = data2[1].id;+ const batchesPage3 = listBatches(apiKey.id, limit + 1, after2);+ const hasMore3 = batchesPage3.length > limit;+ const data3 = hasMore3 ? batchesPage3.slice(0, limit) : batchesPage3;++ assert.strictEqual(data3.length, 1);+ assert.strictEqual(hasMore3, false);+ assert.strictEqual(data3[0].id, batchIds[4]);+});++test("Batch Cancel API", async () => {+ const apiKey = await createApiKey("Cancel Test Key", "test-machine");++ const file = createFile({+ bytes: 10,+ filename: "cancel_mock.jsonl",+ purpose: "batch",+ content: Buffer.from("{}"),+ apiKeyId: apiKey.id+ });++ const batch = createBatch({+ endpoint: "/v1/chat/completions",+ completionWindow: "24h",+ inputFileId: file.id,+ apiKeyId: apiKey.id+ });++ // 1. Initially validating+ assert.strictEqual(batch.status, "validating");++ // 2. Cancel it+ const cancellingAt = Math.floor(Date.now() / 1000);+ updateBatch(batch.id, {+ status: "cancelling",+ cancellingAt+ });++ const updatedBatch = getBatch(batch.id)!;+ assert.strictEqual(updatedBatch.status, "cancelling");+ assert.strictEqual(updatedBatch.cancellingAt, cancellingAt);++ // 3. Test that it can't be cancelled if already terminal+ updateBatch(batch.id, { status: "completed" });+ const terminalBatch = getBatch(batch.id)!;+ assert.strictEqual(terminalBatch.status, "completed");++ // In actual API this would return 400, here we just verify state logic+ const canCancel = !["completed", "failed", "cancelled", "expired"].includes(terminalBatch.status);+ assert.strictEqual(canCancel, false);+});++test("List files pagination and response format", async () => {+ const apiKey = await createApiKey("File List Test Key", "test-machine");++ // 1. Create multiple files+ const fileIds: string[] = [];+ for (let i = 0; i < 5; i++) {+ const f = createFile({+ bytes: 10 + i,+ filename: `file_${i}.jsonl`,+ purpose: i % 2 === 0 ? "batch" : "fine-tune",+ content: Buffer.from("{}"),+ apiKeyId: apiKey.id+ });+ fileIds.push(f.id);+ }++ // Default order is DESC (by created_at, then ID)+ const allFilesSorted = listFiles({ apiKeyId: apiKey.id, order: "desc" });+ const sortedFileIds = allFilesSorted.map(f => f.id);++ // 2. Test listFiles options+ assert.strictEqual(allFilesSorted.length, 5);+ assert.strictEqual(allFilesSorted[0].id, sortedFileIds[0]);++ // 3. Test filtering by purpose+ const batchFiles = listFiles({ apiKeyId: apiKey.id, purpose: "batch" });+ assert.strictEqual(batchFiles.length, 3); // 0, 2, 4+ assert.ok(batchFiles.every(f => f.purpose === "batch"));++ // 4. Test pagination+ const limit = 2;+ const page1 = listFiles({ apiKeyId: apiKey.id, limit });+ assert.strictEqual(page1.length, 2);+ assert.strictEqual(page1[0].id, sortedFileIds[0]);+ assert.strictEqual(page1[1].id, sortedFileIds[1]);++ const after = page1[1].id;+ const page2 = listFiles({ apiKeyId: apiKey.id, limit, after });+ assert.strictEqual(page2.length, 2);+ assert.strictEqual(page2[0].id, sortedFileIds[2]);+ assert.strictEqual(page2[1].id, sortedFileIds[3]);++ const after2 = page2[1].id;+ const page3 = listFiles({ apiKeyId: apiKey.id, limit, after: after2 });+ assert.strictEqual(page3.length, 1);+ assert.strictEqual(page3[0].id, sortedFileIds[4]);++ // 5. Test sorting+ const ascFiles = listFiles({ apiKeyId: apiKey.id, order: "asc" });+ assert.strictEqual(ascFiles.length, 5);+ assert.strictEqual(ascFiles[0].id, [...sortedFileIds].reverse()[0]);+});++test("File upload with expiration and spec-compliant response", async () => {+ const apiKey = await createApiKey("File Upload Test Key", "test-machine");++ // Simulate File object (Next.js File)+ const content = Buffer.from("test content");+ const mockFile = {+ size: content.length,+ name: "test.txt",+ type: "text/plain"+ };++ // We'll test the DB logic and the formatting logic separately+ // as it's hard to call the Next.js route directly in this unit test.++ const expiresAfterSeconds = 3600;+ const expiresAt = Math.floor(Date.now() / 1000) + expiresAfterSeconds;++ const record = createFile({+ bytes: mockFile.size,+ filename: mockFile.name,+ purpose: "batch",+ content: content,+ mimeType: mockFile.type,+ apiKeyId: apiKey.id,+ expiresAt: expiresAt+ });++ assert.strictEqual(record.expiresAt, expiresAt);++ const response = formatFileResponse(record);+ assert.strictEqual(response.id, record.id);+ assert.strictEqual(response.object, "file");+ assert.strictEqual(response.expires_at, expiresAt);+ assert.strictEqual(response.status, "validating");+ assert.ok(!("content" in response), "Response should not contain content");+ assert.ok(!("apiKeyId" in response), "Response should not contain apiKeyId");+});++test("Retrieve file spec compliance", async () => {+ const apiKey = await createApiKey("File Retrieve Test Key", "test-machine");++ const record = createFile({+ bytes: 123,+ filename: "retrieve_test.jsonl",+ purpose: "batch",+ content: Buffer.from("{}"),+ apiKeyId: apiKey.id,+ status: "processed"+ });++ const response = formatFileResponse(record);++ // Check all required fields from the spec+ assert.strictEqual(response.id, record.id);+ assert.strictEqual(response.bytes, 123);+ assert.strictEqual(typeof response.created_at, "number");+ assert.strictEqual(response.filename, "retrieve_test.jsonl");+ assert.strictEqual(response.object, "file");+ assert.strictEqual(response.purpose, "batch");+ assert.strictEqual(response.status, "processed");+ assert.strictEqual(response.expires_at, null);++ // Ensure no internal fields leak+ assert.ok(!("content" in (response as any)));+ assert.ok(!("apiKeyId" in (response as any)));+ assert.ok(!("mimeType" in (response as any)));+});++test("File deletion", async () => {+ const apiKey = await createApiKey("File Delete Test Key", "test-machine");++ const record = createFile({+ bytes: 123,+ filename: "delete_test.jsonl",+ purpose: "batch",+ content: Buffer.from("{}"),+ apiKeyId: apiKey.id+ });++ const fileBefore = getFile(record.id);+ assert.ok(fileBefore !== null);+ assert.strictEqual(fileBefore.id, record.id);++ const deleted = deleteFile(record.id);+ assert.ok(deleted);++ const fileAfter = getFile(record.id);+ assert.strictEqual(fileAfter, null);++ // Verify deletion of content for security+ const db = getDbInstance();+ const row = db.prepare("SELECT content, deleted_at FROM files WHERE id = ?").get(record.id) as any;+ assert.ok(row !== undefined);+ assert.strictEqual(row.content, null);+ assert.ok(row.deleted_at !== null);+});++test("Retrieve file content spec compliance", async () => {+ const apiKey = await createApiKey("File Content Test Key", "test-machine");+ const content = Buffer.from('{"id":"req_1","custom_id":"request-1","response":{"status_code":200,"body":{"choices":[{"message":{"content":"Hello"}}]}}}');++ const record = createFile({+ bytes: content.length,+ filename: "content_test.jsonl",+ purpose: "batch",+ content: content,+ mimeType: "application/jsonl",+ apiKeyId: apiKey.id+ });++ const retrievedContent = getFileContent(record.id);+ assert.ok(retrievedContent !== null);+ assert.deepStrictEqual(retrievedContent, content);++ // Verify ownership check logic (similar to route.ts)+ const file = getFile(record.id);+ assert.ok(file !== null);+ assert.strictEqual(file.apiKeyId, apiKey.id);++ // Verify cross-key access failure+ const otherApiKey = await createApiKey("Other Key", "other-machine");+ assert.ok(file.apiKeyId !== otherApiKey.id);++ // In the route, this would return 404+ const unauthorized = (file.apiKeyId !== null && file.apiKeyId !== otherApiKey.id);+ assert.ok(unauthorized);+});