Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(server): split the 1,241-line agentEval router into sub-domain modules (#21099)

Arvin Xu9b87e261dad7
diff --git a/apps/server/src/routers/lambda/agentEval.ts b/apps/server/src/routers/lambda/agentEval.ts
deleted file mode 100644
index 33834103e73..00000000000
--- a/apps/server/src/routers/lambda/agentEval.ts
+++ /dev/null
@@ -1,1241 +0,0 @@
-import { parseDataset } from '@lobechat/eval-dataset-parser';
-import { TRPCError } from '@trpc/server';
-import debug from 'debug';
-import { z } from 'zod';
-
-import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
-import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
-import {
- AgentEvalBenchmarkModel,
- AgentEvalDatasetModel,
- AgentEvalExperimentModel,
- AgentEvalRunModel,
- AgentEvalRunTopicModel,
- AgentEvalTestCaseModel,
-} from '@/database/models/agentEval';
-import { router } from '@/libs/trpc/lambda';
-import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { AgentEvalRunService } from '@/server/services/agentEvalRun';
-import { FileService } from '@/server/services/file';
-import { FileUploadService } from '@/server/services/fileUpload';
-import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';
-
-import { evalRunInputConfigSchema } from './evalRunConfig.schema';
-
-const rubricTypeSchema = z.enum([
- 'equals',
- 'contains',
- 'regex',
- 'starts-with',
- 'ends-with',
- 'any-of',
- 'numeric',
- 'extract-match',
- 'json-schema',
- 'javascript',
- 'python',
- 'llm-rubric',
- 'factuality',
- 'answer-relevance',
- 'similar',
- 'levenshtein',
- 'rubric',
- 'external',
-]);
-
-const evalConfigSchema = z.object({ judgePrompt: z.string().optional() }).passthrough();
-
-const evalCaseEnvironmentSchema = z
- .object({
- envPrompt: z.string().optional(),
- toolForwarding: z
- .record(
- z.string().trim().min(1),
- z
- .object({
- endpoint: z.string().url(),
- timeoutMs: z.number().int().positive().optional(),
- })
- .strict(),
- )
- .optional(),
- })
- .strict();
-
-const dateValueSchema = z.union([
- z.number().finite(),
- z.string().refine((value) => !Number.isNaN(Date.parse(value)), 'Invalid timestamp'),
-]);
-
-const recordSchema = z.record(z.string(), z.unknown());
-
-const evalTestCaseMessagesSchema = z
- .array(
- z
- .object({
- content: z.string(),
- createdAt: dateValueSchema.optional(),
- error: recordSchema.optional(),
- id: z.string().min(1).optional(),
- metadata: recordSchema.optional(),
- model: z.string().optional(),
- parentId: z.string().min(1).nullable().optional(),
- plugin: recordSchema.optional(),
- pluginError: recordSchema.optional(),
- pluginIntervention: recordSchema.optional(),
- pluginState: recordSchema.optional(),
- provider: z.string().optional(),
- reasoning: recordSchema.optional(),
- role: z.enum(['user', 'assistant', 'system', 'tool']),
- search: recordSchema.optional(),
- tool_call_id: z.string().optional(),
- tools: z.array(recordSchema).optional(),
- traceId: z.string().optional(),
- updatedAt: dateValueSchema.optional(),
- })
- .strict(),
- )
- .superRefine((messages, ctx) => {
- const ids = new Set<string>();
-
- for (const [index, message] of messages.entries()) {
- if (!message.id) continue;
- if (ids.has(message.id)) {
- ctx.addIssue({
- code: 'custom',
- message: 'Message ids must be unique',
- path: [index, 'id'],
- });
- }
- ids.add(message.id);
- }
-
- for (const [index, message] of messages.entries()) {
- if (message.parentId && !ids.has(message.parentId)) {
- ctx.addIssue({
- code: 'custom',
- message: 'Message parentId must reference a message in the same sequence',
- path: [index, 'parentId'],
- });
- }
- }
- });
-
-const evalTestCaseContentSchema = z.object({
- category: z.string().optional(),
- choices: z.array(z.string()).optional(),
- environment: evalCaseEnvironmentSchema.optional(),
- expected: z.string().optional(),
- input: z.string(),
- messages: evalTestCaseMessagesSchema.optional(),
-});
-
-const log = debug('lobe-lambda-router:agent-eval');
-
-const agentEvalProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
- const { ctx } = opts;
- const wsId = ctx.workspaceId ?? undefined;
-
- return opts.next({
- ctx: {
- benchmarkModel: new AgentEvalBenchmarkModel(ctx.serverDB, ctx.userId, wsId),
- datasetModel: new AgentEvalDatasetModel(ctx.serverDB, ctx.userId, wsId),
- experimentModel: new AgentEvalExperimentModel(ctx.serverDB, ctx.userId, wsId),
- runModel: new AgentEvalRunModel(ctx.serverDB, ctx.userId, wsId),
- runService: new AgentEvalRunService(ctx.serverDB, ctx.userId, wsId),
- runTopicModel: new AgentEvalRunTopicModel(ctx.serverDB, ctx.userId, wsId),
- testCaseModel: new AgentEvalTestCaseModel(ctx.serverDB, ctx.userId, wsId),
- fileService: new FileService(ctx.serverDB, ctx.userId, wsId),
- fileUploadService: new FileUploadService(ctx.serverDB, ctx.userId, wsId),
- },
- });
-});
-
-// Write variant for mutations — gates viewers out of all eval-creation/edit
-// flows. Reads keep using `agentEvalProcedure` (viewers may inspect existing
-// benchmarks / runs).
-const agentEvalProcedureWrite = agentEvalProcedure.use(withScopedPermission('agent:update'));
-
-export const agentEvalRouter = router({
- // ============================================
- // Benchmark Operations
- // ============================================
- createBenchmark: agentEvalProcedureWrite
- .input(
- z.object({
- identifier: z.string(),
- name: z.string(),
- description: z.string().optional(),
- rubrics: z.array(z.any()).optional().default([]), // EvalBenchmarkRubric[]
- referenceUrl: z.string().optional(),
- metadata: z.record(z.string(), z.unknown()).optional(),
- isSystem: z.boolean().default(false),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- try {
- const result = await ctx.benchmarkModel.create(input);
- if (!result) {
- throw new TRPCError({
- code: 'INTERNAL_SERVER_ERROR',
- message: 'Failed to create benchmark',
- });
- }
- return result;
- } catch (error: any) {
- // PostgreSQL errors might be in error.cause
- const pgError = error?.cause || error;
-
- // Check for unique constraint violation (Postgres error code 23505)
- if (pgError?.code === '23505' || pgError?.constraint?.includes('identifier')) {
- throw new TRPCError({
- code: 'CONFLICT',
- message: `Benchmark with identifier "${input.identifier}" already exists`,
- });
- }
- throw error;
- }
- }),
-
- listBenchmarks: agentEvalProcedure
- .input(z.object({ includeSystem: z.boolean().default(true) }).optional())
- .query(async ({ ctx, input }) => {
- return ctx.benchmarkModel.query(input?.includeSystem);
- }),
-
- getBenchmark: agentEvalProcedure
- .input(z.object({ id: z.string() }))
- .query(async ({ ctx, input }) => {
- const benchmark = await ctx.benchmarkModel.findById(input.id);
- if (!benchmark) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Benchmark not found' });
- }
- return benchmark;
- }),
-
- updateBenchmark: agentEvalProcedureWrite
- .input(
- z.object({
- id: z.string(),
- name: z.string().optional(),
- description: z.string().optional(),
- rubrics: z.array(z.any()).optional(),
- referenceUrl: z.string().optional(),
- metadata: z.record(z.string(), z.unknown()).optional(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const { id, ...data } = input;
- const result = await ctx.benchmarkModel.update(id, data);
- if (!result) {
- throw new TRPCError({
- code: 'NOT_FOUND',
- message: 'Benchmark not found or cannot be updated',
- });
- }
- return result;
- }),
-
- deleteBenchmark: agentEvalProcedureWrite
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input, ctx }) => {
- try {
- const result = await ctx.benchmarkModel.delete(input.id);
- // Check if any rows were affected
- if (result.rowCount === 0) {
- return {
- success: false,
- error: 'Benchmark not found or cannot be deleted (system benchmarks cannot be deleted)',
- };
- }
- return { success: true };
- } catch (error) {
- return {
- success: false,
- error: error instanceof Error ? error.message : 'Failed to delete benchmark',
- };
- }
- }),
-
- // ============================================
- // Experiment Operations
- // ============================================
- createExperiment: agentEvalProcedureWrite
- .input(
- z.object({
- // Optional caller-supplied id for cross-server idempotent creation.
- id: z.string().optional(),
- name: z.string(),
- description: z.string().optional(),
- metadata: z.record(z.string(), z.unknown()).optional(),
- benchmarkIds: z.array(z.string()).min(1),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const data = await ctx.experimentModel.create(input);
- return { data, success: true };
- }),
-
- listExperiments: agentEvalProcedure.query(async ({ ctx }) => {
- const data = await ctx.experimentModel.query();
- return { data, success: true };
- }),
-
- getExperiment: agentEvalProcedure
- .input(z.object({ id: z.string() }))
- .query(async ({ input, ctx }) => {
- const experiment = await ctx.experimentModel.findById(input.id);
- if (!experiment) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Experiment not found' });
- }
-
- // Enrich runs with target agent display info (batched) and dataset name
- // (mapped from the datasets already fetched — no extra queries).
- const agentIds = [
- ...new Set(experiment.runs.map((run) => run.targetAgentId).filter(Boolean)),
- ] as string[];
- const agents = await Promise.all(
- agentIds.map((id) => ctx.runService.getAgentDisplayInfo(id)),
- );
- const agentMap = Object.fromEntries(agents.filter(Boolean).map((a) => [a!.id, a!]));
- const datasetNameMap = new Map(experiment.datasets.map((d) => [d.id, d.name]));
-
- const runs = experiment.runs.map((run) => ({
- ...run,
- datasetName: datasetNameMap.get(run.datasetId) || undefined,
- targetAgent: run.targetAgentId ? agentMap[run.targetAgentId] : undefined,
- }));
-
- return { data: { ...experiment, runs }, success: true };
- }),
-
- updateExperiment: agentEvalProcedureWrite
- .input(
- z.object({
- id: z.string(),
- name: z.string().optional(),
- description: z.string().optional(),
- metadata: z.record(z.string(), z.unknown()).optional(),
- benchmarkIds: z.array(z.string()).optional(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const { id, ...data } = input;
- const result = await ctx.experimentModel.update(id, data);
- if (!result) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Experiment not found' });
- }
- return { data: result, success: true };
- }),
-
- deleteExperiment: agentEvalProcedureWrite
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input, ctx }) => {
- try {
- const result = await ctx.experimentModel.delete(input.id);
- if (result.rowCount === 0) {
- return { success: false, error: 'Experiment not found' };
- }
- return { success: true };
- } catch (error) {
- return {
- success: false,
- error: error instanceof Error ? error.message : 'Failed to delete experiment',
- };
- }
- }),
-
- // ============================================
- // Dataset Operations
- // ============================================
- createDataset: agentEvalProcedureWrite
- .input(
- z.object({
- // Optional: a dataset accumulated from captured cases belongs to no
- // published benchmark.
- benchmarkId: z.string().optional(),
- identifier: z.string(),
- name: z.string(),
- description: z.string().optional(),
- evalMode: rubricTypeSchema.optional(),
- evalConfig: evalConfigSchema.optional(),
- metadata: z.record(z.string(), z.unknown()).optional(),
- sourceExperimentId: z.string().optional(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- try {
- const result = await ctx.datasetModel.create(input);
- if (!result) {
- throw new TRPCError({
- code: 'INTERNAL_SERVER_ERROR',
- message: 'Failed to create dataset',
- });
- }
- return result;
- } catch (error: any) {
- // PostgreSQL errors might be in error.cause
- const pgError = error?.cause || error;
-
- // Check for unique constraint violation (Postgres error code 23505)
- if (pgError?.code === '23505' || pgError?.constraint?.includes('identifier')) {
- throw new TRPCError({
- code: 'CONFLICT',
- message: `Dataset with identifier "${input.identifier}" already exists for this user`,
- });
- }
- // Check for foreign key violation (benchmark not found)
- if (pgError?.code === '23503' && pgError?.constraint?.includes('benchmark')) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: `Benchmark with id "${input.benchmarkId}" not found`,
- });
- }
- throw error;
- }
- }),
-
- listDatasets: agentEvalProcedure
- .input(z.object({ benchmarkId: z.string().optional() }).optional())
- .query(async ({ ctx, input }) => {
- return ctx.datasetModel.query({ benchmarkId: input?.benchmarkId });
- }),
-
- getDataset: agentEvalProcedure
- .input(z.object({ id: z.string() }))
- .query(async ({ ctx, input }) => {
- const dataset = await ctx.datasetModel.findById(input.id);
- if (!dataset) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Dataset not found' });
- }
- return dataset;
- }),
-
- updateDataset: agentEvalProcedureWrite
- .input(
- z.object({
- id: z.string(),
- name: z.string().optional(),
- description: z.string().optional(),
- evalMode: rubricTypeSchema.nullish(),
- evalConfig: evalConfigSchema.nullish(),
- metadata: z.record(z.string(), z.unknown()).optional(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const { id, ...data } = input;
- const result = await ctx.datasetModel.update(id, data);
- if (!result) {
- throw new TRPCError({
- code: 'NOT_FOUND',
- message: 'Dataset not found or cannot be updated',
- });
- }
- return result;
- }),
-
- deleteDataset: agentEvalProcedureWrite
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input, ctx }) => {
- try {
- const result = await ctx.datasetModel.delete(input.id);
- // Check if any rows were affected
- if (result.rowCount === 0) {
- return {
- success: false,
- error: 'Dataset not found or you do not have permission to delete it',
- };
- }
- return { success: true };
- } catch (error) {
- return {
- success: false,
- error: error instanceof Error ? error.message : 'Failed to delete dataset',
- };
- }
- }),
-
- parseDatasetFile: agentEvalProcedureWrite
- .input(
- z.object({
- pathname: z.string(),
- format: z.enum(['json', 'jsonl', 'csv', 'xlsx']).optional(),
- filename: z.string().optional(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const upload = await ctx.fileUploadService.assertActiveOrLegacy(input.pathname);
- const format = input.format || 'auto';
- const resolvedFilename = input.filename || input.pathname;
- const isXlsx = format === 'xlsx' || resolvedFilename?.match(/\.xlsx?$/i);
-
- try {
- const content = isXlsx
- ? await ctx.fileService.getFileByteArray(input.pathname)
- : await ctx.fileService.getFileContent(input.pathname);
- const result = parseDataset(content, {
- filename: resolvedFilename,
- format: format === 'auto' ? undefined : format,
- preview: 50,
- });
-
- return {
- headers: result.headers,
- preview: result.rows,
- totalCount: result.totalCount,
- format: result.format,
- };
- } catch (error: any) {
- if (upload) await ctx.fileUploadService.releaseBestEffort(input.pathname);
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: `Failed to parse file: ${error.message}`,
- });
- }
- }),
-
- importDataset: agentEvalProcedureWrite
- .input(
- z.object({
- datasetId: z.string(),
- pathname: z.string(),
- format: z.enum(['json', 'jsonl', 'csv', 'xlsx']).optional(),
- filename: z.string().optional(),
- fieldMapping: z.object({
- input: z.string(),
- expected: z.string().optional(),
- expectedDelimiter: z.string().optional(),
- choices: z.string().optional(),
- category: z.string().optional(),
- metadata: z.record(z.string(), z.string()).optional(),
- sortOrder: z.string().optional(),
- }),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const upload = await ctx.fileUploadService.assertActiveOrLegacy(input.pathname);
- let imported = false;
-
- try {
- const format = input.format || 'auto';
- const resolvedFilename = input.filename || input.pathname;
- const isXlsx = format === 'xlsx' || resolvedFilename?.match(/\.xlsx?$/i);
-
- let parsed;
- try {
- const content = isXlsx
- ? await ctx.fileService.getFileByteArray(input.pathname)
- : await ctx.fileService.getFileContent(input.pathname);
- parsed = parseDataset(content, {
- filename: resolvedFilename,
- format: format === 'auto' ? undefined : format,
- });
- } catch (error: any) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: `Failed to parse file: ${error.message}`,
- });
- }
-
- const { fieldMapping } = input;
-
- // Get the current max sortOrder so new imports continue from there
- const existingCount = await ctx.testCaseModel.countByDatasetId(input.datasetId);
-
- const testCases = parsed.rows.map((row, index) => {
- let expectedStr: string | undefined;
-
- if (fieldMapping.expected) {
- const raw = row[fieldMapping.expected];
- if (raw != null) {
- // Split multi-candidate answers by delimiter
- if (fieldMapping.expectedDelimiter) {
- const candidates = String(raw)
- .split(fieldMapping.expectedDelimiter)
- .map((s: string) => s.trim())
- .filter(Boolean);
- expectedStr = candidates.length > 1 ? JSON.stringify(candidates) : String(raw);
- } else {
- expectedStr = String(raw);
- }
- }
- }
-
- // Handle choices field (array or JSON string)
- let choices: string[] | undefined;
- if (fieldMapping.choices) {
- const rawChoices = row[fieldMapping.choices];
- if (Array.isArray(rawChoices)) {
- choices = rawChoices.map(String);
- } else if (typeof rawChoices === 'string') {
- try {
- const parsed = JSON.parse(rawChoices);
- if (Array.isArray(parsed)) choices = parsed.map(String);
- } catch {
- // Not JSON, skip
- }
- }
- }
-
- // Compute sortOrder: use CSV column value if mapped, otherwise auto-increment from 1
- let sortOrder: number;
- if (fieldMapping.sortOrder) {
- const raw = Number(row[fieldMapping.sortOrder]);
- sortOrder = Number.isFinite(raw) ? raw : existingCount + index + 1;
- } else {
- sortOrder = existingCount + index + 1;
- }
-
- return {
- datasetId: input.datasetId,
- content: {
- input: String(row[fieldMapping.input] ?? ''),
- expected: expectedStr,
- choices,
- category: fieldMapping.category ? String(row[fieldMapping.category]) : undefined,
- },
- metadata: fieldMapping.metadata
- ? Object.fromEntries(
- Object.entries(fieldMapping.metadata).map(([key, col]) => [
- key,
- row[col as string],
- ]),
- )
- : {},
- sortOrder,
- };
- });
-
- const result = await ctx.testCaseModel.batchCreate(testCases);
- imported = true;
-
- return { count: result.length, data: result };
- } finally {
- if (upload) await ctx.fileUploadService.releaseBestEffort(input.pathname);
- else if (imported) await ctx.fileService.deleteFile(input.pathname);
- }
- }),
-
- // ============================================
- // TestCase Operations
- // ============================================
- createTestCase: agentEvalProcedureWrite
- .input(
- z.object({
- datasetId: z.string(),
- content: evalTestCaseContentSchema,
- evalMode: rubricTypeSchema.optional(),
- evalConfig: evalConfigSchema.optional(),
- metadata: z.record(z.string(), z.unknown()).optional(),
- sortOrder: z.number().optional(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- try {
- const result = await ctx.testCaseModel.create(input);
- if (!result) {
- throw new TRPCError({
- code: 'INTERNAL_SERVER_ERROR',
- message: 'Failed to create test case',
- });
- }
- return result;
- } catch (error: any) {
- // PostgreSQL errors might be in error.cause
- const pgError = error?.cause || error;
-
- // Check for foreign key violation (dataset not found)
- if (pgError?.code === '23503' && pgError?.constraint?.includes('dataset')) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: `Dataset with id "${input.datasetId}" not found`,
- });
- }
- throw error;
- }
- }),
-
- batchCreateTestCases: agentEvalProcedureWrite
- .input(
- z.object({
- datasetId: z.string(),
- cases: z.array(
- z.object({
- content: evalTestCaseContentSchema,
- metadata: z.record(z.string(), z.unknown()).optional(),
- sortOrder: z.number().optional(),
- }),
- ),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- try {
- const testCases = input.cases.map((c) => ({
- ...c,
- datasetId: input.datasetId,
- }));
- const result = await ctx.testCaseModel.batchCreate(testCases);
- return { count: result.length, data: result };
- } catch (error: any) {
- // PostgreSQL errors might be in error.cause
- const pgError = error?.cause || error;
-
- // Check for foreign key violation (dataset not found)
- if (pgError?.code === '23503' && pgError?.constraint?.includes('dataset')) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: `Dataset with id "${input.datasetId}" not found`,
- });
- }
- throw error;
- }
- }),
-
- updateTestCase: agentEvalProcedureWrite
- .input(
- z.object({
- id: z.string(),
- content: z
- .object({
- input: z.string().optional(),
- expected: z.string().optional(),
- choices: z.array(z.string()).optional(),
- category: z.string().optional(),
- environment: evalCaseEnvironmentSchema.optional(),
- messages: evalTestCaseMessagesSchema.optional(),
- })
- .optional(),
- evalMode: rubricTypeSchema.nullish(),
- evalConfig: evalConfigSchema.nullish(),
- metadata: z.record(z.string(), z.unknown()).optional(),
- sortOrder: z.number().optional(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const { id, ...data } = input;
- const result = await ctx.testCaseModel.update(id, data as any);
- if (!result) {
- throw new TRPCError({
- code: 'NOT_FOUND',
- message: 'Test case not found',
- });
- }
- return result;
- }),
-
- deleteTestCase: agentEvalProcedureWrite
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input, ctx }) => {
- try {
- const result = await ctx.testCaseModel.delete(input.id);
- // Check if any rows were affected
- if (result.rowCount === 0) {
- return {
- success: false,
- error: 'Test case not found',
- };
- }
- return { success: true };
- } catch (error) {
- return {
- success: false,
- error: error instanceof Error ? error.message : 'Failed to delete test case',
- };
- }
- }),
-
- getTestCase: agentEvalProcedure
- .input(z.object({ id: z.string() }))
- .query(async ({ ctx, input }) => {
- const testCase = await ctx.testCaseModel.findById(input.id);
- if (!testCase) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Test case not found' });
- }
- return testCase;
- }),
-
- listTestCases: agentEvalProcedure
- .input(
- z.object({
- datasetId: z.string(),
- limit: z.number().min(1).max(100).default(50).optional(),
- offset: z.number().min(0).default(0).optional(),
- }),
- )
- .query(async ({ ctx, input }) => {
- const [data, total] = await Promise.all([
- ctx.testCaseModel.findByDatasetId(input.datasetId, input.limit, input.offset),
- ctx.testCaseModel.countByDatasetId(input.datasetId),
- ]);
- return { data, total };
- }),
-
- // ============================================
- // Run Operations
- // ============================================
- createRun: agentEvalProcedureWrite
- .input(
- z.object({
- datasetId: z.string(),
- targetAgentId: z.string().optional(),
- name: z.string().optional(),
- config: evalRunInputConfigSchema.optional(),
- experimentId: z.string().optional(),
- parentRunId: z.string().optional(),
- // 'external': create claimable (pending) run with no pre-created topics.
- mode: z.enum(['internal', 'external']).optional(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- try {
- const result = await ctx.runService.createRun(input);
- if (!result) {
- throw new TRPCError({
- code: 'INTERNAL_SERVER_ERROR',
- message: 'Failed to create run',
- });
- }
- return result;
- } catch (error: any) {
- const pgError = error?.cause || error;
-
- if (pgError?.message === 'Experiment not found') {
- throw new TRPCError({ code: 'BAD_REQUEST', message: 'Experiment not found' });
- }
- if (pgError?.message === 'Parent run not found') {
- throw new TRPCError({ code: 'BAD_REQUEST', message: 'Parent run not found' });
- }
-
- // Check for foreign key violation (dataset not found)
- if (pgError?.code === '23503' && pgError?.constraint?.includes('dataset')) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: `Dataset with id "${input.datasetId}" not found`,
- });
- }
- throw error;
- }
- }),
-
- listRuns: agentEvalProcedure
- .input(
- z.object({
- benchmarkId: z.string().optional(),
- datasetId: z.string().optional(),
- experimentId: z.string().optional(),
- status: z
- .enum(['idle', 'pending', 'running', 'completed', 'failed', 'aborted', 'external'])
- .optional(),
- limit: z.number().min(1).max(100).default(50).optional(),
- offset: z.number().min(0).default(0).optional(),
- }),
- )
- .query(async ({ ctx, input }) => {
- const data = await ctx.runModel.query({
- benchmarkId: input.benchmarkId,
- datasetId: input.datasetId,
- experimentId: input.experimentId,
- status: input.status,
- limit: input.limit,
- offset: input.offset,
- });
-
- // Enrich runs with dataset name and agent info
- const datasetIds = [...new Set(data.map((r) => r.datasetId))];
- const agentIds = [...new Set(data.map((r) => r.targetAgentId).filter(Boolean))] as string[];
-
- const [datasets, agents] = await Promise.all([
- Promise.all(datasetIds.map((id) => ctx.datasetModel.findById(id))),
- Promise.all(agentIds.map((id) => ctx.runService.getAgentDisplayInfo(id))),
- ]);
-
- const datasetMap = Object.fromEntries(datasets.filter(Boolean).map((d) => [d!.id, d!.name]));
- const agentMap = Object.fromEntries(agents.filter(Boolean).map((a) => [a!.id, a!]));
-
- const enriched = data.map((run) => ({
- ...run,
- datasetName: datasetMap[run.datasetId] || undefined,
- targetAgent: run.targetAgentId ? agentMap[run.targetAgentId] : undefined,
- }));
-
- const total = data.length;
-
- return { data: enriched, total };
- }),
-
- getRunDetails: agentEvalProcedure
- .input(z.object({ id: z.string() }))
- .query(async ({ ctx, input }) => {
- const result = await ctx.runService.getRunDetails(input.id);
- if (!result) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
- }
- return result;
- }),
-
- deleteRun: agentEvalProcedureWrite
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input, ctx }) => {
- try {
- const result = await ctx.runService.deleteRun(input.id);
- // Check if any rows were affected
- if (result.rowCount === 0) {
- return {
- success: false,
- error: 'Run not found or you do not have permission to delete it',
- };
- }
- return { success: true };
- } catch (error) {
- return {
- success: false,
- error: error instanceof Error ? error.message : 'Failed to delete run',
- };
- }
- }),
-
- // ============================================
- // Run Execution Operations
- // ============================================
-
- /**
- * Start executing a run
- * Transitions: idle/failed → pending → running
- */
- startRun: agentEvalProcedureWrite
- .input(
- z.object({
- id: z.string(),
- force: z.boolean().default(false).optional(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const { id: runId, force } = input;
-
- // Get run to validate ownership and status
- const run = await ctx.runModel.findById(runId);
- if (!run) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
- }
-
- // Check run status
- if (run.status === 'running' && !force) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'Run is already running. Use force=true to restart.',
- });
- }
-
- // Set status to pending immediately so frontend gets feedback
- await ctx.runModel.update(runId, { status: 'pending' });
-
- // Trigger workflow
- await AgentEvalRunWorkflow.triggerRunBenchmark({ force, runId, userId: ctx.userId });
-
- return { success: true, runId };
- }),
-
- /**
- * Abort a running evaluation
- */
- abortRun: agentEvalProcedureWrite
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input, ctx }) => {
- const run = await ctx.runModel.findById(input.id);
- if (!run) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
- }
-
- if (run.status !== 'running' && run.status !== 'pending') {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: `Cannot abort run with status: ${run.status}`,
- });
- }
-
- const service = new AgentEvalRunService(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- );
- await service.abortRun(input.id);
-
- return { success: true };
- }),
-
- retryRunErrors: agentEvalProcedureWrite
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input, ctx }) => {
- const run = await ctx.runModel.findById(input.id);
- if (!run) throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
-
- if (!['completed', 'failed', 'aborted'].includes(run.status)) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: `Cannot retry: status=${run.status}`,
- });
- }
-
- const { retryCount } = await ctx.runService.retryErrorCases(input.id);
-
- await AgentEvalRunWorkflow.triggerRunBenchmark({
- force: true,
- runId: input.id,
- userId: ctx.userId,
- });
-
- return { retryCount, runId: input.id, success: true };
- }),
-
- retryRunCase: agentEvalProcedureWrite
- .input(z.object({ runId: z.string(), testCaseId: z.string() }))
- .mutation(async ({ input, ctx }) => {
- const run = await ctx.runModel.findById(input.runId);
- if (!run) throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
-
- if (!['completed', 'failed', 'aborted', 'running'].includes(run.status)) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: `Cannot retry case: run status=${run.status}`,
- });
- }
-
- try {
- await ctx.runService.retrySingleCase(input.runId, input.testCaseId);
- } catch (error) {
- const message = error instanceof Error ? error.message : 'Cannot retry case';
- if (message.startsWith('Cannot retry: case is')) {
- throw new TRPCError({ code: 'CONFLICT', message });
- }
- if (message === 'RunTopic not found') {
- throw new TRPCError({ code: 'NOT_FOUND', message });
- }
- throw error;
- }
-
- await AgentEvalRunWorkflow.triggerExecuteTestCase({
- runId: input.runId,
- testCaseId: input.testCaseId,
- userId: ctx.userId,
- });
-
- return { runId: input.runId, success: true, testCaseId: input.testCaseId };
- }),
-
- resumeRunCase: agentEvalProcedureWrite
- .input(z.object({ runId: z.string(), testCaseId: z.string(), threadId: z.string().optional() }))
- .mutation(async ({ input, ctx }) => {
- log(
- 'resumeRunCase: runId=%s testCaseId=%s threadId=%s',
- input.runId,
- input.testCaseId,
- input.threadId,
- );
- const result = await ctx.runService.resumeTrajectory({
- runId: input.runId,
- testCaseId: input.testCaseId,
- threadId: input.threadId,
- });
- log('resumeRunCase: result %O', result);
- return result;
- }),
-
- batchResumeRunCases: agentEvalProcedureWrite
- .input(
- z.object({
- runId: z.string(),
- targets: z.array(z.object({ testCaseId: z.string(), threadId: z.string().optional() })),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- log('batchResumeRunCases: runId=%s count=%d', input.runId, input.targets.length);
- const results = await Promise.allSettled(
- input.targets.map((target) =>
- ctx.runService.resumeTrajectory({
- runId: input.runId,
- testCaseId: target.testCaseId,
- threadId: target.threadId,
- }),
- ),
- );
- const succeeded = results.filter((r) => r.status === 'fulfilled').length;
- const failed = results.filter((r) => r.status === 'rejected').length;
- log('batchResumeRunCases: succeeded=%d failed=%d', succeeded, failed);
- return { failed, succeeded, total: input.targets.length };
- }),
-
- getResumableCases: agentEvalProcedure
- .input(z.object({ runId: z.string() }))
- .query(async ({ input, ctx }) => {
- log('getResumableCases: runId=%s', input.runId);
- return ctx.runService.getResumableCases(input.runId);
- }),
-
- /**
- * Get real-time progress of a running evaluation
- */
- getRunProgress: agentEvalProcedure
- .input(z.object({ id: z.string() }))
- .query(async ({ input, ctx }) => {
- let run = await ctx.runModel.findById(input.id);
- if (!run) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
- }
-
- // Check if a 'running' run has timed out
- if (run.status === 'running') {
- const timedOut = await ctx.runService.checkAndHandleRunTimeout(run);
- if (timedOut) {
- run = (await ctx.runModel.findById(input.id))!;
- }
- }
-
- return {
- status: run.status,
- metrics: run.metrics,
- startedAt: run.startedAt,
- updatedAt: run.updatedAt,
- };
- }),
-
- /**
- * Get detailed results of test case executions
- */
- getRunResults: agentEvalProcedure
- .input(
- z.object({
- id: z.string(),
- }),
- )
- .query(async ({ input, ctx }) => {
- const run = await ctx.runModel.findById(input.id);
- if (!run) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
- }
-
- // Get all run topics with test cases and topics
- const allRunTopics = await ctx.runTopicModel.findByRunId(input.id);
-
- return {
- runId: input.id,
- total: allRunTopics.length,
- results: allRunTopics.map((rt) => ({
- createdAt: rt.createdAt,
- evalResult: rt.evalResult,
- passed: rt.passed,
- score: rt.score,
- status: rt.status,
- testCase: rt.testCase,
- testCaseId: rt.testCaseId,
- topic: rt.topic,
- topicId: rt.topicId,
- })),
- };
- }),
-
- /**
- * Update run status (internal use)
- */
- updateRunStatus: agentEvalProcedureWrite
- .input(
- z.object({
- id: z.string(),
- status: z.enum([
- 'idle',
- 'pending',
- 'running',
- 'completed',
- 'failed',
- 'aborted',
- 'external',
- ]),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const { id, status } = input;
-
- const run = await ctx.runModel.findById(id);
- if (!run) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
- }
-
- const result = await ctx.runModel.update(id, { status });
- return result;
- }),
-
- /**
- * Update run metrics (internal use)
- */
- updateRunMetrics: agentEvalProcedureWrite
- .input(
- z.object({
- id: z.string(),
- metrics: z.object({
- totalCases: z.number(),
- passedCases: z.number(),
- failedCases: z.number(),
- averageScore: z.number(),
- passRate: z.number(),
- duration: z.number().optional(),
- rubricScores: z.record(z.string(), z.number()).optional(),
- }),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const { id, metrics } = input;
-
- const run = await ctx.runModel.findById(id);
- if (!run) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
- }
-
- const result = await ctx.runModel.update(id, { metrics });
- return result;
- }),
-
- /**
- * Update run (user-facing: name, datasetId, targetAgentId)
- */
- updateRun: agentEvalProcedureWrite
- .input(
- z.object({
- config: evalRunInputConfigSchema.optional(),
- datasetId: z.string().optional(),
- id: z.string(),
- name: z.string().optional(),
- targetAgentId: z.string().nullish(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const { id, ...updates } = input;
-
- const run = await ctx.runModel.findById(id);
- if (!run) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
- }
-
- // Only allow changing dataset/agent when run hasn't started
- const canChangeConfig = run.status === 'idle';
- const value: Record<string, any> = {};
-
- if (updates.name !== undefined) value.name = updates.name;
- if (canChangeConfig && updates.datasetId !== undefined) value.datasetId = updates.datasetId;
- if (canChangeConfig && updates.targetAgentId !== undefined)
- value.targetAgentId = updates.targetAgentId;
-
- // Config fields can be updated anytime (except when completed)
- if (updates.config) {
- const existingConfig = (run.config as Record<string, unknown>) ?? {};
- const configPatch = Object.fromEntries(
- Object.entries(updates.config).filter(([, v]) => v !== undefined),
- );
- if (Object.keys(configPatch).length > 0) {
- value.config = { ...existingConfig, ...configPatch };
- }
- }
-
- if (Object.keys(value).length === 0) return run;
-
- return ctx.runModel.update(id, value);
- }),
-});
diff --git a/apps/server/src/routers/lambda/agentEval/benchmarks.ts b/apps/server/src/routers/lambda/agentEval/benchmarks.ts
new file mode 100644
index 00000000000..98468a1fd44
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/benchmarks.ts
@@ -0,0 +1,104 @@
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { router } from '@/libs/trpc/lambda';
+
+import { agentEvalProcedure, agentEvalProcedureWrite } from './procedures';
+
+export const benchmarkRouter = router({
+ // ============================================
+ // Benchmark Operations
+ // ============================================
+ createBenchmark: agentEvalProcedureWrite
+ .input(
+ z.object({
+ identifier: z.string(),
+ name: z.string(),
+ description: z.string().optional(),
+ rubrics: z.array(z.any()).optional().default([]), // EvalBenchmarkRubric[]
+ referenceUrl: z.string().optional(),
+ metadata: z.record(z.string(), z.unknown()).optional(),
+ isSystem: z.boolean().default(false),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ const result = await ctx.benchmarkModel.create(input);
+ if (!result) {
+ throw new TRPCError({
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'Failed to create benchmark',
+ });
+ }
+ return result;
+ } catch (error: any) {
+ // PostgreSQL errors might be in error.cause
+ const pgError = error?.cause || error;
+
+ // Check for unique constraint violation (Postgres error code 23505)
+ if (pgError?.code === '23505' || pgError?.constraint?.includes('identifier')) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: `Benchmark with identifier "${input.identifier}" already exists`,
+ });
+ }
+ throw error;
+ }
+ }),
+ listBenchmarks: agentEvalProcedure
+ .input(z.object({ includeSystem: z.boolean().default(true) }).optional())
+ .query(async ({ ctx, input }) => {
+ return ctx.benchmarkModel.query(input?.includeSystem);
+ }),
+ getBenchmark: agentEvalProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ ctx, input }) => {
+ const benchmark = await ctx.benchmarkModel.findById(input.id);
+ if (!benchmark) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Benchmark not found' });
+ }
+ return benchmark;
+ }),
+ updateBenchmark: agentEvalProcedureWrite
+ .input(
+ z.object({
+ id: z.string(),
+ name: z.string().optional(),
+ description: z.string().optional(),
+ rubrics: z.array(z.any()).optional(),
+ referenceUrl: z.string().optional(),
+ metadata: z.record(z.string(), z.unknown()).optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { id, ...data } = input;
+ const result = await ctx.benchmarkModel.update(id, data);
+ if (!result) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: 'Benchmark not found or cannot be updated',
+ });
+ }
+ return result;
+ }),
+ deleteBenchmark: agentEvalProcedureWrite
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ const result = await ctx.benchmarkModel.delete(input.id);
+ // Check if any rows were affected
+ if (result.rowCount === 0) {
+ return {
+ success: false,
+ error: 'Benchmark not found or cannot be deleted (system benchmarks cannot be deleted)',
+ };
+ }
+ return { success: true };
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to delete benchmark',
+ };
+ }
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agentEval/constants.ts b/apps/server/src/routers/lambda/agentEval/constants.ts
new file mode 100644
index 00000000000..89367ae6bd8
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/constants.ts
@@ -0,0 +1,2 @@
+/** Max in-flight lookups when enriching run lists with dataset and agent info. */
+export const RUN_ENRICHMENT_CONCURRENCY = 5;
diff --git a/apps/server/src/routers/lambda/agentEval/datasets.ts b/apps/server/src/routers/lambda/agentEval/datasets.ts
new file mode 100644
index 00000000000..b845c2e2c76
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/datasets.ts
@@ -0,0 +1,275 @@
+import { parseDataset } from '@lobechat/eval-dataset-parser';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { router } from '@/libs/trpc/lambda';
+
+import { agentEvalProcedure, agentEvalProcedureWrite } from './procedures';
+import { evalConfigSchema, rubricTypeSchema } from './schemas';
+
+export const datasetRouter = router({
+ // ============================================
+ // Dataset Operations
+ // ============================================
+ createDataset: agentEvalProcedureWrite
+ .input(
+ z.object({
+ // Optional: a dataset accumulated from captured cases belongs to no
+ // published benchmark.
+ benchmarkId: z.string().optional(),
+ identifier: z.string(),
+ name: z.string(),
+ description: z.string().optional(),
+ evalMode: rubricTypeSchema.optional(),
+ evalConfig: evalConfigSchema.optional(),
+ metadata: z.record(z.string(), z.unknown()).optional(),
+ sourceExperimentId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ const result = await ctx.datasetModel.create(input);
+ if (!result) {
+ throw new TRPCError({
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'Failed to create dataset',
+ });
+ }
+ return result;
+ } catch (error: any) {
+ // PostgreSQL errors might be in error.cause
+ const pgError = error?.cause || error;
+
+ // Check for unique constraint violation (Postgres error code 23505)
+ if (pgError?.code === '23505' || pgError?.constraint?.includes('identifier')) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: `Dataset with identifier "${input.identifier}" already exists for this user`,
+ });
+ }
+ // Check for foreign key violation (benchmark not found)
+ if (pgError?.code === '23503' && pgError?.constraint?.includes('benchmark')) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Benchmark with id "${input.benchmarkId}" not found`,
+ });
+ }
+ throw error;
+ }
+ }),
+ listDatasets: agentEvalProcedure
+ .input(z.object({ benchmarkId: z.string().optional() }).optional())
+ .query(async ({ ctx, input }) => {
+ return ctx.datasetModel.query({ benchmarkId: input?.benchmarkId });
+ }),
+ getDataset: agentEvalProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ ctx, input }) => {
+ const dataset = await ctx.datasetModel.findById(input.id);
+ if (!dataset) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Dataset not found' });
+ }
+ return dataset;
+ }),
+ updateDataset: agentEvalProcedureWrite
+ .input(
+ z.object({
+ id: z.string(),
+ name: z.string().optional(),
+ description: z.string().optional(),
+ evalMode: rubricTypeSchema.nullish(),
+ evalConfig: evalConfigSchema.nullish(),
+ metadata: z.record(z.string(), z.unknown()).optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { id, ...data } = input;
+ const result = await ctx.datasetModel.update(id, data);
+ if (!result) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: 'Dataset not found or cannot be updated',
+ });
+ }
+ return result;
+ }),
+ deleteDataset: agentEvalProcedureWrite
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ const result = await ctx.datasetModel.delete(input.id);
+ // Check if any rows were affected
+ if (result.rowCount === 0) {
+ return {
+ success: false,
+ error: 'Dataset not found or you do not have permission to delete it',
+ };
+ }
+ return { success: true };
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to delete dataset',
+ };
+ }
+ }),
+ parseDatasetFile: agentEvalProcedureWrite
+ .input(
+ z.object({
+ pathname: z.string(),
+ format: z.enum(['json', 'jsonl', 'csv', 'xlsx']).optional(),
+ filename: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const upload = await ctx.fileUploadService.assertActiveOrLegacy(input.pathname);
+ const format = input.format || 'auto';
+ const resolvedFilename = input.filename || input.pathname;
+ const isXlsx = format === 'xlsx' || resolvedFilename?.match(/\.xlsx?$/i);
+
+ try {
+ const content = isXlsx
+ ? await ctx.fileService.getFileByteArray(input.pathname)
+ : await ctx.fileService.getFileContent(input.pathname);
+ const result = parseDataset(content, {
+ filename: resolvedFilename,
+ format: format === 'auto' ? undefined : format,
+ preview: 50,
+ });
+
+ return {
+ headers: result.headers,
+ preview: result.rows,
+ totalCount: result.totalCount,
+ format: result.format,
+ };
+ } catch (error: any) {
+ if (upload) await ctx.fileUploadService.releaseBestEffort(input.pathname);
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Failed to parse file: ${error.message}`,
+ });
+ }
+ }),
+ importDataset: agentEvalProcedureWrite
+ .input(
+ z.object({
+ datasetId: z.string(),
+ pathname: z.string(),
+ format: z.enum(['json', 'jsonl', 'csv', 'xlsx']).optional(),
+ filename: z.string().optional(),
+ fieldMapping: z.object({
+ input: z.string(),
+ expected: z.string().optional(),
+ expectedDelimiter: z.string().optional(),
+ choices: z.string().optional(),
+ category: z.string().optional(),
+ metadata: z.record(z.string(), z.string()).optional(),
+ sortOrder: z.string().optional(),
+ }),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const upload = await ctx.fileUploadService.assertActiveOrLegacy(input.pathname);
+ let imported = false;
+
+ try {
+ const format = input.format || 'auto';
+ const resolvedFilename = input.filename || input.pathname;
+ const isXlsx = format === 'xlsx' || resolvedFilename?.match(/\.xlsx?$/i);
+
+ let parsed;
+ try {
+ const content = isXlsx
+ ? await ctx.fileService.getFileByteArray(input.pathname)
+ : await ctx.fileService.getFileContent(input.pathname);
+ parsed = parseDataset(content, {
+ filename: resolvedFilename,
+ format: format === 'auto' ? undefined : format,
+ });
+ } catch (error: any) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Failed to parse file: ${error.message}`,
+ });
+ }
+
+ const { fieldMapping } = input;
+
+ // Get the current max sortOrder so new imports continue from there
+ const existingCount = await ctx.testCaseModel.countByDatasetId(input.datasetId);
+
+ const testCases = parsed.rows.map((row, index) => {
+ let expectedStr: string | undefined;
+
+ if (fieldMapping.expected) {
+ const raw = row[fieldMapping.expected];
+ if (raw != null) {
+ // Split multi-candidate answers by delimiter
+ if (fieldMapping.expectedDelimiter) {
+ const candidates = String(raw)
+ .split(fieldMapping.expectedDelimiter)
+ .map((s: string) => s.trim())
+ .filter(Boolean);
+ expectedStr = candidates.length > 1 ? JSON.stringify(candidates) : String(raw);
+ } else {
+ expectedStr = String(raw);
+ }
+ }
+ }
+
+ // Handle choices field (array or JSON string)
+ let choices: string[] | undefined;
+ if (fieldMapping.choices) {
+ const rawChoices = row[fieldMapping.choices];
+ if (Array.isArray(rawChoices)) {
+ choices = rawChoices.map(String);
+ } else if (typeof rawChoices === 'string') {
+ try {
+ const parsed = JSON.parse(rawChoices);
+ if (Array.isArray(parsed)) choices = parsed.map(String);
+ } catch {
+ // Not JSON, skip
+ }
+ }
+ }
+
+ // Compute sortOrder: use CSV column value if mapped, otherwise auto-increment from 1
+ let sortOrder: number;
+ if (fieldMapping.sortOrder) {
+ const raw = Number(row[fieldMapping.sortOrder]);
+ sortOrder = Number.isFinite(raw) ? raw : existingCount + index + 1;
+ } else {
+ sortOrder = existingCount + index + 1;
+ }
+
+ return {
+ datasetId: input.datasetId,
+ content: {
+ input: String(row[fieldMapping.input] ?? ''),
+ expected: expectedStr,
+ choices,
+ category: fieldMapping.category ? String(row[fieldMapping.category]) : undefined,
+ },
+ metadata: fieldMapping.metadata
+ ? Object.fromEntries(
+ Object.entries(fieldMapping.metadata).map(([key, col]) => [
+ key,
+ row[col as string],
+ ]),
+ )
+ : {},
+ sortOrder,
+ };
+ });
+
+ const result = await ctx.testCaseModel.batchCreate(testCases);
+ imported = true;
+
+ return { count: result.length, data: result };
+ } finally {
+ if (upload) await ctx.fileUploadService.releaseBestEffort(input.pathname);
+ else if (imported) await ctx.fileService.deleteFile(input.pathname);
+ }
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agentEval/experiments.ts b/apps/server/src/routers/lambda/agentEval/experiments.ts
new file mode 100644
index 00000000000..7812d6667a8
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/experiments.ts
@@ -0,0 +1,94 @@
+import { TRPCError } from '@trpc/server';
+import pMap from 'p-map';
+import { z } from 'zod';
+
+import { router } from '@/libs/trpc/lambda';
+
+import { RUN_ENRICHMENT_CONCURRENCY } from './constants';
+import { agentEvalProcedure, agentEvalProcedureWrite } from './procedures';
+
+export const experimentRouter = router({
+ // ============================================
+ // Experiment Operations
+ // ============================================
+ createExperiment: agentEvalProcedureWrite
+ .input(
+ z.object({
+ // Optional caller-supplied id for cross-server idempotent creation.
+ id: z.string().optional(),
+ name: z.string(),
+ description: z.string().optional(),
+ metadata: z.record(z.string(), z.unknown()).optional(),
+ benchmarkIds: z.array(z.string()).min(1),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const data = await ctx.experimentModel.create(input);
+ return { data, success: true };
+ }),
+ listExperiments: agentEvalProcedure.query(async ({ ctx }) => {
+ const data = await ctx.experimentModel.query();
+ return { data, success: true };
+ }),
+ getExperiment: agentEvalProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ input, ctx }) => {
+ const experiment = await ctx.experimentModel.findById(input.id);
+ if (!experiment) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Experiment not found' });
+ }
+
+ // Enrich runs with target agent display info (batched) and dataset name
+ // (mapped from the datasets already fetched — no extra queries).
+ const agentIds = [
+ ...new Set(experiment.runs.map((run) => run.targetAgentId).filter(Boolean)),
+ ] as string[];
+ const agents = await pMap(agentIds, (id) => ctx.runService.getAgentDisplayInfo(id), {
+ concurrency: RUN_ENRICHMENT_CONCURRENCY,
+ });
+ const agentMap = Object.fromEntries(agents.filter(Boolean).map((a) => [a!.id, a!]));
+ const datasetNameMap = new Map(experiment.datasets.map((d) => [d.id, d.name]));
+
+ const runs = experiment.runs.map((run) => ({
+ ...run,
+ datasetName: datasetNameMap.get(run.datasetId) || undefined,
+ targetAgent: run.targetAgentId ? agentMap[run.targetAgentId] : undefined,
+ }));
+
+ return { data: { ...experiment, runs }, success: true };
+ }),
+ updateExperiment: agentEvalProcedureWrite
+ .input(
+ z.object({
+ id: z.string(),
+ name: z.string().optional(),
+ description: z.string().optional(),
+ metadata: z.record(z.string(), z.unknown()).optional(),
+ benchmarkIds: z.array(z.string()).optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { id, ...data } = input;
+ const result = await ctx.experimentModel.update(id, data);
+ if (!result) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Experiment not found' });
+ }
+ return { data: result, success: true };
+ }),
+ deleteExperiment: agentEvalProcedureWrite
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ const result = await ctx.experimentModel.delete(input.id);
+ if (result.rowCount === 0) {
+ return { success: false, error: 'Experiment not found' };
+ }
+ return { success: true };
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to delete experiment',
+ };
+ }
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agentEval/fanOut.test.ts b/apps/server/src/routers/lambda/agentEval/fanOut.test.ts
new file mode 100644
index 00000000000..3aa174ac210
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/fanOut.test.ts
@@ -0,0 +1,123 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createCallerFactory } from '@/libs/trpc/lambda';
+
+import { RUN_ENRICHMENT_CONCURRENCY } from './constants';
+import { experimentRouter } from './experiments';
+import type * as Procedures from './procedures';
+import { runRouter } from './runs';
+
+const mocks = vi.hoisted(() => ({
+ datasetFindById: vi.fn(),
+ experimentFindById: vi.fn(),
+ getAgentDisplayInfo: vi.fn(),
+ resumeTrajectory: vi.fn(),
+ runQuery: vi.fn(),
+}));
+
+// Replace the auth/RBAC/DB builders with a bare procedure that injects mocked
+// models, so these tests exercise only the procedure bodies.
+vi.mock('./procedures', async (importOriginal) => {
+ const actual = await importOriginal<typeof Procedures>();
+ const { publicProcedure } = await import('@/libs/trpc/lambda');
+ const procedure = publicProcedure.use((opts) =>
+ opts.next({
+ ctx: {
+ datasetModel: { findById: mocks.datasetFindById },
+ experimentModel: { findById: mocks.experimentFindById },
+ runModel: { query: mocks.runQuery },
+ runService: {
+ getAgentDisplayInfo: mocks.getAgentDisplayInfo,
+ resumeTrajectory: mocks.resumeTrajectory,
+ },
+ } as any,
+ }),
+ );
+ return { ...actual, agentEvalProcedure: procedure, agentEvalProcedureWrite: procedure };
+});
+
+const ctx = {} as any;
+const experiments = createCallerFactory(experimentRouter)(ctx);
+const runs = createCallerFactory(runRouter)(ctx);
+
+/** Wraps an async fn so each call resolves after a tick and tracks peak concurrency. */
+const trackInFlight = <A extends unknown[], R>(fn: (...args: A) => R) => {
+ const state = { inFlight: 0, max: 0 };
+ const wrapped = async (...args: A) => {
+ state.inFlight += 1;
+ state.max = Math.max(state.max, state.inFlight);
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ state.inFlight -= 1;
+ return fn(...args);
+ };
+ return { state, wrapped };
+};
+
+const agent = (id: string) => ({ avatar: null, id, title: `Agent ${id}` });
+const ids = (prefix: string, n: number) => Array.from({ length: n }, (_, i) => `${prefix}${i}`);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('agentEval router fan-outs', () => {
+ it('getExperiment enriches every run in order with a bounded agent lookup', async () => {
+ const agentIds = ids('agent-', 12);
+ mocks.experimentFindById.mockResolvedValue({
+ datasets: [{ id: 'ds-1', name: 'Dataset 1' }],
+ id: 'exp-1',
+ runs: agentIds.map((targetAgentId, i) => ({
+ datasetId: 'ds-1',
+ id: `run-${i}`,
+ targetAgentId,
+ })),
+ });
+ const tracker = trackInFlight((id: string) => agent(id));
+ mocks.getAgentDisplayInfo.mockImplementation(tracker.wrapped);
+
+ const result = await experiments.getExperiment({ id: 'exp-1' });
+
+ expect(result.data.runs.map((r: any) => r.targetAgent)).toEqual(agentIds.map(agent));
+ expect(result.data.runs.every((r: any) => r.datasetName === 'Dataset 1')).toBe(true);
+ expect(tracker.state.max).toBeLessThanOrEqual(RUN_ENRICHMENT_CONCURRENCY);
+ expect(tracker.state.max).toBeGreaterThan(1);
+ });
+
+ it('listRuns enriches dataset names and agents with bounded lookups', async () => {
+ const rows = ids('', 12).map((i) => ({
+ datasetId: `ds-${i}`,
+ id: `run-${i}`,
+ targetAgentId: `agent-${i}`,
+ }));
+ mocks.runQuery.mockResolvedValue(rows);
+ const datasets = trackInFlight((id: string) => ({ id, name: `Name ${id}` }));
+ const agents = trackInFlight((id: string) => agent(id));
+ mocks.datasetFindById.mockImplementation(datasets.wrapped);
+ mocks.getAgentDisplayInfo.mockImplementation(agents.wrapped);
+
+ const result = await runs.listRuns({});
+
+ expect(result.data.map((r: any) => [r.datasetName, r.targetAgent])).toEqual(
+ rows.map((r) => [`Name ${r.datasetId}`, agent(r.targetAgentId)]),
+ );
+ expect(datasets.state.max).toBeLessThanOrEqual(RUN_ENRICHMENT_CONCURRENCY);
+ expect(agents.state.max).toBeLessThanOrEqual(RUN_ENRICHMENT_CONCURRENCY);
+ });
+
+ it('batchResumeRunCases settles each target independently with bounded concurrency', async () => {
+ const targets = ids('case-', 12).map((testCaseId) => ({ testCaseId }));
+ const tracker = trackInFlight(({ testCaseId }: { testCaseId: string }) => {
+ if (testCaseId === 'case-3' || testCaseId === 'case-7') throw new Error('resume failed');
+ return { ok: true };
+ });
+ mocks.resumeTrajectory.mockImplementation(tracker.wrapped);
+
+ const result = await runs.batchResumeRunCases({ runId: 'run-1', targets });
+
+ expect(result).toEqual({ failed: 2, succeeded: 10, total: 12 });
+ expect(mocks.resumeTrajectory).toHaveBeenCalledTimes(12);
+ expect(tracker.state.max).toBeLessThanOrEqual(5);
+ expect(tracker.state.max).toBeGreaterThan(1);
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentEval/index.procedures.test.ts b/apps/server/src/routers/lambda/agentEval/index.procedures.test.ts
new file mode 100644
index 00000000000..570fb437201
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/index.procedures.test.ts
@@ -0,0 +1,68 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { agentEvalRouter } from './index';
+
+/**
+ * Pins the router's public surface: every procedure path, its kind, and its
+ * middleware chain length (which encodes the procedure builder and its input
+ * parsers). Splitting the router across files must keep all three.
+ */
+describe('agentEvalRouter procedures', () => {
+ const procedures = (agentEvalRouter as any)._def.procedures as Record<string, any>;
+
+ it('exposes exactly the expected procedure paths', () => {
+ expect(Object.keys(procedures).sort()).toEqual(expected().map(([name]) => name));
+ });
+
+ it.each(expected())('%s is a %s with %i middlewares', (name, type, middlewares) => {
+ expect(procedures[name]._def.type).toBe(type);
+ expect(procedures[name]._def.middlewares).toHaveLength(middlewares);
+ });
+});
+
+function expected(): Array<
+ [name: string, type: 'mutation' | 'query' | 'subscription', middlewares: number]
+> {
+ return [
+ ['abortRun', 'mutation', 13],
+ ['batchCreateTestCases', 'mutation', 13],
+ ['batchResumeRunCases', 'mutation', 13],
+ ['createBenchmark', 'mutation', 13],
+ ['createDataset', 'mutation', 13],
+ ['createExperiment', 'mutation', 13],
+ ['createRun', 'mutation', 13],
+ ['createTestCase', 'mutation', 13],
+ ['deleteBenchmark', 'mutation', 13],
+ ['deleteDataset', 'mutation', 13],
+ ['deleteExperiment', 'mutation', 13],
+ ['deleteRun', 'mutation', 13],
+ ['deleteTestCase', 'mutation', 13],
+ ['getBenchmark', 'query', 12],
+ ['getDataset', 'query', 12],
+ ['getExperiment', 'query', 12],
+ ['getResumableCases', 'query', 12],
+ ['getRunDetails', 'query', 12],
+ ['getRunProgress', 'query', 12],
+ ['getRunResults', 'query', 12],
+ ['getTestCase', 'query', 12],
+ ['importDataset', 'mutation', 13],
+ ['listBenchmarks', 'query', 12],
+ ['listDatasets', 'query', 12],
+ ['listExperiments', 'query', 11],
+ ['listRuns', 'query', 12],
+ ['listTestCases', 'query', 12],
+ ['parseDatasetFile', 'mutation', 13],
+ ['resumeRunCase', 'mutation', 13],
+ ['retryRunCase', 'mutation', 13],
+ ['retryRunErrors', 'mutation', 13],
+ ['startRun', 'mutation', 13],
+ ['updateBenchmark', 'mutation', 13],
+ ['updateDataset', 'mutation', 13],
+ ['updateExperiment', 'mutation', 13],
+ ['updateRun', 'mutation', 13],
+ ['updateRunMetrics', 'mutation', 13],
+ ['updateRunStatus', 'mutation', 13],
+ ['updateTestCase', 'mutation', 13],
+ ];
+}
diff --git a/apps/server/src/routers/lambda/agentEval/index.ts b/apps/server/src/routers/lambda/agentEval/index.ts
new file mode 100644
index 00000000000..13578378dbc
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/index.ts
@@ -0,0 +1,15 @@
+import { mergeRouters } from '@/libs/trpc/lambda';
+
+import { benchmarkRouter } from './benchmarks';
+import { datasetRouter } from './datasets';
+import { experimentRouter } from './experiments';
+import { runRouter } from './runs';
+import { testCaseRouter } from './testCases';
+
+export const agentEvalRouter = mergeRouters(
+ benchmarkRouter,
+ experimentRouter,
+ datasetRouter,
+ testCaseRouter,
+ runRouter,
+);
diff --git a/apps/server/src/routers/lambda/agentEval/procedures.ts b/apps/server/src/routers/lambda/agentEval/procedures.ts
new file mode 100644
index 00000000000..222c5fd6d91
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/procedures.ts
@@ -0,0 +1,38 @@
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import {
+ AgentEvalBenchmarkModel,
+ AgentEvalDatasetModel,
+ AgentEvalExperimentModel,
+ AgentEvalRunModel,
+ AgentEvalRunTopicModel,
+ AgentEvalTestCaseModel,
+} from '@/database/models/agentEval';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+import { FileService } from '@/server/services/file';
+import { FileUploadService } from '@/server/services/fileUpload';
+
+export const agentEvalProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ const wsId = ctx.workspaceId ?? undefined;
+
+ return opts.next({
+ ctx: {
+ benchmarkModel: new AgentEvalBenchmarkModel(ctx.serverDB, ctx.userId, wsId),
+ datasetModel: new AgentEvalDatasetModel(ctx.serverDB, ctx.userId, wsId),
+ experimentModel: new AgentEvalExperimentModel(ctx.serverDB, ctx.userId, wsId),
+ runModel: new AgentEvalRunModel(ctx.serverDB, ctx.userId, wsId),
+ runService: new AgentEvalRunService(ctx.serverDB, ctx.userId, wsId),
+ runTopicModel: new AgentEvalRunTopicModel(ctx.serverDB, ctx.userId, wsId),
+ testCaseModel: new AgentEvalTestCaseModel(ctx.serverDB, ctx.userId, wsId),
+ fileService: new FileService(ctx.serverDB, ctx.userId, wsId),
+ fileUploadService: new FileUploadService(ctx.serverDB, ctx.userId, wsId),
+ },
+ });
+});
+
+// Write variant for mutations — gates viewers out of all eval-creation/edit
+// flows. Reads keep using `agentEvalProcedure` (viewers may inspect existing
+// benchmarks / runs).
+export const agentEvalProcedureWrite = agentEvalProcedure.use(withScopedPermission('agent:update'));
diff --git a/apps/server/src/routers/lambda/agentEval/runs.ts b/apps/server/src/routers/lambda/agentEval/runs.ts
new file mode 100644
index 00000000000..2994fe0f523
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/runs.ts
@@ -0,0 +1,486 @@
+import { TRPCError } from '@trpc/server';
+import debug from 'debug';
+import pMap from 'p-map';
+import { z } from 'zod';
+
+import { router } from '@/libs/trpc/lambda';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';
+
+import { evalRunInputConfigSchema } from '../evalRunConfig.schema';
+import { RUN_ENRICHMENT_CONCURRENCY } from './constants';
+import { agentEvalProcedure, agentEvalProcedureWrite } from './procedures';
+
+const log = debug('lobe-lambda-router:agent-eval');
+
+/** Max trajectories resumed at once by `batchResumeRunCases`. */
+const BATCH_RESUME_CONCURRENCY = 5;
+
+export const runRouter = router({
+ // ============================================
+ // Run Operations
+ // ============================================
+ createRun: agentEvalProcedureWrite
+ .input(
+ z.object({
+ datasetId: z.string(),
+ targetAgentId: z.string().optional(),
+ name: z.string().optional(),
+ config: evalRunInputConfigSchema.optional(),
+ experimentId: z.string().optional(),
+ parentRunId: z.string().optional(),
+ // 'external': create claimable (pending) run with no pre-created topics.
+ mode: z.enum(['internal', 'external']).optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ const result = await ctx.runService.createRun(input);
+ if (!result) {
+ throw new TRPCError({
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'Failed to create run',
+ });
+ }
+ return result;
+ } catch (error: any) {
+ const pgError = error?.cause || error;
+
+ if (pgError?.message === 'Experiment not found') {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Experiment not found' });
+ }
+ if (pgError?.message === 'Parent run not found') {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Parent run not found' });
+ }
+
+ // Check for foreign key violation (dataset not found)
+ if (pgError?.code === '23503' && pgError?.constraint?.includes('dataset')) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Dataset with id "${input.datasetId}" not found`,
+ });
+ }
+ throw error;
+ }
+ }),
+ listRuns: agentEvalProcedure
+ .input(
+ z.object({
+ benchmarkId: z.string().optional(),
+ datasetId: z.string().optional(),
+ experimentId: z.string().optional(),
+ status: z
+ .enum(['idle', 'pending', 'running', 'completed', 'failed', 'aborted', 'external'])
+ .optional(),
+ limit: z.number().min(1).max(100).default(50).optional(),
+ offset: z.number().min(0).default(0).optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ const data = await ctx.runModel.query({
+ benchmarkId: input.benchmarkId,
+ datasetId: input.datasetId,
+ experimentId: input.experimentId,
+ status: input.status,
+ limit: input.limit,
+ offset: input.offset,
+ });
+
+ // Enrich runs with dataset name and agent info
+ const datasetIds = [...new Set(data.map((r) => r.datasetId))];
+ const agentIds = [...new Set(data.map((r) => r.targetAgentId).filter(Boolean))] as string[];
+
+ const [datasets, agents] = await Promise.all([
+ pMap(datasetIds, (id) => ctx.datasetModel.findById(id), {
+ concurrency: RUN_ENRICHMENT_CONCURRENCY,
+ }),
+ pMap(agentIds, (id) => ctx.runService.getAgentDisplayInfo(id), {
+ concurrency: RUN_ENRICHMENT_CONCURRENCY,
+ }),
+ ]);
+
+ const datasetMap = Object.fromEntries(datasets.filter(Boolean).map((d) => [d!.id, d!.name]));
+ const agentMap = Object.fromEntries(agents.filter(Boolean).map((a) => [a!.id, a!]));
+
+ const enriched = data.map((run) => ({
+ ...run,
+ datasetName: datasetMap[run.datasetId] || undefined,
+ targetAgent: run.targetAgentId ? agentMap[run.targetAgentId] : undefined,
+ }));
+
+ const total = data.length;
+
+ return { data: enriched, total };
+ }),
+ getRunDetails: agentEvalProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ ctx, input }) => {
+ const result = await ctx.runService.getRunDetails(input.id);
+ if (!result) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
+ }
+ return result;
+ }),
+ deleteRun: agentEvalProcedureWrite
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ const result = await ctx.runService.deleteRun(input.id);
+ // Check if any rows were affected
+ if (result.rowCount === 0) {
+ return {
+ success: false,
+ error: 'Run not found or you do not have permission to delete it',
+ };
+ }
+ return { success: true };
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to delete run',
+ };
+ }
+ }),
+
+ // ============================================
+ // Run Execution Operations
+ // ============================================
+ /**
+ * Start executing a run
+ * Transitions: idle/failed → pending → running
+ */
+ startRun: agentEvalProcedureWrite
+ .input(
+ z.object({
+ id: z.string(),
+ force: z.boolean().default(false).optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { id: runId, force } = input;
+
+ // Get run to validate ownership and status
+ const run = await ctx.runModel.findById(runId);
+ if (!run) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
+ }
+
+ // Check run status
+ if (run.status === 'running' && !force) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Run is already running. Use force=true to restart.',
+ });
+ }
+
+ // Set status to pending immediately so frontend gets feedback
+ await ctx.runModel.update(runId, { status: 'pending' });
+
+ // Trigger workflow
+ await AgentEvalRunWorkflow.triggerRunBenchmark({ force, runId, userId: ctx.userId });
+
+ return { success: true, runId };
+ }),
+ /**
+ * Abort a running evaluation
+ */
+ abortRun: agentEvalProcedureWrite
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ const run = await ctx.runModel.findById(input.id);
+ if (!run) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
+ }
+
+ if (run.status !== 'running' && run.status !== 'pending') {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Cannot abort run with status: ${run.status}`,
+ });
+ }
+
+ const service = new AgentEvalRunService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ await service.abortRun(input.id);
+
+ return { success: true };
+ }),
+ retryRunErrors: agentEvalProcedureWrite
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ const run = await ctx.runModel.findById(input.id);
+ if (!run) throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
+
+ if (!['completed', 'failed', 'aborted'].includes(run.status)) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Cannot retry: status=${run.status}`,
+ });
+ }
+
+ const { retryCount } = await ctx.runService.retryErrorCases(input.id);
+
+ await AgentEvalRunWorkflow.triggerRunBenchmark({
+ force: true,
+ runId: input.id,
+ userId: ctx.userId,
+ });
+
+ return { retryCount, runId: input.id, success: true };
+ }),
+ retryRunCase: agentEvalProcedureWrite
+ .input(z.object({ runId: z.string(), testCaseId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ const run = await ctx.runModel.findById(input.runId);
+ if (!run) throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
+
+ if (!['completed', 'failed', 'aborted', 'running'].includes(run.status)) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Cannot retry case: run status=${run.status}`,
+ });
+ }
+
+ try {
+ await ctx.runService.retrySingleCase(input.runId, input.testCaseId);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'Cannot retry case';
+ if (message.startsWith('Cannot retry: case is')) {
+ throw new TRPCError({ code: 'CONFLICT', message });
+ }
+ if (message === 'RunTopic not found') {
+ throw new TRPCError({ code: 'NOT_FOUND', message });
+ }
+ throw error;
+ }
+
+ await AgentEvalRunWorkflow.triggerExecuteTestCase({
+ runId: input.runId,
+ testCaseId: input.testCaseId,
+ userId: ctx.userId,
+ });
+
+ return { runId: input.runId, success: true, testCaseId: input.testCaseId };
+ }),
+ resumeRunCase: agentEvalProcedureWrite
+ .input(z.object({ runId: z.string(), testCaseId: z.string(), threadId: z.string().optional() }))
+ .mutation(async ({ input, ctx }) => {
+ log(
+ 'resumeRunCase: runId=%s testCaseId=%s threadId=%s',
+ input.runId,
+ input.testCaseId,
+ input.threadId,
+ );
+ const result = await ctx.runService.resumeTrajectory({
+ runId: input.runId,
+ testCaseId: input.testCaseId,
+ threadId: input.threadId,
+ });
+ log('resumeRunCase: result %O', result);
+ return result;
+ }),
+ batchResumeRunCases: agentEvalProcedureWrite
+ .input(
+ z.object({
+ runId: z.string(),
+ targets: z.array(z.object({ testCaseId: z.string(), threadId: z.string().optional() })),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ log('batchResumeRunCases: runId=%s count=%d', input.runId, input.targets.length);
+ // Each resume settles independently (like `Promise.allSettled`): one
+ // failed target must not abort the others.
+ const results = await pMap(
+ input.targets,
+ async (target) => {
+ try {
+ await ctx.runService.resumeTrajectory({
+ runId: input.runId,
+ testCaseId: target.testCaseId,
+ threadId: target.threadId,
+ });
+ return true;
+ } catch {
+ return false;
+ }
+ },
+ { concurrency: BATCH_RESUME_CONCURRENCY },
+ );
+ const succeeded = results.filter(Boolean).length;
+ const failed = results.length - succeeded;
+ log('batchResumeRunCases: succeeded=%d failed=%d', succeeded, failed);
+ return { failed, succeeded, total: input.targets.length };
+ }),
+ getResumableCases: agentEvalProcedure
+ .input(z.object({ runId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ log('getResumableCases: runId=%s', input.runId);
+ return ctx.runService.getResumableCases(input.runId);
+ }),
+ /**
+ * Get real-time progress of a running evaluation
+ */
+ getRunProgress: agentEvalProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ input, ctx }) => {
+ let run = await ctx.runModel.findById(input.id);
+ if (!run) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
+ }
+
+ // Check if a 'running' run has timed out
+ if (run.status === 'running') {
+ const timedOut = await ctx.runService.checkAndHandleRunTimeout(run);
+ if (timedOut) {
+ run = (await ctx.runModel.findById(input.id))!;
+ }
+ }
+
+ return {
+ status: run.status,
+ metrics: run.metrics,
+ startedAt: run.startedAt,
+ updatedAt: run.updatedAt,
+ };
+ }),
+ /**
+ * Get detailed results of test case executions
+ */
+ getRunResults: agentEvalProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ const run = await ctx.runModel.findById(input.id);
+ if (!run) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
+ }
+
+ // Get all run topics with test cases and topics
+ const allRunTopics = await ctx.runTopicModel.findByRunId(input.id);
+
+ return {
+ runId: input.id,
+ total: allRunTopics.length,
+ results: allRunTopics.map((rt) => ({
+ createdAt: rt.createdAt,
+ evalResult: rt.evalResult,
+ passed: rt.passed,
+ score: rt.score,
+ status: rt.status,
+ testCase: rt.testCase,
+ testCaseId: rt.testCaseId,
+ topic: rt.topic,
+ topicId: rt.topicId,
+ })),
+ };
+ }),
+ /**
+ * Update run status (internal use)
+ */
+ updateRunStatus: agentEvalProcedureWrite
+ .input(
+ z.object({
+ id: z.string(),
+ status: z.enum([
+ 'idle',
+ 'pending',
+ 'running',
+ 'completed',
+ 'failed',
+ 'aborted',
+ 'external',
+ ]),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { id, status } = input;
+
+ const run = await ctx.runModel.findById(id);
+ if (!run) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
+ }
+
+ const result = await ctx.runModel.update(id, { status });
+ return result;
+ }),
+ /**
+ * Update run metrics (internal use)
+ */
+ updateRunMetrics: agentEvalProcedureWrite
+ .input(
+ z.object({
+ id: z.string(),
+ metrics: z.object({
+ totalCases: z.number(),
+ passedCases: z.number(),
+ failedCases: z.number(),
+ averageScore: z.number(),
+ passRate: z.number(),
+ duration: z.number().optional(),
+ rubricScores: z.record(z.string(), z.number()).optional(),
+ }),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { id, metrics } = input;
+
+ const run = await ctx.runModel.findById(id);
+ if (!run) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
+ }
+
+ const result = await ctx.runModel.update(id, { metrics });
+ return result;
+ }),
+ /**
+ * Update run (user-facing: name, datasetId, targetAgentId)
+ */
+ updateRun: agentEvalProcedureWrite
+ .input(
+ z.object({
+ config: evalRunInputConfigSchema.optional(),
+ datasetId: z.string().optional(),
+ id: z.string(),
+ name: z.string().optional(),
+ targetAgentId: z.string().nullish(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { id, ...updates } = input;
+
+ const run = await ctx.runModel.findById(id);
+ if (!run) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
+ }
+
+ // Only allow changing dataset/agent when run hasn't started
+ const canChangeConfig = run.status === 'idle';
+ const value: Record<string, any> = {};
+
+ if (updates.name !== undefined) value.name = updates.name;
+ if (canChangeConfig && updates.datasetId !== undefined) value.datasetId = updates.datasetId;
+ if (canChangeConfig && updates.targetAgentId !== undefined)
+ value.targetAgentId = updates.targetAgentId;
+
+ // Config fields can be updated anytime (except when completed)
+ if (updates.config) {
+ const existingConfig = (run.config as Record<string, unknown>) ?? {};
+ const configPatch = Object.fromEntries(
+ Object.entries(updates.config).filter(([, v]) => v !== undefined),
+ );
+ if (Object.keys(configPatch).length > 0) {
+ value.config = { ...existingConfig, ...configPatch };
+ }
+ }
+
+ if (Object.keys(value).length === 0) return run;
+
+ return ctx.runModel.update(id, value);
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agentEval/schemas.ts b/apps/server/src/routers/lambda/agentEval/schemas.ts
new file mode 100644
index 00000000000..2e6008731c4
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/schemas.ts
@@ -0,0 +1,109 @@
+import { z } from 'zod';
+
+export const rubricTypeSchema = z.enum([
+ 'equals',
+ 'contains',
+ 'regex',
+ 'starts-with',
+ 'ends-with',
+ 'any-of',
+ 'numeric',
+ 'extract-match',
+ 'json-schema',
+ 'javascript',
+ 'python',
+ 'llm-rubric',
+ 'factuality',
+ 'answer-relevance',
+ 'similar',
+ 'levenshtein',
+ 'rubric',
+ 'external',
+]);
+
+export const evalConfigSchema = z.object({ judgePrompt: z.string().optional() }).passthrough();
+
+export const evalCaseEnvironmentSchema = z
+ .object({
+ envPrompt: z.string().optional(),
+ toolForwarding: z
+ .record(
+ z.string().trim().min(1),
+ z
+ .object({
+ endpoint: z.string().url(),
+ timeoutMs: z.number().int().positive().optional(),
+ })
+ .strict(),
+ )
+ .optional(),
+ })
+ .strict();
+
+const dateValueSchema = z.union([
+ z.number().finite(),
+ z.string().refine((value) => !Number.isNaN(Date.parse(value)), 'Invalid timestamp'),
+]);
+
+const recordSchema = z.record(z.string(), z.unknown());
+
+export const evalTestCaseMessagesSchema = z
+ .array(
+ z
+ .object({
+ content: z.string(),
+ createdAt: dateValueSchema.optional(),
+ error: recordSchema.optional(),
+ id: z.string().min(1).optional(),
+ metadata: recordSchema.optional(),
+ model: z.string().optional(),
+ parentId: z.string().min(1).nullable().optional(),
+ plugin: recordSchema.optional(),
+ pluginError: recordSchema.optional(),
+ pluginIntervention: recordSchema.optional(),
+ pluginState: recordSchema.optional(),
+ provider: z.string().optional(),
+ reasoning: recordSchema.optional(),
+ role: z.enum(['user', 'assistant', 'system', 'tool']),
+ search: recordSchema.optional(),
+ tool_call_id: z.string().optional(),
+ tools: z.array(recordSchema).optional(),
+ traceId: z.string().optional(),
+ updatedAt: dateValueSchema.optional(),
+ })
+ .strict(),
+ )
+ .superRefine((messages, ctx) => {
+ const ids = new Set<string>();
+
+ for (const [index, message] of messages.entries()) {
+ if (!message.id) continue;
+ if (ids.has(message.id)) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'Message ids must be unique',
+ path: [index, 'id'],
+ });
+ }
+ ids.add(message.id);
+ }
+
+ for (const [index, message] of messages.entries()) {
+ if (message.parentId && !ids.has(message.parentId)) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'Message parentId must reference a message in the same sequence',
+ path: [index, 'parentId'],
+ });
+ }
+ }
+ });
+
+export const evalTestCaseContentSchema = z.object({
+ category: z.string().optional(),
+ choices: z.array(z.string()).optional(),
+ environment: evalCaseEnvironmentSchema.optional(),
+ expected: z.string().optional(),
+ input: z.string(),
+ messages: evalTestCaseMessagesSchema.optional(),
+});
diff --git a/apps/server/src/routers/lambda/agentEval/testCases.ts b/apps/server/src/routers/lambda/agentEval/testCases.ts
new file mode 100644
index 00000000000..8c2c06743e0
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/testCases.ts
@@ -0,0 +1,164 @@
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { router } from '@/libs/trpc/lambda';
+
+import { agentEvalProcedure, agentEvalProcedureWrite } from './procedures';
+import {
+ evalCaseEnvironmentSchema,
+ evalConfigSchema,
+ evalTestCaseContentSchema,
+ evalTestCaseMessagesSchema,
+ rubricTypeSchema,
+} from './schemas';
+
+export const testCaseRouter = router({
+ // ============================================
+ // TestCase Operations
+ // ============================================
+ createTestCase: agentEvalProcedureWrite
+ .input(
+ z.object({
+ datasetId: z.string(),
+ content: evalTestCaseContentSchema,
+ evalMode: rubricTypeSchema.optional(),
+ evalConfig: evalConfigSchema.optional(),
+ metadata: z.record(z.string(), z.unknown()).optional(),
+ sortOrder: z.number().optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ const result = await ctx.testCaseModel.create(input);
+ if (!result) {
+ throw new TRPCError({
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'Failed to create test case',
+ });
+ }
+ return result;
+ } catch (error: any) {
+ // PostgreSQL errors might be in error.cause
+ const pgError = error?.cause || error;
+
+ // Check for foreign key violation (dataset not found)
+ if (pgError?.code === '23503' && pgError?.constraint?.includes('dataset')) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Dataset with id "${input.datasetId}" not found`,
+ });
+ }
+ throw error;
+ }
+ }),
+ batchCreateTestCases: agentEvalProcedureWrite
+ .input(
+ z.object({
+ datasetId: z.string(),
+ cases: z.array(
+ z.object({
+ content: evalTestCaseContentSchema,
+ metadata: z.record(z.string(), z.unknown()).optional(),
+ sortOrder: z.number().optional(),
+ }),
+ ),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ const testCases = input.cases.map((c) => ({
+ ...c,
+ datasetId: input.datasetId,
+ }));
+ const result = await ctx.testCaseModel.batchCreate(testCases);
+ return { count: result.length, data: result };
+ } catch (error: any) {
+ // PostgreSQL errors might be in error.cause
+ const pgError = error?.cause || error;
+
+ // Check for foreign key violation (dataset not found)
+ if (pgError?.code === '23503' && pgError?.constraint?.includes('dataset')) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Dataset with id "${input.datasetId}" not found`,
+ });
+ }
+ throw error;
+ }
+ }),
+ updateTestCase: agentEvalProcedureWrite
+ .input(
+ z.object({
+ id: z.string(),
+ content: z
+ .object({
+ input: z.string().optional(),
+ expected: z.string().optional(),
+ choices: z.array(z.string()).optional(),
+ category: z.string().optional(),
+ environment: evalCaseEnvironmentSchema.optional(),
+ messages: evalTestCaseMessagesSchema.optional(),
+ })
+ .optional(),
+ evalMode: rubricTypeSchema.nullish(),
+ evalConfig: evalConfigSchema.nullish(),
+ metadata: z.record(z.string(), z.unknown()).optional(),
+ sortOrder: z.number().optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { id, ...data } = input;
+ const result = await ctx.testCaseModel.update(id, data as any);
+ if (!result) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: 'Test case not found',
+ });
+ }
+ return result;
+ }),
+ deleteTestCase: agentEvalProcedureWrite
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ const result = await ctx.testCaseModel.delete(input.id);
+ // Check if any rows were affected
+ if (result.rowCount === 0) {
+ return {
+ success: false,
+ error: 'Test case not found',
+ };
+ }
+ return { success: true };
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Failed to delete test case',
+ };
+ }
+ }),
+ getTestCase: agentEvalProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ ctx, input }) => {
+ const testCase = await ctx.testCaseModel.findById(input.id);
+ if (!testCase) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Test case not found' });
+ }
+ return testCase;
+ }),
+ listTestCases: agentEvalProcedure
+ .input(
+ z.object({
+ datasetId: z.string(),
+ limit: z.number().min(1).max(100).default(50).optional(),
+ offset: z.number().min(0).default(0).optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ const [data, total] = await Promise.all([
+ ctx.testCaseModel.findByDatasetId(input.datasetId, input.limit, input.offset),
+ ctx.testCaseModel.countByDatasetId(input.datasetId),
+ ]);
+ return { data, total };
+ }),
+});