π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(agent-eval): split the 2537-line agent eval run service into cohesive modules (#21142)
Arvin Xu1f0ca61914ce
diff --git a/apps/server/src/services/agentEvalRun/__tests__/multiThreadTrigger.test.ts b/apps/server/src/services/agentEvalRun/__tests__/multiThreadTrigger.test.tsnew file mode 100644index 00000000000..b750af772b4--- /dev/null+++ b/apps/server/src/services/agentEvalRun/__tests__/multiThreadTrigger.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it, vi } from 'vitest';++import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';++import { executeMultiThreadTrajectory } from '../thread';+import type { EvalRunDeps } from '../types';++vi.mock('@/server/workflows/agentEvalRun', () => ({+ AgentEvalRunWorkflow: { triggerRunThreadTrajectory: vi.fn() },+}));++vi.mock('@/server/services/aiAgent', () => ({ AiAgentService: vi.fn() }));++const createDeps = () => {+ let next = 0;+ return {+ runTopicModel: {+ findByRunAndTestCase: vi.fn().mockResolvedValue({ evalResult: null, topicId: 'topic-1' }),+ updateByRunAndTopic: vi.fn().mockResolvedValue(undefined),+ },+ threadModel: { create: vi.fn().mockImplementation(async () => ({ id: `thread-${next++}` })) },+ topicModel: { findById: vi.fn().mockResolvedValue({ metadata: {} }) },+ userId: 'user-1',+ };+};++describe('executeMultiThreadTrajectory', () => {+ it('attempts every pass@k trigger even when an early dispatch fails', async () => {+ const k = 8;+ const deps = createDeps();+ const failure = new Error('qstash down');+ const trigger = vi.mocked(AgentEvalRunWorkflow.triggerRunThreadTrajectory);+ trigger.mockReset();+ trigger.mockImplementation(async ({ threadId }) => {+ if (threadId === 'thread-0') throw failure;+ return undefined as any;+ });++ await expect(+ executeMultiThreadTrajectory(deps as unknown as EvalRunDeps, {+ k,+ run: { datasetId: 'dataset-1' },+ runId: 'run-1',+ testCaseId: 'case-1',+ }),+ ).rejects.toBe(failure);++ expect(trigger).toHaveBeenCalledTimes(k);+ expect(new Set(trigger.mock.calls.map(([params]) => params.threadId)).size).toBe(k);+ });+});diff --git a/apps/server/src/services/agentEvalRun/completion.ts b/apps/server/src/services/agentEvalRun/completion.tsnew file mode 100644index 00000000000..72bae7fa8ed--- /dev/null+++ b/apps/server/src/services/agentEvalRun/completion.ts@@ -0,0 +1,276 @@+import { evaluate } from '@lobechat/eval-rubric';+import type {+ EvalBenchmarkRubric,+ EvalRunMetrics,+ EvalRunTopicResult,+ RubricType,+} from '@lobechat/types';++import type { EvalRunDeps } from './types';+import { roundCost } from './utils';++export async function recordTrajectoryCompletion(+ deps: EvalRunDeps,+ params: {+ runId: string;+ status?: string;+ telemetry: {+ completionReason?: string;+ cost?: number;+ duration?: number;+ errorDetail?: unknown;+ errorMessage?: string;+ llmCalls?: number;+ steps?: number;+ toolCalls?: number;+ totalTokens?: number;+ };+ testCaseId: string;+ },+): Promise<{ allDone: boolean; completedCount: number }> {+ const { runId, testCaseId, telemetry, status } = params;++ // Write runtime telemetry to RunTopic+ const runTopic = await deps.runTopicModel.findByRunAndTestCase(runId, testCaseId);+ if (runTopic) {+ // Skip if topic is already in a terminal state (e.g. timeout marked by checkAndHandleRunTimeout).+ // The interrupted agent still fires the completion webhook, but we must not overwrite the result.+ const terminalStates = ['passed', 'failed', 'error', 'timeout', 'external'];+ if (runTopic.status && terminalStates.includes(runTopic.status)) {+ // Fall through to progress tracking below without modifying this topic+ } else {+ // Build merged evalResult with telemetry data β use this as base for all subsequent writes+ const evalResultWithTelemetry: EvalRunTopicResult = {+ ...runTopic.evalResult,+ completionReason: telemetry.completionReason,+ cost: telemetry.cost != null ? roundCost(telemetry.cost) : undefined,+ duration: telemetry.duration,+ llmCalls: telemetry.llmCalls,+ rubricScores: runTopic.evalResult?.rubricScores,+ steps: telemetry.steps,+ tokens: telemetry.totalTokens,+ toolCalls: telemetry.toolCalls,+ };++ await deps.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {+ evalResult: evalResultWithTelemetry,+ });++ if (status === 'error') {+ // Short-circuit: execution error β skip evaluation, write error directly+ await deps.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {+ evalResult: {+ ...evalResultWithTelemetry,+ error:+ telemetry.errorMessage ||+ `Execution error: ${telemetry.completionReason || 'unknown'}`,+ errorDetail: telemetry.errorDetail,+ },+ passed: false,+ score: 0,+ status: 'error',+ });+ } else {+ // Per-case evaluation: immediately evaluate this case against rubrics+ try {+ await evaluateCase(deps, runId, { ...runTopic, evalResult: evalResultWithTelemetry });+ } catch (e) {+ // Evaluation failure should not block telemetry or progress tracking+ console.error(e);+ }+ }+ }+ }++ // Get run to read totalCases+ const run = await deps.runModel.findById(runId);+ if (!run) return { allDone: false, completedCount: 0 };++ const totalCases = run.metrics?.totalCases;+ if (!totalCases) return { allDone: false, completedCount: 0 };++ // Aggregate real-time metrics from all RunTopics+ const allTopics = await deps.runTopicModel.findByRunId(runId);+ const completedCount = allTopics.filter(+ (t) =>+ (t.evalResult && 'completionReason' in t.evalResult) ||+ t.status === 'timeout' ||+ t.status === 'external',+ ).length;+ const passedCases = allTopics.filter((t) => t.status === 'passed').length;+ const failedCases = allTopics.filter((t) => t.status === 'failed').length;+ const errorCases = allTopics.filter((t) => t.status === 'error').length;+ const externalCasesTraj = allTopics.filter((t) => t.status === 'external').length;+ const timeoutCases = allTopics.filter((t) => t.status === 'timeout').length;++ let sumCost = 0;+ let sumTokens = 0;+ let sumSteps = 0;+ let sumLlmCalls = 0;+ let sumToolCalls = 0;+ let actualTotalCost = 0;+ let actualTotalTokens = 0;+ let actualTotalDuration = 0;+ for (const t of allTopics) {+ const r = t.evalResult as Record<string, unknown> | null;+ if (r && ('completionReason' in r || t.status === 'timeout')) {+ if (typeof r.cost === 'number') sumCost += r.cost;+ if (typeof r.tokens === 'number') sumTokens += r.tokens;+ if (typeof r.steps === 'number') sumSteps += r.steps;+ if (typeof r.llmCalls === 'number') sumLlmCalls += r.llmCalls;+ if (typeof r.toolCalls === 'number') sumToolCalls += r.toolCalls;+ const rTotalCost =+ typeof r.totalCost === 'number' ? r.totalCost : typeof r.cost === 'number' ? r.cost : 0;+ const rTotalTokens =+ typeof r.totalTokens === 'number'+ ? r.totalTokens+ : typeof r.tokens === 'number'+ ? r.tokens+ : 0;+ const rTotalDuration =+ typeof r.totalDuration === 'number'+ ? r.totalDuration+ : typeof r.duration === 'number'+ ? r.duration+ : 0;+ actualTotalCost += rTotalCost;+ actualTotalTokens += rTotalTokens;+ actualTotalDuration += rTotalDuration;+ }+ }++ // Update run metrics with real-time counts+ await deps.runModel.update(runId, {+ metrics: {+ ...(run.metrics as EvalRunMetrics),+ completedCases: completedCount,+ cost: sumCost ? roundCost(sumCost) : undefined,+ errorCases,+ externalCases: externalCasesTraj || undefined,+ failedCases,+ llmCalls: sumLlmCalls || undefined,+ passedCases,+ perCaseCost: sumCost && completedCount ? roundCost(sumCost / completedCount) : undefined,+ perCaseLlmCalls:+ sumLlmCalls && completedCount+ ? Math.round((sumLlmCalls / completedCount) * 10) / 10+ : undefined,+ perCaseSteps:+ sumSteps && completedCount ? Math.round((sumSteps / completedCount) * 10) / 10 : undefined,+ perCaseTokens:+ sumTokens && completedCount ? Math.round(sumTokens / completedCount) : undefined,+ perCaseToolCalls:+ sumToolCalls && completedCount+ ? Math.round((sumToolCalls / completedCount) * 10) / 10+ : undefined,+ steps: sumSteps || undefined,+ timeoutCases,+ tokens: sumTokens || undefined,+ toolCalls: sumToolCalls || undefined,+ totalCost: actualTotalCost ? roundCost(actualTotalCost) : undefined,+ totalDuration: actualTotalDuration || undefined,+ totalTokens: actualTotalTokens || undefined,+ },+ });++ return { allDone: completedCount >= totalCases, completedCount };+}++async function evaluateCase(+ deps: EvalRunDeps,+ runId: string,+ runTopic: {+ evalResult?: EvalRunTopicResult | null;+ runId: string;+ testCase?: { content?: any; evalConfig?: any; evalMode?: string | null } | null;+ topicId: string;+ },+) {+ // Resolve eval context: run β dataset β benchmark+ const run = await deps.runModel.findById(runId);+ if (!run) return;++ const dataset = await deps.datasetModel.findById(run.datasetId);+ if (!dataset) return;++ const benchmark = dataset.benchmarkId+ ? await deps.benchmarkModel.findById(dataset.benchmarkId)+ : null;++ const passThreshold = (run.config?.passThreshold as number) ?? 0.6;+ const benchmarkRubrics = benchmark?.rubrics ?? [];++ // Get messages for this topic+ const messages = await deps.messageModel.query({ topicId: runTopic.topicId });+ const assistantMessages = messages.filter((m: { role: string }) => m.role === 'assistant');+ const lastAssistantMsg = assistantMessages.at(-1);++ const existingResult = runTopic.evalResult;++ if (!lastAssistantMsg || !lastAssistantMsg.content) {+ await deps.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {+ evalResult: { ...existingResult, error: 'No assistant output', rubricScores: [] },+ passed: false,+ score: 0,+ status: 'error',+ });+ return;+ }++ const testCase = runTopic.testCase;+ if (!testCase) return;++ // Resolve rubrics: TestCase evalMode > Dataset evalMode > Benchmark rubrics+ const evalMode = (testCase.evalMode ?? dataset.evalMode) as RubricType | null | undefined;+ const evalConfig = testCase.evalConfig ?? dataset.evalConfig;++ // ββ External eval mode: agent finished, hand off to external scorer ββ+ if (evalMode === 'external') {+ await deps.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {+ evalResult: { ...existingResult, awaitingExternalEval: true },+ status: 'external',+ });+ return;+ }++ let effectiveRubrics: EvalBenchmarkRubric[];+ if (evalMode) {+ effectiveRubrics = [+ {+ config: (evalConfig ?? {}) as unknown as EvalBenchmarkRubric['config'],+ id: `eval-mode-${evalMode}`,+ name: evalMode,+ type: evalMode,+ weight: 1,+ },+ ];+ } else {+ effectiveRubrics = benchmarkRubrics ?? [];+ }++ // No rubrics to evaluate against β skip evaluation entirely+ if (effectiveRubrics.length === 0) return;++ // Run evaluation+ const result = await evaluate(+ { actual: lastAssistantMsg.content, rubrics: effectiveRubrics, testCase: testCase.content },+ { passThreshold },+ );++ const evalResult: EvalRunTopicResult = {+ ...existingResult,+ rubricScores: result.rubricResults.map((r) => ({+ reason: r.reason,+ rubricId: r.rubricId,+ score: r.score,+ })),+ };++ // Write results to RunTopic+ await deps.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {+ evalResult,+ passed: result.passed,+ score: result.score,+ status: result.passed ? 'passed' : 'failed',+ });+}diff --git a/apps/server/src/services/agentEvalRun/constants.ts b/apps/server/src/services/agentEvalRun/constants.tsnew file mode 100644index 00000000000..a6fa23038e7--- /dev/null+++ b/apps/server/src/services/agentEvalRun/constants.ts@@ -0,0 +1,5 @@+export const EVAL_AGENT_RUNTIME_QSTASH_RETRIES = 5;+export const EVAL_AGENT_RUNTIME_QSTASH_RETRY_DELAY = '10000 * (1 + retried)';+export const EVAL_HISTORY_TAIL_METADATA_KEY = 'evalHistoryTailMessageId';+/** Caps concurrent pass@k run-thread-trajectory workflow triggers per topic. */+export const THREAD_TRIGGER_CONCURRENCY = 5;diff --git a/apps/server/src/services/agentEvalRun/createRun.ts b/apps/server/src/services/agentEvalRun/createRun.tsnew file mode 100644index 00000000000..ac8f5d94fb8--- /dev/null+++ b/apps/server/src/services/agentEvalRun/createRun.ts@@ -0,0 +1,379 @@+import { idGenerator } from '@lobechat/database';+import type {+ EvalRunAgentSnapshot,+ EvalRunInputConfig,+ ImportedMessage,+ ToolIntervention,+} from '@lobechat/types';+import { getActivePluginIds } from '@lobechat/types';+import { clampToolIdentifier } from '@lobechat/utils/clampToolIdentifier';+import { eq, inArray, sql } from 'drizzle-orm';++import { agentEvalRunTopics, messagePlugins, messages, topics } from '@/database/schemas';++import { EVAL_HISTORY_TAIL_METADATA_KEY } from './constants';+import type { EvalRunDeps } from './types';++const EVAL_HISTORY_MESSAGE_BATCH_SIZE = 500;++/** Thrown when a caller-supplied run id exists with non-equivalent create params. */+export const RUN_CREATE_ID_CONFLICT = 'Run id already exists with different create parameters';++/** Stable JSON stringify: sorts object keys recursively, drops undefined. */+const stableStringify = (value: unknown): string => {+ if (value === undefined) return '';+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? '';+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;+ const entries = Object.entries(value as Record<string, unknown>)+ .filter(([, v]) => v !== undefined)+ .sort(([a], [b]) => (a < b ? -1 : 1))+ .map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`);+ return `{${entries.join(',')}}`;+};++export async function createRun(+ deps: EvalRunDeps,+ params: {+ config?: EvalRunInputConfig;+ datasetId: string;+ experimentId?: string;+ /**+ * Caller-supplied run id for idempotent cross-server creation. When a run+ * with this id already exists: equivalent immutable create params β the+ * existing run is returned; otherwise a conflict error is thrown.+ */+ id?: string;+ /**+ * 'internal' (default): pre-create Topics/RunTopics for every test case and+ * leave the run `idle` until `startRun` triggers the QStash workflow.+ * 'external': create no Topics/RunTopics and set the run `pending` so an+ * external worker can claim it; no workflow is triggered.+ */+ mode?: 'external' | 'internal';+ name?: string;+ parentRunId?: string;+ targetAgentId?: string;+ },+) {+ let { datasetId, targetAgentId } = params;+ let inputConfig = params.config;+ const isExternal = params.mode === 'external';++ // Fork: inherit target agent / dataset / config from the parent run.+ // These are immutable on a fork β reject any override attempt.+ if (params.parentRunId) {+ const parent = await deps.runModel.findById(params.parentRunId);+ if (!parent) throw new Error('Parent run not found');++ if (+ (params.targetAgentId && params.targetAgentId !== parent.targetAgentId) ||+ (params.config && Object.keys(params.config).length > 0) ||+ (params.datasetId && params.datasetId !== parent.datasetId)+ ) {+ throw new Error('Cannot override target agent, config, or dataset when forking a run');+ }++ targetAgentId = parent.targetAgentId ?? undefined;+ datasetId = parent.datasetId;+ inputConfig = (parent.config as EvalRunInputConfig | undefined) ?? undefined;+ }++ // External execution is driven case-by-case through `runExecuteCase`, which+ // only supports single-thread (k=1) runs today. Check after fork resolution+ // so inherited configs are covered too.+ if (isExternal && ((inputConfig as { k?: number } | undefined)?.k ?? 1) > 1) {+ throw new Error('External runs only support k=1 (pass@k is not supported yet)');+ }++ // Validate the experiment scope (and bump its recency once the run exists).+ if (params.experimentId) {+ const experiment = await deps.experimentModel.findById(params.experimentId);+ if (!experiment) throw new Error('Experiment not found');+ }++ // Re-snapshot the current agent config (forks capture the *current* state).+ const agentSnapshot = targetAgentId ? await snapshotAgentConfig(deps, targetAgentId) : undefined;++ // Persist the execution mode as an immutable snapshot: a run's mode cannot+ // be inferred from status once the run reaches a terminal state, and the+ // idempotency check below must compare it.+ const executionMode = isExternal ? ('external' as const) : ('internal' as const);+ const config = { ...inputConfig, agentSnapshot, executionMode };++ // Idempotent create: a caller-supplied id that already exists returns the+ // existing run when the immutable create params are equivalent (datasetId /+ // experimentId / parentRunId / targetAgentId / executionMode / input config+ // β the agent snapshot is excluded since it is re-captured server-side on+ // every create).+ const matchesExisting = (existing: {+ config?: unknown;+ datasetId: string;+ experimentId?: string | null;+ parentRunId?: string | null;+ targetAgentId?: string | null;+ }) => {+ const {+ agentSnapshot: _existingSnapshot,+ executionMode: existingMode,+ ...existingConfig+ } = (existing.config ?? {}) as Record<string, unknown>;+ return (+ existing.datasetId === datasetId &&+ (existing.experimentId ?? null) === (params.experimentId ?? null) &&+ (existing.parentRunId ?? null) === (params.parentRunId ?? null) &&+ (existing.targetAgentId ?? null) === (targetAgentId ?? null) &&+ existingMode === executionMode &&+ stableStringify(existingConfig) === stableStringify(inputConfig ?? {})+ );+ };++ if (params.id) {+ const existing = await deps.runModel.findById(params.id);+ if (existing) {+ if (!matchesExisting(existing)) throw new Error(RUN_CREATE_ID_CONFLICT);+ return existing;+ }+ }++ const { mode: _mode, ...restParams } = params;+ let run;+ try {+ run = await deps.runModel.create({+ ...restParams,+ datasetId,+ targetAgentId,+ config,+ // External runs start claimable; internal runs wait for `startRun`.+ status: isExternal ? 'pending' : 'idle',+ });+ } catch (error) {+ // Race-safe idempotency: a concurrent create with the same caller id won+ // β return the winner when params are equivalent, else conflict.+ const databaseError = error as { code?: string; cause?: { code?: string } };+ if (params.id && (databaseError?.code ?? databaseError?.cause?.code) === '23505') {+ const existing = await deps.runModel.findById(params.id);+ if (existing) {+ if (!matchesExisting(existing)) throw new Error(RUN_CREATE_ID_CONFLICT, { cause: error });+ return existing;+ }+ throw new Error(RUN_CREATE_ID_CONFLICT, { cause: error });+ }+ throw error;+ }++ if (params.experimentId) {+ await deps.experimentModel.touch(params.experimentId);+ }++ // External runs create Topics/RunTopics on demand (per executed case).+ if (isExternal) return run;++ // Pre-create Topics and RunTopics for all test cases (status='pending')+ const testCases = await deps.testCaseModel.findByDatasetId(datasetId);++ if (testCases.length > 0) {+ await createRunTopics(deps, run.id, targetAgentId, testCases);+ }++ return run;+}++export function createRunTopics(+ deps: EvalRunDeps,+ runId: string,+ targetAgentId: string | null | undefined,+ testCases: Array<{+ content: { input: string; messages?: ImportedMessage[] };+ id: string;+ sortOrder: number | null;+ }>,+) {+ return deps.db.transaction(async (tx) => {+ const preparedCases = testCases.map((testCase) => ({+ testCase,+ topicId: idGenerator('topics'),+ }));++ await tx.insert(topics).values(+ preparedCases.map(({ testCase, topicId }) => ({+ agentId: targetAgentId ?? null,+ id: topicId,+ title: `[${(testCase.sortOrder ?? 0) + 1}] ${testCase.content.input.slice(0, 50) || 'Topic'}...`,+ trigger: 'eval' as const,+ userId: deps.userId,+ workspaceId: deps.workspaceId ?? null,+ })),+ );++ for (const { testCase, topicId } of preparedCases) {+ const history = testCase.content.messages?.filter((message) => message.role !== 'system');+ if (!history?.length) continue;++ const idMapping = new Map<string, string>();+ const hasParentInfo = history.some((message) => message.parentId != null);+ const now = Date.now();+ let previousCreatedAt = Number.NEGATIVE_INFINITY;+ const preparedMessages = history.map((message, index) => {+ const id = idGenerator('messages');+ if (message.id) idMapping.set(message.id, id);++ const timestamp =+ message.createdAt === undefined+ ? now + index+ : typeof message.createdAt === 'number'+ ? message.createdAt+ : Date.parse(message.createdAt);+ const createdAt = Math.max(+ Number.isNaN(timestamp) ? now + index : timestamp,+ previousCreatedAt + 1,+ );+ previousCreatedAt = createdAt;++ const updatedTimestamp =+ message.updatedAt === undefined+ ? createdAt+ : typeof message.updatedAt === 'number'+ ? message.updatedAt+ : Date.parse(message.updatedAt);++ return {+ createdAt,+ id,+ message,+ updatedAt: Math.max(+ Number.isNaN(updatedTimestamp) ? createdAt : updatedTimestamp,+ createdAt,+ ),+ };+ });++ const messageRows = preparedMessages.map(({ createdAt, id, message, updatedAt }, index) => ({+ agentId: null,+ content: message.content,+ createdAt: new Date(createdAt),+ error: message.error ?? null,+ id,+ metadata: message.metadata ?? null,+ model: message.model ?? null,+ parentId: null,+ provider: message.provider ?? null,+ reasoning: message.reasoning ?? null,+ role: message.role,+ search: message.search ?? null,+ tools: message.tools ?? null,+ topicId,+ traceId: message.traceId ?? null,+ updatedAt: new Date(updatedAt),+ userId: deps.userId,+ workspaceId: deps.workspaceId ?? null,+ }));+ const pluginRows = preparedMessages.flatMap(({ id, message }) => {+ if (+ !message.plugin &&+ !message.pluginError &&+ !message.pluginIntervention &&+ !message.pluginState &&+ !message.tool_call_id+ ) {+ return [];+ }++ return [+ {+ apiName: clampToolIdentifier(message.plugin?.apiName) ?? null,+ arguments: message.plugin?.arguments ?? null,+ error: message.pluginError ?? null,+ id,+ identifier: clampToolIdentifier(message.plugin?.identifier) ?? null,+ intervention: message.pluginIntervention as ToolIntervention | undefined,+ state: message.pluginState ?? null,+ toolCallId: message.tool_call_id ?? null,+ type: message.plugin?.type ?? null,+ userId: deps.userId,+ workspaceId: deps.workspaceId ?? null,+ },+ ];+ });++ for (let index = 0; index < messageRows.length; index += EVAL_HISTORY_MESSAGE_BATCH_SIZE) {+ await tx+ .insert(messages)+ .values(messageRows.slice(index, index + EVAL_HISTORY_MESSAGE_BATCH_SIZE));+ }+ const parentLinks = preparedMessages+ .map(({ id, message }, index) => ({+ id,+ parentId: hasParentInfo+ ? message.parentId+ ? (idMapping.get(message.parentId) ?? null)+ : null+ : (preparedMessages[index - 1]?.id ?? null),+ }))+ .filter((link): link is { id: string; parentId: string } => link.parentId !== null);+ for (let index = 0; index < parentLinks.length; index += EVAL_HISTORY_MESSAGE_BATCH_SIZE) {+ const chunk = parentLinks.slice(index, index + EVAL_HISTORY_MESSAGE_BATCH_SIZE);+ await tx+ .update(messages)+ .set({+ parentId: sql`case ${messages.id} ${sql.join(+ chunk.map(({ id, parentId }) => sql`when ${id} then ${parentId}`),+ sql` `,+ )} end`,+ })+ .where(+ inArray(+ messages.id,+ chunk.map(({ id }) => id),+ ),+ );+ }+ for (let index = 0; index < pluginRows.length; index += EVAL_HISTORY_MESSAGE_BATCH_SIZE) {+ await tx+ .insert(messagePlugins)+ .values(pluginRows.slice(index, index + EVAL_HISTORY_MESSAGE_BATCH_SIZE));+ }++ await tx+ .update(topics)+ .set({ metadata: { [EVAL_HISTORY_TAIL_METADATA_KEY]: preparedMessages.at(-1)!.id } })+ .where(eq(topics.id, topicId));+ }++ await tx.insert(agentEvalRunTopics).values(+ preparedCases.map(({ testCase, topicId }) => ({+ runId,+ status: 'pending' as const,+ testCaseId: testCase.id,+ topicId,+ userId: deps.userId,+ workspaceId: deps.workspaceId ?? null,+ })),+ );++ return preparedCases.map(({ topicId }) => topicId);+ });+}++async function snapshotAgentConfig(+ deps: EvalRunDeps,+ agentId: string,+): Promise<EvalRunAgentSnapshot | undefined> {+ const agentConfig = await deps.agentService.getAgentConfigById(agentId);+ if (!agentConfig) return undefined;++ return {+ avatar: agentConfig.avatar,+ chatConfig: agentConfig.chatConfig as unknown as Record<string, unknown>,+ description: null,+ fewShots: agentConfig.fewShots,+ model: agentConfig.model,+ params: agentConfig.params as Record<string, unknown>,+ // Pinned identifiers only β this snapshot is a display-only DTO+ // (EvalRunAgentSnapshot.plugins stays string[]), and a disabled entry+ // isn't part of what actually ran.+ plugins: getActivePluginIds(agentConfig.plugins),+ provider: agentConfig.provider,+ systemRole: agentConfig.systemRole,+ title: agentConfig.title,+ };+}diff --git a/apps/server/src/services/agentEvalRun/deps.ts b/apps/server/src/services/agentEvalRun/deps.tsnew file mode 100644index 00000000000..c54074343ce--- /dev/null+++ b/apps/server/src/services/agentEvalRun/deps.ts@@ -0,0 +1,55 @@+import type { LobeChatDatabase } from '@lobechat/database';++import {+ AgentEvalBenchmarkModel,+ AgentEvalDatasetModel,+ AgentEvalExperimentModel,+ AgentEvalRunModel,+ AgentEvalRunTopicModel,+ AgentEvalTestCaseModel,+} from '@/database/models/agentEval';+import { MessageModel } from '@/database/models/message';+import { ThreadModel } from '@/database/models/thread';+import { TopicModel } from '@/database/models/topic';+import { AgentService } from '@/server/services/agent';++import type { EvalRunDeps } from './types';++/**+ * Builds the owner-scoped models every eval run stage works with. Used by the+ * `AgentEvalRunService` constructor and by completion hooks that need a fresh+ * set of models without importing the service class (which would be circular).+ */+export const createEvalRunDeps = (+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+): EvalRunDeps => {+ // Built in the order the class constructed its models before the split.+ const runModel = new AgentEvalRunModel(db, userId, workspaceId);+ const benchmarkModel = new AgentEvalBenchmarkModel(db, userId, workspaceId);+ const datasetModel = new AgentEvalDatasetModel(db, userId, workspaceId);+ const experimentModel = new AgentEvalExperimentModel(db, userId, workspaceId);+ const runTopicModel = new AgentEvalRunTopicModel(db, userId, workspaceId);+ const testCaseModel = new AgentEvalTestCaseModel(db, userId, workspaceId);+ const messageModel = new MessageModel(db, userId, workspaceId);+ const threadModel = new ThreadModel(db, userId, workspaceId);+ const topicModel = new TopicModel(db, userId, workspaceId);+ const agentService = new AgentService(db, userId, workspaceId);++ return {+ agentService,+ benchmarkModel,+ datasetModel,+ db,+ experimentModel,+ messageModel,+ runModel,+ runTopicModel,+ testCaseModel,+ threadModel,+ topicModel,+ userId,+ workspaceId,+ };+};diff --git a/apps/server/src/services/agentEvalRun/index.surface.test.ts b/apps/server/src/services/agentEvalRun/index.surface.test.tsnew file mode 100644index 00000000000..6e1ad131578--- /dev/null+++ b/apps/server/src/services/agentEvalRun/index.surface.test.ts@@ -0,0 +1,57 @@+// @vitest-environment node+import type { LobeChatDatabase } from '@lobechat/database';+import { describe, expect, it } from 'vitest';++import { evaluateAndFinalizeRun } from './aggregate';+import * as runModule from './index';+import { AgentEvalRunService, RUN_CREATE_ID_CONFLICT } from './index';++/**+ * Pins the public surface of `@/server/services/agentEvalRun`: the runtime+ * exports callers import and the members an `AgentEvalRunService` exposes. The+ * behavior behind them is covered by `__tests__/`.+ */+describe('agent eval run service public surface', () => {+ it('exports the same runtime names', () => {+ expect(Object.keys(runModule).sort()).toEqual([+ 'AgentEvalRunService',+ 'RUN_CREATE_ID_CONFLICT',+ ]);+ expect(RUN_CREATE_ID_CONFLICT).toBe('Run id already exists with different create parameters');+ });++ it('exposes the same public methods on the prototype', () => {+ const methods = [+ 'abortRun',+ 'canResumeTrajectory',+ 'checkAndHandleRunTimeout',+ 'claimRun',+ 'createRun',+ 'deleteRun',+ 'executeMultiThreadTrajectory',+ 'executeResumedThreadTrajectory',+ 'executeResumedTrajectory',+ 'executeThreadTrajectory',+ 'executeTrajectory',+ 'executeTrajectoryOnDemand',+ 'getAgentDisplayInfo',+ 'getResumableCases',+ 'getRunDetails',+ 'loadTrajectoryData',+ 'recordThreadCompletion',+ 'recordTrajectoryCompletion',+ 'resumeTrajectory',+ 'retryErrorCases',+ 'retrySingleCase',+ ];+ for (const method of methods)+ expect(typeof AgentEvalRunService.prototype[method as keyof AgentEvalRunService]).toBe(+ 'function',+ );+ });++ it('exposes evaluateAndFinalizeRun as the shared aggregate function', () => {+ const service = new AgentEvalRunService({} as LobeChatDatabase, 'user');+ expect(service.evaluateAndFinalizeRun).toBe(evaluateAndFinalizeRun);+ });+});diff --git a/apps/server/src/services/agentEvalRun/index.ts b/apps/server/src/services/agentEvalRun/index.tsindex 258d909af47..4efcb892704 100644--- a/apps/server/src/services/agentEvalRun/index.ts+++ b/apps/server/src/services/agentEvalRun/index.ts@@ -1,795 +1,84 @@-import { LOADING_FLAT } from '@lobechat/const';import type { LobeChatDatabase } from '@lobechat/database';-import { idGenerator } from '@lobechat/database';-import { evaluate } from '@lobechat/eval-rubric';-import type {- EvalBenchmarkRubric,- EvalCaseEnvironment,- EvalRunAgentSnapshot,- EvalRunConfig,- EvalRunInputConfig,- EvalRunMetrics,- EvalRunTopicResult,- EvalTestCaseMetadata,- EvalThreadResult,- ImportedMessage,- RubricType,- ToolIntervention,-} from '@lobechat/types';-import { getActivePluginIds, RequestTrigger } from '@lobechat/types';-import { clampToolIdentifier } from '@lobechat/utils/clampToolIdentifier';-import debug from 'debug';-import { eq, inArray, sql } from 'drizzle-orm';-import {- AgentEvalBenchmarkModel,- AgentEvalDatasetModel,- AgentEvalExperimentModel,- AgentEvalRunModel,- AgentEvalRunTopicModel,- AgentEvalTestCaseModel,-} from '@/database/models/agentEval';-import { MessageModel } from '@/database/models/message';-import { ThreadModel } from '@/database/models/thread';-import { TopicModel } from '@/database/models/topic';-import { agentEvalRunTopics, messagePlugins, messages, topics } from '@/database/schemas';-import { AgentService } from '@/server/services/agent';-import { AgentRuntimeService } from '@/server/services/agentRuntime/AgentRuntimeService';-import type { EvalRuntimeContext } from '@/server/services/agentRuntime/types';-import { AiAgentService } from '@/server/services/aiAgent';-import {- AgentEvalRunWorkflow,- type ResumeAgentTrajectoryPayload,- type ResumeThreadTrajectoryPayload,-} from '@/server/workflows/agentEvalRun';+import type { AgentEvalRunModel } from '@/database/models/agentEval';import { evaluateAndFinalizeRun } from './aggregate';+import { recordTrajectoryCompletion } from './completion';+import { createRun } from './createRun';+import { createEvalRunDeps } from './deps';+import { executeResumedThreadTrajectory, executeResumedTrajectory } from './resumeExecution';+import { canResumeTrajectory, getResumableCases, resumeTrajectory } from './resumeTarget';+import {+ abortRun,+ checkAndHandleRunTimeout,+ deleteRun,+ getAgentDisplayInfo,+ getRunDetails,+ retryErrorCases,+ retrySingleCase,+} from './runLifecycle';+import {+ executeMultiThreadTrajectory,+ executeThreadTrajectory,+ recordThreadCompletion,+} from './thread';+import {+ claimRun,+ executeTrajectory,+ executeTrajectoryOnDemand,+ loadTrajectoryData,+} from './trajectory';+import type { EvalRunDeps } from './types';-/** Round cost to at most 6 decimal places to avoid floating-point noise */-const roundCost = (v: number): number => Math.round(v * 1e6) / 1e6;-const EVAL_AGENT_RUNTIME_QSTASH_RETRIES = 5;-const EVAL_AGENT_RUNTIME_QSTASH_RETRY_DELAY = '10000 * (1 + retried)';-const EVAL_HISTORY_MESSAGE_BATCH_SIZE = 500;-const EVAL_HISTORY_TAIL_METADATA_KEY = 'evalHistoryTailMessageId';-const RESUMABLE_THREAD_STATUSES = new Set(['error', 'timeout']);--const getEvalContextParams = (- envPrompt?: string,- environment?: EvalCaseEnvironment,- caseId?: string,-) => {- const mergedEnvPrompt =- [envPrompt, environment?.envPrompt].filter(Boolean).join('\n\n') || undefined;- const evalRuntime: EvalRuntimeContext | undefined =- caseId || environment?.toolForwarding- ? { ...(caseId && { caseId }), toolForwarding: environment?.toolForwarding }- : undefined;-- return {- ...(mergedEnvPrompt && { evalContext: { envPrompt: mergedEnvPrompt } }),- ...(evalRuntime && { evalRuntime }),- };-};--const getCaseId = (metadata?: EvalTestCaseMetadata | null) => metadata?.caseId;--/** Thrown when a caller-supplied run id exists with non-equivalent create params. */-export const RUN_CREATE_ID_CONFLICT = 'Run id already exists with different create parameters';--/** Stable JSON stringify: sorts object keys recursively, drops undefined. */-const stableStringify = (value: unknown): string => {- if (value === undefined) return '';- if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? '';- if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;- const entries = Object.entries(value as Record<string, unknown>)- .filter(([, v]) => v !== undefined)- .sort(([a], [b]) => (a < b ? -1 : 1))- .map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`);- return `{${entries.join(',')}}`;-};--const log = debug('lobe-server:eval-run-service');--interface ResumableCaseTarget {- caseStatus?: string | null;- input: string;- resumeStatus?: 'error' | 'timeout';- sortOrder: number | null;- testCaseId: string;- threadId?: string;-}--interface ResumableThreadResult extends EvalThreadResult {- status: 'error' | 'timeout';-}--const getThreadResultStatus = (- evalResult: Record<string, unknown>,-): EvalThreadResult['status'] | undefined => {- const { status } = evalResult;-- if (status === 'completed' || status === 'error' || status === 'external' || status === 'timeout')- return status;-- if (evalResult.passed === true) return 'passed';- if (evalResult.passed === false) return 'failed';-- return undefined;-};+export { RUN_CREATE_ID_CONFLICT } from './createRun';-const resetResumedThreadResult = (thread: EvalThreadResult): EvalThreadResult => ({- threadId: thread.threadId,- status: thread.status === 'external' ? 'external' : 'running',-});+/** The arguments a stage function takes after its `deps`. */+type StageArgs<F> = F extends (deps: EvalRunDeps, ...args: infer A) => unknown ? A : never;export class AgentEvalRunService {- private readonly db: LobeChatDatabase;- private readonly userId: string;+ /** The same instance as `deps.runModel`; kept as a field for callers that read it directly. */private readonly runModel: AgentEvalRunModel;- private readonly benchmarkModel: AgentEvalBenchmarkModel;- private readonly datasetModel: AgentEvalDatasetModel;- private readonly experimentModel: AgentEvalExperimentModel;- private readonly runTopicModel: AgentEvalRunTopicModel;- private readonly testCaseModel: AgentEvalTestCaseModel;- private readonly messageModel: MessageModel;- private readonly threadModel: ThreadModel;- private readonly topicModel: TopicModel;- private readonly agentService: AgentService;-- private workspaceId?: string;+ private readonly deps: EvalRunDeps;constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {- this.db = db;- this.userId = userId;- this.workspaceId = workspaceId;- this.runModel = new AgentEvalRunModel(db, userId, workspaceId);- this.benchmarkModel = new AgentEvalBenchmarkModel(db, userId, workspaceId);- this.datasetModel = new AgentEvalDatasetModel(db, userId, workspaceId);- this.experimentModel = new AgentEvalExperimentModel(db, userId, workspaceId);- this.runTopicModel = new AgentEvalRunTopicModel(db, userId, workspaceId);- this.testCaseModel = new AgentEvalTestCaseModel(db, userId, workspaceId);- this.messageModel = new MessageModel(db, userId, workspaceId);- this.threadModel = new ThreadModel(db, userId, workspaceId);- this.topicModel = new TopicModel(db, userId, workspaceId);- this.agentService = new AgentService(db, userId, workspaceId);+ this.deps = createEvalRunDeps(db, userId, workspaceId);+ this.runModel = this.deps.runModel;}- async createRun(params: {- config?: EvalRunInputConfig;- datasetId: string;- experimentId?: string;- /**- * Caller-supplied run id for idempotent cross-server creation. When a run- * with this id already exists: equivalent immutable create params β the- * existing run is returned; otherwise a conflict error is thrown.- */- id?: string;- /**- * 'internal' (default): pre-create Topics/RunTopics for every test case and- * leave the run `idle` until `startRun` triggers the QStash workflow.- * 'external': create no Topics/RunTopics and set the run `pending` so an- * external worker can claim it; no workflow is triggered.- */- mode?: 'external' | 'internal';- name?: string;- parentRunId?: string;- targetAgentId?: string;- }) {- let { datasetId, targetAgentId } = params;- let inputConfig = params.config;- const isExternal = params.mode === 'external';-- // Fork: inherit target agent / dataset / config from the parent run.- // These are immutable on a fork β reject any override attempt.- if (params.parentRunId) {- const parent = await this.runModel.findById(params.parentRunId);- if (!parent) throw new Error('Parent run not found');-- if (- (params.targetAgentId && params.targetAgentId !== parent.targetAgentId) ||- (params.config && Object.keys(params.config).length > 0) ||- (params.datasetId && params.datasetId !== parent.datasetId)- ) {- throw new Error('Cannot override target agent, config, or dataset when forking a run');- }-- targetAgentId = parent.targetAgentId ?? undefined;- datasetId = parent.datasetId;- inputConfig = (parent.config as EvalRunInputConfig | undefined) ?? undefined;- }-- // External execution is driven case-by-case through `runExecuteCase`, which- // only supports single-thread (k=1) runs today. Check after fork resolution- // so inherited configs are covered too.- if (isExternal && ((inputConfig as { k?: number } | undefined)?.k ?? 1) > 1) {- throw new Error('External runs only support k=1 (pass@k is not supported yet)');- }-- // Validate the experiment scope (and bump its recency once the run exists).- if (params.experimentId) {- const experiment = await this.experimentModel.findById(params.experimentId);- if (!experiment) throw new Error('Experiment not found');- }-- // Re-snapshot the current agent config (forks capture the *current* state).- const agentSnapshot = targetAgentId ? await this.snapshotAgentConfig(targetAgentId) : undefined;-- // Persist the execution mode as an immutable snapshot: a run's mode cannot- // be inferred from status once the run reaches a terminal state, and the- // idempotency check below must compare it.- const executionMode = isExternal ? ('external' as const) : ('internal' as const);- const config = { ...inputConfig, agentSnapshot, executionMode };-- // Idempotent create: a caller-supplied id that already exists returns the- // existing run when the immutable create params are equivalent (datasetId /- // experimentId / parentRunId / targetAgentId / executionMode / input config- // β the agent snapshot is excluded since it is re-captured server-side on- // every create).- const matchesExisting = (existing: {- config?: unknown;- datasetId: string;- experimentId?: string | null;- parentRunId?: string | null;- targetAgentId?: string | null;- }) => {- const {- agentSnapshot: _existingSnapshot,- executionMode: existingMode,- ...existingConfig- } = (existing.config ?? {}) as Record<string, unknown>;- return (- existing.datasetId === datasetId &&- (existing.experimentId ?? null) === (params.experimentId ?? null) &&- (existing.parentRunId ?? null) === (params.parentRunId ?? null) &&- (existing.targetAgentId ?? null) === (targetAgentId ?? null) &&- existingMode === executionMode &&- stableStringify(existingConfig) === stableStringify(inputConfig ?? {})- );- };-- if (params.id) {- const existing = await this.runModel.findById(params.id);- if (existing) {- if (!matchesExisting(existing)) throw new Error(RUN_CREATE_ID_CONFLICT);- return existing;- }- }-- const { mode: _mode, ...restParams } = params;- let run;- try {- run = await this.runModel.create({- ...restParams,- datasetId,- targetAgentId,- config,- // External runs start claimable; internal runs wait for `startRun`.- status: isExternal ? 'pending' : 'idle',- });- } catch (error) {- // Race-safe idempotency: a concurrent create with the same caller id won- // β return the winner when params are equivalent, else conflict.- const databaseError = error as { code?: string; cause?: { code?: string } };- if (params.id && (databaseError?.code ?? databaseError?.cause?.code) === '23505') {- const existing = await this.runModel.findById(params.id);- if (existing) {- if (!matchesExisting(existing)) throw new Error(RUN_CREATE_ID_CONFLICT, { cause: error });- return existing;- }- throw new Error(RUN_CREATE_ID_CONFLICT, { cause: error });- }- throw error;- }-- if (params.experimentId) {- await this.experimentModel.touch(params.experimentId);- }-- // External runs create Topics/RunTopics on demand (per executed case).- if (isExternal) return run;-- // Pre-create Topics and RunTopics for all test cases (status='pending')- const testCases = await this.testCaseModel.findByDatasetId(datasetId);-- if (testCases.length > 0) {- await this.createRunTopics(run.id, targetAgentId, testCases);- }-- return run;+ createRun(...args: StageArgs<typeof createRun>) {+ return createRun(this.deps, ...args);}- private createRunTopics(- runId: string,- targetAgentId: string | null | undefined,- testCases: Array<{- content: { input: string; messages?: ImportedMessage[] };- id: string;- sortOrder: number | null;- }>,- ) {- return this.db.transaction(async (tx) => {- const preparedCases = testCases.map((testCase) => ({- testCase,- topicId: idGenerator('topics'),- }));-- await tx.insert(topics).values(- preparedCases.map(({ testCase, topicId }) => ({- agentId: targetAgentId ?? null,- id: topicId,- title: `[${(testCase.sortOrder ?? 0) + 1}] ${testCase.content.input.slice(0, 50) || 'Topic'}...`,- trigger: 'eval' as const,- userId: this.userId,- workspaceId: this.workspaceId ?? null,- })),- );-- for (const { testCase, topicId } of preparedCases) {- const history = testCase.content.messages?.filter((message) => message.role !== 'system');- if (!history?.length) continue;-- const idMapping = new Map<string, string>();- const hasParentInfo = history.some((message) => message.parentId != null);- const now = Date.now();- let previousCreatedAt = Number.NEGATIVE_INFINITY;- const preparedMessages = history.map((message, index) => {- const id = idGenerator('messages');- if (message.id) idMapping.set(message.id, id);-- const timestamp =- message.createdAt === undefined- ? now + index- : typeof message.createdAt === 'number'- ? message.createdAt- : Date.parse(message.createdAt);- const createdAt = Math.max(- Number.isNaN(timestamp) ? now + index : timestamp,- previousCreatedAt + 1,- );- previousCreatedAt = createdAt;-- const updatedTimestamp =- message.updatedAt === undefined- ? createdAt- : typeof message.updatedAt === 'number'- ? message.updatedAt- : Date.parse(message.updatedAt);-- return {- createdAt,- id,- message,- updatedAt: Math.max(- Number.isNaN(updatedTimestamp) ? createdAt : updatedTimestamp,- createdAt,- ),- };- });-- const messageRows = preparedMessages.map(- ({ createdAt, id, message, updatedAt }, index) => ({- agentId: null,- content: message.content,- createdAt: new Date(createdAt),- error: message.error ?? null,- id,- metadata: message.metadata ?? null,- model: message.model ?? null,- parentId: null,- provider: message.provider ?? null,- reasoning: message.reasoning ?? null,- role: message.role,- search: message.search ?? null,- tools: message.tools ?? null,- topicId,- traceId: message.traceId ?? null,- updatedAt: new Date(updatedAt),- userId: this.userId,- workspaceId: this.workspaceId ?? null,- }),- );- const pluginRows = preparedMessages.flatMap(({ id, message }) => {- if (- !message.plugin &&- !message.pluginError &&- !message.pluginIntervention &&- !message.pluginState &&- !message.tool_call_id- ) {- return [];- }-- return [- {- apiName: clampToolIdentifier(message.plugin?.apiName) ?? null,- arguments: message.plugin?.arguments ?? null,- error: message.pluginError ?? null,- id,- identifier: clampToolIdentifier(message.plugin?.identifier) ?? null,- intervention: message.pluginIntervention as ToolIntervention | undefined,- state: message.pluginState ?? null,- toolCallId: message.tool_call_id ?? null,- type: message.plugin?.type ?? null,- userId: this.userId,- workspaceId: this.workspaceId ?? null,- },- ];- });-- for (let index = 0; index < messageRows.length; index += EVAL_HISTORY_MESSAGE_BATCH_SIZE) {- await tx- .insert(messages)- .values(messageRows.slice(index, index + EVAL_HISTORY_MESSAGE_BATCH_SIZE));- }- const parentLinks = preparedMessages- .map(({ id, message }, index) => ({- id,- parentId: hasParentInfo- ? message.parentId- ? (idMapping.get(message.parentId) ?? null)- : null- : (preparedMessages[index - 1]?.id ?? null),- }))- .filter((link): link is { id: string; parentId: string } => link.parentId !== null);- for (let index = 0; index < parentLinks.length; index += EVAL_HISTORY_MESSAGE_BATCH_SIZE) {- const chunk = parentLinks.slice(index, index + EVAL_HISTORY_MESSAGE_BATCH_SIZE);- await tx- .update(messages)- .set({- parentId: sql`case ${messages.id} ${sql.join(- chunk.map(({ id, parentId }) => sql`when ${id} then ${parentId}`),- sql` `,- )} end`,- })- .where(- inArray(- messages.id,- chunk.map(({ id }) => id),- ),- );- }- for (let index = 0; index < pluginRows.length; index += EVAL_HISTORY_MESSAGE_BATCH_SIZE) {- await tx- .insert(messagePlugins)- .values(pluginRows.slice(index, index + EVAL_HISTORY_MESSAGE_BATCH_SIZE));- }-- await tx- .update(topics)- .set({ metadata: { [EVAL_HISTORY_TAIL_METADATA_KEY]: preparedMessages.at(-1)!.id } })- .where(eq(topics.id, topicId));- }-- await tx.insert(agentEvalRunTopics).values(- preparedCases.map(({ testCase, topicId }) => ({- runId,- status: 'pending' as const,- testCaseId: testCase.id,- topicId,- userId: this.userId,- workspaceId: this.workspaceId ?? null,- })),- );-- return preparedCases.map(({ topicId }) => topicId);- });+ deleteRun(...args: StageArgs<typeof deleteRun>) {+ return deleteRun(this.deps, ...args);}- async deleteRun(id: string) {- // 1. Get associated topics before deletion (cascade will remove run_topics rows)- const runTopics = await this.runTopicModel.findByRunId(id);- const topicIds = runTopics.map((rt) => rt.topicId).filter(Boolean);-- // 2. Delete the run (cascades to run_topics)- const result = await this.runModel.delete(id);-- // 3. Delete orphaned topics- if (topicIds.length > 0) {- await this.topicModel.batchDelete(topicIds);- }-- return result;+ abortRun(...args: StageArgs<typeof abortRun>) {+ return abortRun(this.deps, ...args);}- async abortRun(runId: string) {- // 1. Find all running RunTopics and interrupt their agent operations- const runTopics = await this.runTopicModel.findByRunId(runId);- const runningTopics = runTopics.filter((t) => t.status === 'running');-- if (runningTopics.length > 0) {- const agentRuntimeService = new AgentRuntimeService(this.db, this.userId);- for (const rt of runningTopics) {- const opId = (rt.evalResult as EvalRunTopicResult)?.operationId;- if (opId) {- try {- await agentRuntimeService.interruptOperation(opId);- } catch {- // best effort- }- }- }- }-- // 2. Mark all pending/running RunTopics as aborted (error + 'Aborted')- await this.runTopicModel.batchMarkAborted(runId);-- // 3. Update run status to aborted- await this.runModel.update(runId, { status: 'aborted' });+ retryErrorCases(...args: StageArgs<typeof retryErrorCases>) {+ return retryErrorCases(this.deps, ...args);}- async retryErrorCases(runId: string): Promise<{ retryCount: number }> {- const run = await this.runModel.findById(runId);- if (!run) throw new Error('Run not found');-- const allTopics = await this.runTopicModel.findByRunId(runId);- const errorTopics = allTopics.filter((t) => t.status === 'error' || t.status === 'timeout');-- if (errorTopics.length === 0) return { retryCount: 0 };-- // Collect test case IDs and info for recreation- const errorTestCases = errorTopics.map((t) => ({- content: t.testCase?.content ?? { input: '' },- id: t.testCaseId,- sortOrder: t.testCase?.sortOrder ?? null,- }));-- // 1. Delete error/terminal RunTopics (the filter above excludes active- // running/pending cases, so only terminal rows are ever removed).- await this.runTopicModel.deleteErrorRunTopics(runId);-- // 2. Preserve old Topics (old conversations are kept for audit/history);- // only the RunTopic association is replaced.- // 3. Create fresh Topics, histories, and pending RunTopics together.- await this.createRunTopics(runId, run.targetAgentId, errorTestCases);-- // 4. Set run status to pending- await this.runModel.update(runId, { status: 'pending' });-- return { retryCount: errorTopics.length };+ retrySingleCase(...args: StageArgs<typeof retrySingleCase>) {+ return retrySingleCase(this.deps, ...args);}- async retrySingleCase(runId: string, testCaseId: string) {- const run = await this.runModel.findById(runId);- if (!run) throw new Error('Run not found');-- const runTopic = await this.runTopicModel.findByRunAndTestCase(runId, testCaseId);- if (!runTopic) throw new Error('RunTopic not found');-- // Active associations must not be replaced β surface a conflict.- if (runTopic.status === 'running' || runTopic.status === 'pending') {- throw new Error(`Cannot retry: case is ${runTopic.status}`);- }-- // 1. Delete old RunTopic association- await this.runTopicModel.deleteByRunAndTestCase(runId, testCaseId);-- // 2. Preserve the old Topic (conversation history); only re-link.- // 3. Create a fresh Topic, its history, and its RunTopic together.- await this.createRunTopics(runId, run.targetAgentId, [- {- content: runTopic.testCase?.content ?? { input: '' },- id: testCaseId,- sortOrder: runTopic.testCase?.sortOrder ?? null,- },- ]);-- // 5. Set run status to running- await this.runModel.update(runId, { status: 'running' });- }-- async canResumeTrajectory(params: { runId: string; testCaseId: string; threadId?: string }) {- const invalidResumeTargetReason = 'Invalid resume target';- const trajectoryNotResumableReason = 'Trajectory is not resumable';- const resumeLimitReachedReason = 'Resume limit reached';-- log('canResumeTrajectory: %O', params);- const run = await this.runModel.findById(params.runId);- if (!run) return { canResume: false, reason: invalidResumeTargetReason };-- if (!['aborted', 'failed', 'running'].includes(run.status)) {- return { canResume: false, reason: trajectoryNotResumableReason };- }-- const runTopic = await this.runTopicModel.findByRunAndTestCase(params.runId, params.testCaseId);- if (!runTopic) return { canResume: false, reason: invalidResumeTargetReason };-- log('canResumeTrajectory: runTopic.status=%s topicId=%s', runTopic.status, runTopic.topicId);-- const k = run.config?.k ?? 1;- const hasInvalidThreadTarget = (k === 1 && !!params.threadId) || (k > 1 && !params.threadId);- if (hasInvalidThreadTarget) {- return { canResume: false, reason: invalidResumeTargetReason };- }-- if (!runTopic.topicId) {- return { canResume: false, reason: invalidResumeTargetReason };- }-- if (k === 1 && !RESUMABLE_THREAD_STATUSES.has(runTopic.status ?? '')) {- log('canResumeTrajectory: rejected β runTopic.status=%s', runTopic.status);- return { canResume: false, reason: trajectoryNotResumableReason };- }-- if (params.threadId) {- const thread = await this.threadModel.findById(params.threadId);-- if (!thread || thread.topicId !== runTopic.topicId || thread.type !== 'eval') {- return { canResume: false, reason: invalidResumeTargetReason };- }-- const targetThread = runTopic.evalResult?.threads?.find(- (item) => item.threadId === params.threadId,- );-- if (!targetThread || !RESUMABLE_THREAD_STATUSES.has(targetThread.status ?? '')) {- return { canResume: false, reason: trajectoryNotResumableReason };- }-- const maxSteps = run.config?.maxSteps;- const prevSteps =- ((thread.metadata as Record<string, unknown> | null)?.steps as number | undefined) ?? 0;-- if (maxSteps && prevSteps >= maxSteps) {- log(- 'canResumeTrajectory: rejected thread β prevSteps=%d >= maxSteps=%d',- prevSteps,- maxSteps,- );- return { canResume: false, reason: resumeLimitReachedReason };- }- }-- // pass@1 resumes track steps on the runTopic; pass@k uses per-thread metadata above.- if (k > 1) return { canResume: true as const };-- // Reject if the previous run already exhausted maxSteps- const maxSteps = run.config?.maxSteps;- const prevSteps = runTopic.evalResult?.steps ?? 0;- if (maxSteps && prevSteps >= maxSteps) {- log('canResumeTrajectory: rejected β prevSteps=%d >= maxSteps=%d', prevSteps, maxSteps);- return { canResume: false, reason: resumeLimitReachedReason };- }-- return { canResume: true as const };+ canResumeTrajectory(...args: StageArgs<typeof canResumeTrajectory>) {+ return canResumeTrajectory(this.deps, ...args);}/*** Batch-check which error/timeout cases in a run can be resumed.* Returns one entry per candidate case with canResume + optional reason.*/- async getResumableCases(runId: string) {- const run = await this.runModel.findById(runId);- if (!run) return [];-- const allTopics = await this.runTopicModel.findByRunId(runId);- const k = run.config?.k ?? 1;- const candidates = allTopics- .map((topic) => this.getResumableCaseTarget(topic, k))- .filter((topic): topic is ResumableCaseTarget => !!topic);-- const results = await Promise.all(- candidates.map(async (candidate) => {- const check = await this.canResumeTrajectory({- runId,- testCaseId: candidate.testCaseId,- threadId: candidate.threadId,- });- return {- caseStatus: candidate.caseStatus,- canResume: check.canResume,- input: candidate.input,- reason: 'reason' in check ? check.reason : undefined,- resumeStatus: candidate.resumeStatus,- sortOrder: candidate.sortOrder,- testCaseId: candidate.testCaseId,- threadId: candidate.threadId,- };- }),- );-- return results;+ getResumableCases(...args: StageArgs<typeof getResumableCases>) {+ return getResumableCases(this.deps, ...args);}- async resumeTrajectory(params: { runId: string; testCaseId: string; threadId?: string }) {- log('resumeTrajectory: %O', params);- const resumeCheck = await this.canResumeTrajectory(params);- if (!resumeCheck.canResume) {- log('resumeTrajectory: canResume=false reason=%s', resumeCheck.reason);- throw new Error(resumeCheck.reason);- }-- const target = await this.resolveTrajectoryResumeTarget(params);- const { caseId, envPrompt, environment, parentMessageId, run, thread, topicId } = target;- log(- 'resumeTrajectory: resolved target β topicId=%s parentMessageId=%s threadId=%s',- topicId,- parentMessageId,- thread?.id,- );-- if (thread) {- log('resumeTrajectory: triggering resume-thread-trajectory');- await AgentEvalRunWorkflow.triggerResumeThreadTrajectory({- appContext: { threadId: thread.id, topicId },- caseId,- envPrompt,- maxSteps: run.config?.maxSteps,- parentMessageId,- runId: run.id,- targetAgentId: run.targetAgentId ?? undefined,- testCaseId: params.testCaseId,- threadId: thread.id,- topicId,- environment,- userId: this.userId,- });- } else {- log('resumeTrajectory: triggering resume-agent-trajectory');- await AgentEvalRunWorkflow.triggerResumeAgentTrajectory({- appContext: { topicId },- caseId,- envPrompt,- maxSteps: run.config?.maxSteps,- parentMessageId,- runId: run.id,- targetAgentId: run.targetAgentId ?? undefined,- testCaseId: params.testCaseId,- topicId,- environment,- userId: this.userId,- });- }-- const result = {- mode: thread ? ('thread' as const) : ('single' as const),- runId: run.id,- testCaseId: params.testCaseId,- threadId: thread?.id,- topicId,- triggered: true,- };- log('resumeTrajectory: done %O', result);- return result;- }-- private getResumableCaseTarget(- runTopic: {- evalResult?: EvalRunTopicResult | null;- status?: string | null;- testCase?: { content?: { input?: string } | null; sortOrder?: number | null } | null;- testCaseId: string;- },- k: number,- ): ResumableCaseTarget | undefined {- if (k === 1) {- if (!RESUMABLE_THREAD_STATUSES.has(runTopic.status ?? '')) return undefined;-- return {- caseStatus: runTopic.status,- input: runTopic.testCase?.content?.input ?? '',- resumeStatus: runTopic.status as 'error' | 'timeout',- sortOrder: runTopic.testCase?.sortOrder ?? null,- testCaseId: runTopic.testCaseId,- };- }-- const resumableThread = this.getResumableThread(runTopic.evalResult?.threads);- if (!resumableThread?.status) return undefined;-- return {- caseStatus: runTopic.status,- input: runTopic.testCase?.content?.input ?? '',- resumeStatus: resumableThread.status,- sortOrder: runTopic.testCase?.sortOrder ?? null,- testCaseId: runTopic.testCaseId,- threadId: resumableThread.threadId,- };- }-- private getResumableThread(threads?: EvalThreadResult[]) {- return threads?.find((thread): thread is ResumableThreadResult =>- RESUMABLE_THREAD_STATUSES.has(thread.status ?? ''),- );+ resumeTrajectory(...args: StageArgs<typeof resumeTrajectory>) {+ return resumeTrajectory(this.deps, ...args);}/**@@ -797,138 +86,8 @@ export class AgentEvalRunService {* Claims the runTopic via CAS (timeout β running) for idempotency, then* calls execAgent with resume=true so the runtime continues from parentMessageId.*/- async executeResumedTrajectory(params: ResumeAgentTrajectoryPayload) {- const {- appContext,- envPrompt,- maxSteps,- parentMessageId,- runId,- targetAgentId,- testCaseId,- topicId,- environment,- } = params;-- const resumeCheck = await this.canResumeTrajectory({ runId, testCaseId });- if (!resumeCheck.canResume) {- return { reason: resumeCheck.reason, status: 'cancelled' as const, topicId };- }-- // Look up the pre-created RunTopic and reset it for resume- log(- 'executeResumedTrajectory: run=%s testCase=%s topicId=%s parentMessageId=%s',- runId,- testCaseId,- topicId,- parentMessageId,- );- const runTopic = await this.runTopicModel.findByRunAndTestCase(runId, testCaseId);- if (!runTopic) {- throw new Error(`RunTopic not found for run=${runId} testCase=${testCaseId}`);- }-- // Capture accumulated telemetry from previous runs before clearing evalResult- const prevSteps = runTopic.evalResult?.steps ?? 0;- const prevCost = runTopic.evalResult?.cost ?? 0;- const prevLlmCalls = runTopic.evalResult?.llmCalls ?? 0;- const prevToolCalls = runTopic.evalResult?.toolCalls ?? 0;- const prevTokens = runTopic.evalResult?.tokens ?? 0;- log('executeResumedTrajectory: prev telemetry steps=%d cost=%d', prevSteps, prevCost);- const now = new Date();-- await this.runTopicModel.updateByRunAndTopic(runId, topicId, {- createdAt: now, // reset for timeout tracking β resume is a fresh time window- evalResult: null,- passed: null,- score: null,- status: 'running',- });-- await this.runModel.update(runId, { startedAt: now, status: 'running' });-- const aiAgentService = new AiAgentService(this.db, this.userId, {- workspaceId: this.workspaceId,- });- const webhookUrl = '/api/workflows/agent-eval-run/on-trajectory-complete';- const userId = this.userId;- const db = this.db;-- try {- const execResult = await aiAgentService.execAgent({- agentId: targetAgentId,- appContext,- autoStart: true,- trigger: RequestTrigger.Eval,- hooks: [- {- handler: async (event) => {- // Local mode: directly record completion- const service = new AgentEvalRunService(db, userId, this.workspaceId);- await service.recordTrajectoryCompletion({- runId,- status: event.status || event.reason || 'done',- telemetry: {- completionReason: event.reason,- cost: (event.cost ?? 0) + prevCost,- duration: event.duration,- errorDetail: event.errorDetail,- errorMessage: event.errorMessage,- llmCalls: (event.llmCalls ?? 0) + prevLlmCalls,- steps: (event.steps ?? 0) + prevSteps,- toolCalls: (event.toolCalls ?? 0) + prevToolCalls,- totalTokens: (event.totalTokens ?? 0) + prevTokens,- },- testCaseId,- });- },- id: 'eval-trajectory-complete',- type: 'onComplete' as const,- webhook: {- body: { runId, testCaseId, userId },- delivery: 'qstash' as const,- url: webhookUrl,- },- },- ],- ...getEvalContextParams(envPrompt, environment, params.caseId),- initialStepCount: prevSteps,- maxSteps,- parentMessageId,- prompt: '',- resume: true,- userInterventionConfig: { approvalMode: 'headless' },- });-- if (execResult?.operationId) {- await this.runTopicModel.updateByRunAndTopic(runId, topicId, {- evalResult: { operationId: execResult.operationId, rubricScores: [] },- });- }-- return { status: 'started' as const, topicId };- } catch (error) {- const errorMessage =- error instanceof Error ? error.message : 'Agent execution failed to start';- console.error(- `[resume-agent-trajectory] execAgent failed for run=${runId} testCase=${testCaseId}:`,- error,- );-- // Record error and finalize the run if all test cases are done- const { allDone } = await this.recordTrajectoryCompletion({- runId,- status: 'error',- telemetry: { completionReason: 'error', errorMessage },- testCaseId,- });-- if (allDone) {- await AgentEvalRunWorkflow.triggerFinalizeRun({ runId, userId: this.userId });- }-- return { reason: errorMessage, status: 'error' as const, topicId };- }+ executeResumedTrajectory(...args: StageArgs<typeof executeResumedTrajectory>) {+ return executeResumedTrajectory(this.deps, ...args);}/**@@ -936,460 +95,16 @@ export class AgentEvalRunService {* Claims the runTopic via CAS (timeout β running) for idempotency, then* calls execAgent with resume=true so the runtime continues from parentMessageId.*/- async executeResumedThreadTrajectory(params: ResumeThreadTrajectoryPayload) {- const {- appContext,- caseId,- envPrompt,- maxSteps,- parentMessageId,- runId,- targetAgentId,- testCaseId,- threadId,- environment,- topicId,- } = params;-- const resumeCheck = await this.canResumeTrajectory({ runId, testCaseId, threadId });- if (!resumeCheck.canResume) {- return { reason: resumeCheck.reason, status: 'cancelled' as const, threadId, topicId };- }-- // Look up the pre-created RunTopic and reset it for resume- const runTopic = await this.runTopicModel.findByRunAndTestCase(runId, testCaseId);- if (!runTopic) {- throw new Error(`RunTopic not found for run=${runId} testCase=${testCaseId}`);- }-- const currentThread = await this.threadModel.findById(threadId);- const currentThreadMeta = (currentThread?.metadata ?? {}) as Record<string, unknown>;- const prevThreads = runTopic.evalResult?.threads ?? [];- const nextThreads = prevThreads.some((thread) => thread.threadId === threadId)- ? prevThreads.map((thread) =>- thread.threadId === threadId ? resetResumedThreadResult(thread) : thread,- )- : [...prevThreads, { status: 'running' as const, threadId }];-- // Capture accumulated telemetry from the target thread only- const prevSteps = (currentThreadMeta.steps as number | undefined) ?? 0;- const prevCost = (currentThreadMeta.cost as number | undefined) ?? 0;- const prevLlmCalls = (currentThreadMeta.llmCalls as number | undefined) ?? 0;- const prevToolCalls = (currentThreadMeta.toolCalls as number | undefined) ?? 0;- const prevTokens = (currentThreadMeta.tokens as number | undefined) ?? 0;- const now = new Date();-- await this.runTopicModel.updateByRunAndTopic(runId, topicId, {- createdAt: now,- evalResult: { threads: nextThreads },- passed: null,- score: null,- status: 'running',- });-- await this.threadModel.update(threadId, {- metadata: { testCaseId } as any,- });-- await this.runModel.update(runId, { startedAt: now, status: 'running' });-- const aiAgentService = new AiAgentService(this.db, this.userId, {- workspaceId: this.workspaceId,- });- const webhookUrl = '/api/workflows/agent-eval-run/on-thread-complete';- const userId = this.userId;- const db = this.db;-- try {- const execResult = await aiAgentService.execAgent({- agentId: targetAgentId,- appContext,- autoStart: true,- trigger: RequestTrigger.Eval,- hooks: [- {- handler: async (event) => {- // Local mode: directly record thread completion- const service = new AgentEvalRunService(db, userId, this.workspaceId);- await service.recordThreadCompletion({- runId,- status: event.status || event.reason || 'done',- telemetry: {- completionReason: event.reason,- cost: (event.cost ?? 0) + prevCost,- duration: event.duration,- errorMessage: event.errorMessage,- llmCalls: (event.llmCalls ?? 0) + prevLlmCalls,- steps: (event.steps ?? 0) + prevSteps,- toolCalls: (event.toolCalls ?? 0) + prevToolCalls,- totalTokens: (event.totalTokens ?? 0) + prevTokens,- },- testCaseId,- threadId,- topicId,- });- },- id: 'eval-thread-complete',- type: 'onComplete' as const,- webhook: {- body: { runId, testCaseId, threadId, topicId, userId },- delivery: 'qstash' as const,- url: webhookUrl,- },- },- ],- ...getEvalContextParams(envPrompt, environment, caseId),- initialStepCount: prevSteps,- maxSteps,- parentMessageId,- prompt: '',- resume: true,- userInterventionConfig: { approvalMode: 'headless' },- });-- // Write operationId to thread metadata- if (execResult?.operationId) {- await this.threadModel.update(threadId, {- metadata: { operationId: execResult.operationId, testCaseId } as any,- });- }-- return { status: 'started' as const, threadId, topicId };- } catch (error) {- const errorMessage =- error instanceof Error ? error.message : 'Thread execution failed to start';- console.error(- `[resume-thread-trajectory] execAgent failed for run=${runId} thread=${threadId}:`,- error,- );-- // Record error and finalize the run if all test cases are done- const { allRunDone } = await this.recordThreadCompletion({- runId,- status: 'error',- telemetry: { completionReason: 'error', errorMessage },- testCaseId,- threadId,- topicId,- });-- if (allRunDone) {- await AgentEvalRunWorkflow.triggerFinalizeRun({ runId, userId: this.userId });- }-- return { reason: errorMessage, status: 'error' as const, threadId, topicId };- }+ executeResumedThreadTrajectory(...args: StageArgs<typeof executeResumedThreadTrajectory>) {+ return executeResumedThreadTrajectory(this.deps, ...args);}- private async resolveTrajectoryResumeTarget(params: {- runId: string;- testCaseId: string;- threadId?: string;- }) {- log(- 'resolveTrajectoryResumeTarget: run=%s testCase=%s thread=%s',- params.runId,- params.testCaseId,- params.threadId,- );- const loaded = await this.loadTrajectoryData(params.runId, params.testCaseId);- if ('error' in loaded) {- throw new Error(loaded.error);- }-- const { envPrompt, environment, run, testCase } = loaded;- const runTopic = await this.runTopicModel.findByRunAndTestCase(params.runId, params.testCaseId);- if (!runTopic?.topicId) throw new Error('RunTopic topicId is required');-- log(- 'resolveTrajectoryResumeTarget: topicId=%s runTopic.status=%s',- runTopic.topicId,- runTopic.status,- );-- let thread: Awaited<ReturnType<ThreadModel['findById']>> | undefined;-- if (params.threadId) {- thread = await this.threadModel.findById(params.threadId);- if (!thread) throw new Error('Thread not found');- }-- const { danglingIds, parentMessageId } = await this.resolveResumeParentMessageId({- threadId: thread?.id,- topicId: runTopic.topicId,- });-- log(- 'resolveTrajectoryResumeTarget: parentMessageId=%s danglingIds=%d',- parentMessageId,- danglingIds.length,- );-- // Remove dangling partial messages before resume so the context engine (which- // re-fetches all topic messages after every tool-call batch) cannot include them.- if (danglingIds.length > 0) {- log(- 'resolveTrajectoryResumeTarget: deleting %d dangling messages: %O',- danglingIds.length,- danglingIds,- );- await this.messageModel.deleteMessages(danglingIds);- }-- return {- appContext: thread- ? { threadId: thread.id, topicId: runTopic.topicId }- : { topicId: runTopic.topicId },- caseId: getCaseId(testCase.metadata),- envPrompt,- parentMessageId,- run,- runTopic,- thread,- environment,- topicId: runTopic.topicId,- };+ loadTrajectoryData(...args: StageArgs<typeof loadTrajectoryData>) {+ return loadTrajectoryData(this.deps, ...args);}- private async resolveResumeParentMessageId(params: { threadId?: string; topicId: string }) {- log('resolveResumeParentMessageId: topicId=%s threadId=%s', params.topicId, params.threadId);- const messages = await this.messageModel.query({- threadId: params.threadId,- topicId: params.topicId,- });-- log('resolveResumeParentMessageId: total messages=%d', messages.length);- log(- 'resolveResumeParentMessageId: messages (role, id, contentLen, parentId) = %O',- messages.map((m) => ({- role: m.role,- id: m.id,- contentLen: m.content?.length ?? 0,- parentId: (m as any).parentId ?? null,- })),- );-- // Strategy:- // - tool results are always complete (atomic, written after execution succeeds)- // - assistant messages may be partial (LLM stream interrupted mid-way)- // So: prefer the last tool result with content as the resume point.- // Only fall back to assistant / user if no tool result exists.-- let parentMessageId: string | undefined;-- // Pass 1: find the last tool result with content- for (let index = messages.length - 1; index >= 0; index--) {- const message = messages[index];- if (message.role === 'tool' && message.content) {- log(- 'resolveResumeParentMessageId: found via tool id=%s contentLen=%d',- message.id,- message.content.length,- );- parentMessageId = message.id;- break;- }- }-- // Pass 2: no tool result β fall back to last substantive assistant, then user- if (!parentMessageId) {- for (let index = messages.length - 1; index >= 0; index--) {- const message = messages[index];-- if (message.role === 'assistant') {- if (!message.content || message.content === LOADING_FLAT) {- log('resolveResumeParentMessageId: skip empty/loading assistant msgId=%s', message.id);- continue;- }- log(- 'resolveResumeParentMessageId: fallback via assistant id=%s contentLen=%d',- message.id,- message.content.length,- );- parentMessageId = message.id;- break;- }-- if (message.role === 'user') {- log('resolveResumeParentMessageId: fallback via user id=%s', message.id);- parentMessageId = message.id;- break;- }- }- }-- if (!parentMessageId) throw new Error('Unable to resolve a valid resume parent message');-- // Build the valid ancestor chain from parentMessageId up to root.- // Return danglingIds for the caller to delete β keeping this method side-effect-free.- const parentIdMap = new Map<string, string | null>();- for (const m of messages) {- parentIdMap.set(m.id, (m as any).parentId ?? null);- }-- const ancestorSet = new Set<string>();- let cursor: string | null = parentMessageId;- while (cursor) {- ancestorSet.add(cursor);- cursor = parentIdMap.get(cursor) ?? null;- }-- const danglingIds = messages.map((m) => m.id).filter((id) => !ancestorSet.has(id));-- return { danglingIds, parentMessageId };- }-- async loadTrajectoryData(runId: string, testCaseId: string) {- const run = await this.runModel.findById(runId);- if (!run) return { error: 'Run not found' as const };-- const testCase = await this.testCaseModel.findById(testCaseId);- if (!testCase) return { error: 'Test case not found' as const };-- let envPrompt: string | undefined;- let environment: EvalCaseEnvironment | undefined;- if (run.datasetId) {- const dataset = await this.datasetModel.findById(run.datasetId);- envPrompt = dataset?.evalConfig?.envPrompt;- environment = testCase.content.environment;- }-- return { envPrompt, environment, run, testCase };- }-- async executeTrajectory(params: {- envPrompt?: string;- run: {- config?: EvalRunConfig | null;- datasetId: string;- targetAgentId?: string | null;- };- runId: string;- testCase: {- content: { input?: string };- metadata?: EvalTestCaseMetadata | null;- sortOrder?: number | null;- };- testCaseId: string;- environment?: EvalCaseEnvironment;- }) {- const { runId, testCaseId } = params;-- // Look up the pre-created RunTopic (created during createRun)- const runTopic = await this.runTopicModel.findByRunAndTestCase(runId, testCaseId);- if (!runTopic) {- throw new Error(`RunTopic not found for run=${runId} testCase=${testCaseId}`);- }-- return this.executeTrajectoryCore({ ...params, topicId: runTopic.topicId });- }-- /**- * Shared trajectory execution once the target topic is known. Marks the- * RunTopic running and starts the agent via execAgent.- */- private async executeTrajectoryCore(params: {- /** Route execution to an enrolled device (native AgentRuntime). */- deviceId?: string;- envPrompt?: string;- run: {- config?: EvalRunConfig | null;- datasetId: string;- targetAgentId?: string | null;- };- runId: string;- testCase: {- content: { input?: string };- metadata?: EvalTestCaseMetadata | null;- sortOrder?: number | null;- };- testCaseId: string;- topicId: string;- environment?: EvalCaseEnvironment;- }) {- const { envPrompt, environment, run, runId, testCaseId, topicId } = params;- const caseId = getCaseId(params.testCase.metadata);-- // Update status from 'pending' to 'running'- await this.runTopicModel.updateByRunAndTopic(runId, topicId, { status: 'running' });-- const aiAgentService = new AiAgentService(this.db, this.userId, {- workspaceId: this.workspaceId,- });- const webhookUrl = '/api/workflows/agent-eval-run/on-trajectory-complete';- const userId = this.userId;- const db = this.db;-- try {- const execResult = await aiAgentService.execAgent({- agentId: run.targetAgentId ?? undefined,- appContext: { topicId },- autoStart: true,- ...(params.deviceId && { deviceId: params.deviceId }),- trigger: RequestTrigger.Eval,- hooks: [- {- handler: async (event) => {- // Local mode: directly record completion- const service = new AgentEvalRunService(db, userId, this.workspaceId);- await service.recordTrajectoryCompletion({- runId,- status: event.status || event.reason || 'done',- telemetry: {- completionReason: event.reason,- cost: event.cost,- duration: event.duration,- errorDetail: event.errorDetail,- errorMessage: event.errorMessage,- llmCalls: event.llmCalls,- steps: event.steps,- toolCalls: event.toolCalls,- totalTokens: event.totalTokens,- },- testCaseId,- });- },- id: 'eval-trajectory-complete',- type: 'onComplete' as const,- webhook: {- body: { runId, testCaseId, userId },- delivery: 'qstash' as const,- url: webhookUrl,- },- },- ],- ...getEvalContextParams(envPrompt, environment, caseId),- maxSteps: run.config?.maxSteps,- prompt: params.testCase.content.input || '',- queueRetries: EVAL_AGENT_RUNTIME_QSTASH_RETRIES,- queueRetryDelay: EVAL_AGENT_RUNTIME_QSTASH_RETRY_DELAY,- userInterventionConfig: { approvalMode: 'headless' },- });-- if (execResult?.operationId) {- await this.runTopicModel.updateByRunAndTopic(runId, topicId, {- evalResult: { operationId: execResult.operationId, rubricScores: [] },- });- }-- return { operationId: execResult?.operationId, topicId };- } catch (error) {- const errorMessage =- error instanceof Error ? error.message : 'Agent execution failed to start';- console.error(- `[run-agent-trajectory] execAgent failed for run=${runId} testCase=${testCaseId}:`,- error,- );-- await this.runTopicModel.updateByRunAndTopic(runId, topicId, {- evalResult: { completionReason: 'error', error: errorMessage, rubricScores: [] },- passed: false,- score: 0,- status: 'error',- });-- return { error: errorMessage, topicId };- }+ executeTrajectory(...args: StageArgs<typeof executeTrajectory>) {+ return executeTrajectory(this.deps, ...args);}/**@@ -1398,34 +113,8 @@ export class AgentEvalRunService {* exposing the dataset-native `metadata.caseId`), and the agent snapshot.* Throws when the run is not owned or not currently pending.*/- async claimRun(runId: string) {- const run = await this.runModel.claim(runId);- if (!run) throw new Error('Run is not pending or already claimed');-- const [dataset, testCases] = await Promise.all([- this.datasetModel.findById(run.datasetId),- this.testCaseModel.findByDatasetId(run.datasetId),- ]);-- return {- agentSnapshot: (run.config as EvalRunConfig | null)?.agentSnapshot,- dataset: dataset- ? {- evalConfig: dataset.evalConfig,- id: dataset.id,- identifier: dataset.identifier,- metadata: dataset.metadata,- name: dataset.name,- }- : undefined,- run,- testCases: testCases.map((tc) => ({- content: tc.content,- id: tc.id,- metadata: tc.metadata,- sortOrder: tc.sortOrder,- })),- };+ claimRun(...args: StageArgs<typeof claimRun>) {+ return claimRun(this.deps, ...args);}/**@@ -1435,246 +124,24 @@ export class AgentEvalRunService {* then runs the trajectory. Idempotent for terminal cases β the old RunTopic* association is replaced with a fresh Topic; an active case is rejected.*/- async executeTrajectoryOnDemand(params: {- caseId: string;- /** Route execution to an enrolled device (native AgentRuntime). */- deviceId?: string;- prompt?: string;- runId: string;- }) {- const { runId, caseId } = params;-- const run = await this.runModel.findById(runId);- if (!run) throw new Error('Run not found');- if (run.status !== 'running') {- throw new Error(`Run is not running (status=${run.status}); claim it first`);- }- if (((run.config as EvalRunConfig | null)?.k ?? 1) > 1) {- throw new Error('External execution only supports k=1');- }-- // Resolve the dataset-native caseId to an internal test case.- let testCase = await this.testCaseModel.findByDatasetIdAndCaseId(run.datasetId, caseId);- if (!testCase) {- const byId = await this.testCaseModel.findById(caseId);- if (byId && byId.datasetId === run.datasetId) testCase = byId;- }- if (!testCase) throw new Error(`Test case not found for caseId=${caseId}`);-- const testCaseId = testCase.id;- const dataset = await this.datasetModel.findById(run.datasetId);- const envPrompt = dataset?.evalConfig?.envPrompt;- const environment = testCase.content.environment;-- // Idempotent re-run of a terminal case: drop only the old RunTopic- // association (the old Topic is preserved) and link a fresh one.- const existing = await this.runTopicModel.findByRunAndTestCase(runId, testCaseId);- if (existing) {- if (existing.status === 'running' || existing.status === 'pending') {- throw new Error(`Case ${caseId} is already active for this run`);- }- await this.runTopicModel.deleteByRunAndTestCase(runId, testCaseId);- }-- const topicId = (- await this.createRunTopics(runId, run.targetAgentId, [- { content: testCase.content, id: testCaseId, sortOrder: testCase.sortOrder },- ])- )[0]!;-- const result = await this.executeTrajectoryCore({- deviceId: params.deviceId,- envPrompt,- run: { config: run.config, datasetId: run.datasetId, targetAgentId: run.targetAgentId },- runId,- testCase: {- content: { ...testCase.content, input: params.prompt ?? testCase.content.input },- metadata: testCase.metadata,- sortOrder: testCase.sortOrder,- },- testCaseId,- topicId,- environment,- });-- return { ...result, testCaseId };+ executeTrajectoryOnDemand(...args: StageArgs<typeof executeTrajectoryOnDemand>) {+ return executeTrajectoryOnDemand(this.deps, ...args);}/*** Execute a test case with K threads (for pass@k).* Creates K threads in the pre-existing topic, then triggers K run-thread-trajectory workflows.*/- async executeMultiThreadTrajectory(params: {- k: number;- run: {- config?: EvalRunConfig | null;- datasetId: string;- targetAgentId?: string | null;- };- runId: string;- testCaseId: string;- }) {- const { k, runId, testCaseId } = params;-- const runTopic = await this.runTopicModel.findByRunAndTestCase(runId, testCaseId);- if (!runTopic) {- throw new Error(`RunTopic not found for run=${runId} testCase=${testCaseId}`);- }-- const topicId = runTopic.topicId;- const topic = await this.topicModel.findById(topicId);- const historyTailMessageId = topic?.metadata?.[EVAL_HISTORY_TAIL_METADATA_KEY];- const sourceMessageId =- typeof historyTailMessageId === 'string' ? historyTailMessageId : undefined;-- // Update status from 'pending' to 'running'- await this.runTopicModel.updateByRunAndTopic(runId, topicId, { status: 'running' });-- // Create K threads in the topic- const threadIds: string[] = [];- for (let i = 0; i < k; i++) {- const thread = await this.threadModel.create({- sourceMessageId,- topicId,- type: 'eval',- });- if (thread) threadIds.push(thread.id);- }-- await this.runTopicModel.updateByRunAndTopic(runId, topicId, {- evalResult: {- // Persist thread ids before fan-out so pass@k UIs can render attempts immediately.- ...(runTopic.evalResult as EvalRunTopicResult | null),- threads: threadIds.map((threadId) => ({- status: 'running' as const,- threadId,- })),- } satisfies EvalRunTopicResult,- });-- // Trigger K run-thread-trajectory workflows in parallel- await Promise.all(- threadIds.map((threadId) =>- AgentEvalRunWorkflow.triggerRunThreadTrajectory({- runId,- testCaseId,- threadId,- topicId,- userId: this.userId,- }),- ),- );-- return { threadIds, topicId };+ executeMultiThreadTrajectory(...args: StageArgs<typeof executeMultiThreadTrajectory>) {+ return executeMultiThreadTrajectory(this.deps, ...args);}/*** Execute a single thread trajectory (for pass@k).* Calls execAgent with topicId + threadId, webhook points to on-thread-complete.*/- async executeThreadTrajectory(params: {- envPrompt?: string;- run: {- config?: EvalRunConfig | null;- targetAgentId?: string | null;- };- runId: string;- testCase: {- content: { input?: string };- metadata?: EvalTestCaseMetadata | null;- sortOrder?: number | null;- };- testCaseId: string;- threadId: string;- topicId: string;- environment?: EvalCaseEnvironment;- }) {- const { envPrompt, environment, run, runId, testCaseId, threadId, topicId } = params;- const caseId = getCaseId(params.testCase.metadata);-- const aiAgentService = new AiAgentService(this.db, this.userId, {- workspaceId: this.workspaceId,- });- const webhookUrl = '/api/workflows/agent-eval-run/on-thread-complete';- const userId = this.userId;- const db = this.db;-- try {- const execResult = await aiAgentService.execAgent({- agentId: run.targetAgentId ?? undefined,- appContext: { threadId, topicId },- autoStart: true,- trigger: RequestTrigger.Eval,- hooks: [- {- handler: async (event) => {- // Local mode: directly record thread completion- const service = new AgentEvalRunService(db, userId, this.workspaceId);- await service.recordThreadCompletion({- runId,- status: event.status || event.reason || 'done',- telemetry: {- completionReason: event.reason,- cost: event.cost,- duration: event.duration,- errorMessage: event.errorMessage,- llmCalls: event.llmCalls,- steps: event.steps,- toolCalls: event.toolCalls,- totalTokens: event.totalTokens,- },- testCaseId,- threadId,- topicId,- });- },- id: 'eval-thread-complete',- type: 'onComplete' as const,- webhook: {- body: { runId, testCaseId, threadId, topicId, userId },- delivery: 'qstash' as const,- url: webhookUrl,- },- },- ],- ...getEvalContextParams(envPrompt, environment, caseId),- maxSteps: run.config?.maxSteps,- prompt: params.testCase.content.input || '',- queueRetries: EVAL_AGENT_RUNTIME_QSTASH_RETRIES,- queueRetryDelay: EVAL_AGENT_RUNTIME_QSTASH_RETRY_DELAY,- userInterventionConfig: { approvalMode: 'headless' },- });-- // Write operationId to thread metadata- if (execResult?.operationId) {- await this.threadModel.update(threadId, {- metadata: { operationId: execResult.operationId, testCaseId },- } as any);- }-- return { threadId, topicId };- } catch (error) {- const errorMessage =- error instanceof Error ? error.message : 'Thread execution failed to start';- console.error(- `[run-thread-trajectory] execAgent failed for run=${runId} thread=${threadId}:`,- error,- );-- // Mark the thread explicitly as error; aggregation and resume-target selection rely on metadata.status.- await this.threadModel.update(threadId, {- metadata: {- completedAt: new Date().toISOString(),- error: errorMessage,- passed: false,- score: 0,- status: 'error',- testCaseId,- },- } as any);-- return { error: errorMessage, threadId, topicId };- }+ executeThreadTrajectory(...args: StageArgs<typeof executeThreadTrajectory>) {+ return executeThreadTrajectory(this.deps, ...args);}/**@@ -1682,856 +149,31 @@ export class AgentEvalRunService {* Evaluates the thread's messages, writes result to thread.metadata,* then checks if all K threads are done. If so, aggregates into RunTopic.*/- async recordThreadCompletion(params: {- runId: string;- status: string;- telemetry: {- completionReason?: string;- cost?: number;- duration?: number;- errorMessage?: string;- llmCalls?: number;- steps?: number;- toolCalls?: number;- totalTokens?: number;- };- testCaseId: string;- threadId: string;- topicId: string;- }): Promise<{ allRunDone: boolean; allThreadsDone: boolean }> {- const { runId, testCaseId, threadId, topicId, telemetry, status } = params;-- // 1. Evaluate this thread's messages- const evalResult = await this.evaluateThread({- runId,- status,- telemetry,- testCaseId,- threadId,- topicId,- });-- // 2. Write eval result to thread.metadata- await this.threadModel.update(threadId, {- metadata: {- ...evalResult,- completedAt: new Date().toISOString(),- // Normalize status into metadata so later aggregation can reconstruct threads[] consistently.- status: getThreadResultStatus(evalResult),- testCaseId,- },- } as any);-- // 3. Check if all K threads for this topic are done- const allThreads = await this.threadModel.queryByTopicId(topicId);- const evalThreads = allThreads.filter((t) => t.type === 'eval');- const completedThreads = evalThreads.filter((t) => {- const meta = t.metadata as Record<string, unknown> | null;- return meta && 'completedAt' in meta;- });-- const allThreadsDone = completedThreads.length >= evalThreads.length;-- if (!allThreadsDone) {- return { allRunDone: false, allThreadsDone: false };- }-- // 4. All K threads done β aggregate into RunTopic- await this.aggregateThreadResults({- completedThreads: evalThreads,- runId,- testCaseId,- topicId,- });-- // 5. Check if the entire run is done (same as recordTrajectoryCompletion)- const run = await this.runModel.findById(runId);- if (!run) return { allRunDone: false, allThreadsDone: true };-- const totalCases = run.metrics?.totalCases;- if (!totalCases) return { allRunDone: false, allThreadsDone: true };-- const allTopics = await this.runTopicModel.findByRunId(runId);- const completedCount = allTopics.filter(- (t) => (t.evalResult && 'completionReason' in t.evalResult) || t.status === 'timeout',- ).length;-- // Update run metrics- const passedCases = allTopics.filter((t) => t.status === 'passed').length;- const failedCases = allTopics.filter((t) => t.status === 'failed').length;- const errorCases = allTopics.filter((t) => t.status === 'error').length;- const externalCasesRT = allTopics.filter((t) => t.status === 'external').length;- const timeoutCases = allTopics.filter((t) => t.status === 'timeout').length;-- let sumCost = 0;- let sumTokens = 0;- let sumSteps = 0;- let sumLlmCalls = 0;- let sumToolCalls = 0;- let actualTotalCost = 0;- let actualTotalTokens = 0;- let actualTotalDuration = 0;- for (const t of allTopics) {- const r = t.evalResult as Record<string, unknown> | null;- if (r && ('completionReason' in r || t.status === 'timeout')) {- if (typeof r.cost === 'number') sumCost += r.cost;- if (typeof r.tokens === 'number') sumTokens += r.tokens;- if (typeof r.steps === 'number') sumSteps += r.steps;- if (typeof r.llmCalls === 'number') sumLlmCalls += r.llmCalls;- if (typeof r.toolCalls === 'number') sumToolCalls += r.toolCalls;- const rTotalCost =- typeof r.totalCost === 'number' ? r.totalCost : typeof r.cost === 'number' ? r.cost : 0;- const rTotalTokens =- typeof r.totalTokens === 'number'- ? r.totalTokens- : typeof r.tokens === 'number'- ? r.tokens- : 0;- const rTotalDuration =- typeof r.totalDuration === 'number'- ? r.totalDuration- : typeof r.duration === 'number'- ? r.duration- : 0;- actualTotalCost += rTotalCost;- actualTotalTokens += rTotalTokens;- actualTotalDuration += rTotalDuration;- }- }-- await this.runModel.update(runId, {- metrics: {- ...(run.metrics as EvalRunMetrics),- completedCases: completedCount,- cost: sumCost ? roundCost(sumCost) : undefined,- errorCases,- externalCases: externalCasesRT || undefined,- failedCases,- llmCalls: sumLlmCalls || undefined,- passedCases,- perCaseCost: sumCost && completedCount ? roundCost(sumCost / completedCount) : undefined,- perCaseLlmCalls:- sumLlmCalls && completedCount- ? Math.round((sumLlmCalls / completedCount) * 10) / 10- : undefined,- perCaseSteps:- sumSteps && completedCount- ? Math.round((sumSteps / completedCount) * 10) / 10- : undefined,- perCaseTokens:- sumTokens && completedCount ? Math.round(sumTokens / completedCount) : undefined,- perCaseToolCalls:- sumToolCalls && completedCount- ? Math.round((sumToolCalls / completedCount) * 10) / 10- : undefined,- steps: sumSteps || undefined,- timeoutCases,- tokens: sumTokens || undefined,- toolCalls: sumToolCalls || undefined,- totalCost: actualTotalCost ? roundCost(actualTotalCost) : undefined,- totalDuration: actualTotalDuration || undefined,- totalTokens: actualTotalTokens || undefined,- },- });-- return { allRunDone: completedCount >= totalCases, allThreadsDone: true };- }-- /**- * Evaluate a single thread's messages against rubrics.- * Returns the eval result to write into thread.metadata.- */- private async evaluateThread(params: {- runId: string;- status: string;- telemetry: {- completionReason?: string;- cost?: number;- duration?: number;- errorDetail?: unknown;- errorMessage?: string;- llmCalls?: number;- steps?: number;- toolCalls?: number;- totalTokens?: number;- };- testCaseId: string;- threadId: string;- topicId: string;- }): Promise<Record<string, unknown>> {- const { runId, status, telemetry, testCaseId, threadId } = params;-- const baseMeta: Record<string, unknown> = {- completionReason: telemetry.completionReason,- cost: telemetry.cost != null ? roundCost(telemetry.cost) : undefined,- duration: telemetry.duration,- llmCalls: telemetry.llmCalls,- steps: telemetry.steps,- tokens: telemetry.totalTokens,- toolCalls: telemetry.toolCalls,- };-- // Error case β skip evaluation- if (status === 'error') {- return {- ...baseMeta,- error:- telemetry.errorMessage || `Execution error: ${telemetry.completionReason || 'unknown'}`,- errorDetail: telemetry.errorDetail,- passed: false,- score: 0,- };- }-- // Load run β dataset β benchmark for rubrics- const run = await this.runModel.findById(runId);- if (!run) return { ...baseMeta, error: 'Run not found', passed: false, score: 0 };-- const dataset = await this.datasetModel.findById(run.datasetId);- if (!dataset) return { ...baseMeta, error: 'Dataset not found', passed: false, score: 0 };-- // A dataset need not belong to a benchmark; such a dataset simply- // contributes no benchmark-level rubrics, and scoring falls back to the- // per-case / per-dataset evalMode. Bailing here would leave every case in a- // captured dataset permanently unscored.- const benchmark = dataset.benchmarkId- ? await this.benchmarkModel.findById(dataset.benchmarkId)- : null;-- const testCase = await this.testCaseModel.findById(testCaseId);- if (!testCase) return { ...baseMeta, error: 'Test case not found', passed: false, score: 0 };-- const passThreshold = (run.config?.passThreshold as number) ?? 0.6;-- // Get messages for this thread- const messages = await this.messageModel.query({ threadId, topicId: params.topicId });- const assistantMessages = messages.filter((m: { role: string }) => m.role === 'assistant');- const lastAssistantMsg = assistantMessages.at(-1);-- if (!lastAssistantMsg || !lastAssistantMsg.content) {- return {- ...baseMeta,- error: 'No assistant output',- passed: false,- rubricScores: [],- score: 0,- };- }-- // Resolve rubrics- const evalMode = (testCase.evalMode ?? dataset.evalMode) as RubricType | null | undefined;- const evalConfig = testCase.evalConfig ?? dataset.evalConfig;-- // ββ External eval mode: agent finished, hand off to external scorer ββ- if (evalMode === 'external') {- return {- ...baseMeta,- awaitingExternalEval: true,- passed: undefined,- score: undefined,- status: 'external',- };- }-- let effectiveRubrics: EvalBenchmarkRubric[];- if (evalMode) {- effectiveRubrics = [- {- config: (evalConfig ?? {}) as unknown as EvalBenchmarkRubric['config'],- id: `eval-mode-${evalMode}`,- name: evalMode,- type: evalMode,- weight: 1,- },- ];- } else {- effectiveRubrics = benchmark?.rubrics ?? [];- }-- // Run evaluation- const result = await evaluate(- { actual: lastAssistantMsg.content, rubrics: effectiveRubrics, testCase: testCase.content },- { passThreshold },- );-- return {- ...baseMeta,- passed: result.passed,- rubricScores: result.rubricResults.map((r) => ({- reason: r.reason,- rubricId: r.rubricId,- score: r.score,- })),- score: result.score,- };- }-- /**- * Aggregate all completed thread results into RunTopic.- * Writes threads[] array, plus top-level score/passed using pass@k logic.- */- private async aggregateThreadResults(params: {- completedThreads: Array<{ id: string; metadata?: Record<string, unknown> | null }>;- runId: string;- testCaseId: string;- topicId: string;- }) {- const { completedThreads, runId, topicId } = params;-- // Build threads array from metadata- const threadResults: Array<{- completionReason?: string;- cost?: number;- duration?: number;- error?: string;- llmCalls?: number;- passed?: boolean;- rubricScores?: Array<{ reason?: string; rubricId: string; score: number }>;- score?: number;- status?: 'error' | 'external' | 'failed' | 'passed' | 'running' | 'timeout';- steps?: number;- threadId: string;- tokens?: number;- toolCalls?: number;- }> = completedThreads.map((t) => {- const meta = (t.metadata ?? {}) as Record<string, unknown>;- return {- completionReason: meta.completionReason as string | undefined,- cost: meta.cost as number | undefined,- duration: meta.duration as number | undefined,- error: meta.error as string | undefined,- llmCalls: meta.llmCalls as number | undefined,- passed: meta.passed as boolean | undefined,- rubricScores: meta.rubricScores as any,- score: meta.score as number | undefined,- status: meta.status as- 'error' | 'external' | 'failed' | 'passed' | 'running' | 'timeout' | undefined,- steps: meta.steps as number | undefined,- threadId: t.id,- tokens: meta.tokens as number | undefined,- toolCalls: meta.toolCalls as number | undefined,- };- });-- // ββ External eval mode: if all threads await external scoring, propagate that status ββ- const allExternal = threadResults.every((t) => t.status === 'external');- if (allExternal) {- await this.runTopicModel.updateByRunAndTopic(runId, topicId, {- evalResult: {- awaitingExternalEval: true,- completionReason: 'external',- threads: threadResults,- } satisfies EvalRunTopicResult,- status: 'external',- });- return;- }-- // pass@k: at least one thread passed- const anyPassed = threadResults.some((t) => t.passed === true);- // pass^k: all threads passed- const allPassed = threadResults.every((t) => t.passed === true);-- // Best score (used as the representative score)- const scores = threadResults.filter((t) => t.score != null).map((t) => t.score!);- const bestScore = scores.length > 0 ? Math.max(...scores) : 0;-- // Aggregate metrics as totals across K threads- let totalCost = 0;- let totalDuration = 0;- let totalTokens = 0;- let totalSteps = 0;- let totalLlmCalls = 0;- let totalToolCalls = 0;- for (const t of threadResults) {- if (t.cost) totalCost += t.cost;- if (t.duration) totalDuration += t.duration;- if (t.tokens) totalTokens += t.tokens;- if (t.steps) totalSteps += t.steps;- if (t.llmCalls) totalLlmCalls += t.llmCalls;- if (t.toolCalls) totalToolCalls += t.toolCalls;- }-- // Compute per-case averages (primary fields = avg)- const k = threadResults.length;-- // The topic-level completionReason: use "completed" if any succeeded- const completionReason = anyPassed ? 'completed' : 'failed';-- // Write aggregated result to RunTopic- // Primary fields (cost/tokens/duration/steps/llmCalls/toolCalls) = average per execution- // total* fields = cumulative across K threads- await this.runTopicModel.updateByRunAndTopic(runId, topicId, {- evalResult: {- completionReason,- cost: totalCost ? roundCost(totalCost / k) : undefined,- duration: totalDuration ? totalDuration / k : undefined,- llmCalls: totalLlmCalls ? Math.round((totalLlmCalls / k) * 10) / 10 : undefined,- passAllK: allPassed,- passAtK: anyPassed,- steps: totalSteps ? Math.round((totalSteps / k) * 10) / 10 : undefined,- threads: threadResults,- tokens: totalTokens ? totalTokens / k : undefined,- toolCalls: totalToolCalls ? Math.round((totalToolCalls / k) * 10) / 10 : undefined,- totalCost: totalCost ? roundCost(totalCost) : undefined,- totalDuration: totalDuration || undefined,- totalTokens: totalTokens || undefined,- } satisfies EvalRunTopicResult,- // pass@k: passed if any thread passed- passed: anyPassed,- score: bestScore,- status: anyPassed ? 'passed' : 'failed',- });+ recordThreadCompletion(...args: StageArgs<typeof recordThreadCompletion>) {+ return recordThreadCompletion(this.deps, ...args);}- async getRunDetails(id: string) {- let run = await this.runModel.findById(id);- if (!run) return null;-- // Check if a 'running' run has timed out- if (run.status === 'running') {- const timedOut = await this.checkAndHandleRunTimeout(run);- if (timedOut) {- run = (await this.runModel.findById(id))!;- }- }-- // Get dataset and run topics in parallel- const [dataset, runTopics] = await Promise.all([- this.datasetModel.findById(run.datasetId),- this.runTopicModel.findByRunId(id),- ]);-- // Get target agent display info via AgentService (fallback for runs without snapshot)- let targetAgent:- | { avatar?: string; id: string; model?: string; provider?: string; title?: string }- | undefined;- if (run.targetAgentId) {- const agentConfig = await this.agentService.getAgentConfigById(run.targetAgentId);- if (agentConfig) {- targetAgent = {- avatar: agentConfig.avatar,- id: run.targetAgentId,- model: agentConfig.model,- provider: agentConfig.provider,- title: agentConfig.title,- };- }- }-- return {- ...run,- dataset,- targetAgent,- topics: runTopics.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,- })),- };+ getRunDetails(...args: StageArgs<typeof getRunDetails>) {+ return getRunDetails(this.deps, ...args);}- async getAgentDisplayInfo(agentId: string) {- const agentConfig = await this.agentService.getAgentConfigById(agentId);- if (!agentConfig) return undefined;- return {- avatar: agentConfig.avatar,- id: agentId,- model: agentConfig.model,- provider: agentConfig.provider,- title: agentConfig.title,- };+ getAgentDisplayInfo(...args: StageArgs<typeof getAgentDisplayInfo>) {+ return getAgentDisplayInfo(this.deps, ...args);}- async recordTrajectoryCompletion(params: {- runId: string;- status?: string;- telemetry: {- completionReason?: string;- cost?: number;- duration?: number;- errorDetail?: unknown;- errorMessage?: string;- llmCalls?: number;- steps?: number;- toolCalls?: number;- totalTokens?: number;- };- testCaseId: string;- }): Promise<{ allDone: boolean; completedCount: number }> {- const { runId, testCaseId, telemetry, status } = params;-- // Write runtime telemetry to RunTopic- const runTopic = await this.runTopicModel.findByRunAndTestCase(runId, testCaseId);- if (runTopic) {- // Skip if topic is already in a terminal state (e.g. timeout marked by checkAndHandleRunTimeout).- // The interrupted agent still fires the completion webhook, but we must not overwrite the result.- const terminalStates = ['passed', 'failed', 'error', 'timeout', 'external'];- if (runTopic.status && terminalStates.includes(runTopic.status)) {- // Fall through to progress tracking below without modifying this topic- } else {- // Build merged evalResult with telemetry data β use this as base for all subsequent writes- const evalResultWithTelemetry: EvalRunTopicResult = {- ...runTopic.evalResult,- completionReason: telemetry.completionReason,- cost: telemetry.cost != null ? roundCost(telemetry.cost) : undefined,- duration: telemetry.duration,- llmCalls: telemetry.llmCalls,- rubricScores: runTopic.evalResult?.rubricScores,- steps: telemetry.steps,- tokens: telemetry.totalTokens,- toolCalls: telemetry.toolCalls,- };-- await this.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {- evalResult: evalResultWithTelemetry,- });-- if (status === 'error') {- // Short-circuit: execution error β skip evaluation, write error directly- await this.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {- evalResult: {- ...evalResultWithTelemetry,- error:- telemetry.errorMessage ||- `Execution error: ${telemetry.completionReason || 'unknown'}`,- errorDetail: telemetry.errorDetail,- },- passed: false,- score: 0,- status: 'error',- });- } else {- // Per-case evaluation: immediately evaluate this case against rubrics- try {- await this.evaluateCase(runId, { ...runTopic, evalResult: evalResultWithTelemetry });- } catch (e) {- // Evaluation failure should not block telemetry or progress tracking- console.error(e);- }- }- }- }-- // Get run to read totalCases- const run = await this.runModel.findById(runId);- if (!run) return { allDone: false, completedCount: 0 };-- const totalCases = run.metrics?.totalCases;- if (!totalCases) return { allDone: false, completedCount: 0 };-- // Aggregate real-time metrics from all RunTopics- const allTopics = await this.runTopicModel.findByRunId(runId);- const completedCount = allTopics.filter(- (t) =>- (t.evalResult && 'completionReason' in t.evalResult) ||- t.status === 'timeout' ||- t.status === 'external',- ).length;- const passedCases = allTopics.filter((t) => t.status === 'passed').length;- const failedCases = allTopics.filter((t) => t.status === 'failed').length;- const errorCases = allTopics.filter((t) => t.status === 'error').length;- const externalCasesTraj = allTopics.filter((t) => t.status === 'external').length;- const timeoutCases = allTopics.filter((t) => t.status === 'timeout').length;-- let sumCost = 0;- let sumTokens = 0;- let sumSteps = 0;- let sumLlmCalls = 0;- let sumToolCalls = 0;- let actualTotalCost = 0;- let actualTotalTokens = 0;- let actualTotalDuration = 0;- for (const t of allTopics) {- const r = t.evalResult as Record<string, unknown> | null;- if (r && ('completionReason' in r || t.status === 'timeout')) {- if (typeof r.cost === 'number') sumCost += r.cost;- if (typeof r.tokens === 'number') sumTokens += r.tokens;- if (typeof r.steps === 'number') sumSteps += r.steps;- if (typeof r.llmCalls === 'number') sumLlmCalls += r.llmCalls;- if (typeof r.toolCalls === 'number') sumToolCalls += r.toolCalls;- const rTotalCost =- typeof r.totalCost === 'number' ? r.totalCost : typeof r.cost === 'number' ? r.cost : 0;- const rTotalTokens =- typeof r.totalTokens === 'number'- ? r.totalTokens- : typeof r.tokens === 'number'- ? r.tokens- : 0;- const rTotalDuration =- typeof r.totalDuration === 'number'- ? r.totalDuration- : typeof r.duration === 'number'- ? r.duration- : 0;- actualTotalCost += rTotalCost;- actualTotalTokens += rTotalTokens;- actualTotalDuration += rTotalDuration;- }- }-- // Update run metrics with real-time counts- await this.runModel.update(runId, {- metrics: {- ...(run.metrics as EvalRunMetrics),- completedCases: completedCount,- cost: sumCost ? roundCost(sumCost) : undefined,- errorCases,- externalCases: externalCasesTraj || undefined,- failedCases,- llmCalls: sumLlmCalls || undefined,- passedCases,- perCaseCost: sumCost && completedCount ? roundCost(sumCost / completedCount) : undefined,- perCaseLlmCalls:- sumLlmCalls && completedCount- ? Math.round((sumLlmCalls / completedCount) * 10) / 10- : undefined,- perCaseSteps:- sumSteps && completedCount- ? Math.round((sumSteps / completedCount) * 10) / 10- : undefined,- perCaseTokens:- sumTokens && completedCount ? Math.round(sumTokens / completedCount) : undefined,- perCaseToolCalls:- sumToolCalls && completedCount- ? Math.round((sumToolCalls / completedCount) * 10) / 10- : undefined,- steps: sumSteps || undefined,- timeoutCases,- tokens: sumTokens || undefined,- toolCalls: sumToolCalls || undefined,- totalCost: actualTotalCost ? roundCost(actualTotalCost) : undefined,- totalDuration: actualTotalDuration || undefined,- totalTokens: actualTotalTokens || undefined,- },- });-- return { allDone: completedCount >= totalCases, completedCount };+ recordTrajectoryCompletion(...args: StageArgs<typeof recordTrajectoryCompletion>) {+ return recordTrajectoryCompletion(this.deps, ...args);}evaluateAndFinalizeRun = evaluateAndFinalizeRun;- private async evaluateCase(- runId: string,- runTopic: {- evalResult?: EvalRunTopicResult | null;- runId: string;- testCase?: { content?: any; evalConfig?: any; evalMode?: string | null } | null;- topicId: string;- },- ) {- // Resolve eval context: run β dataset β benchmark- const run = await this.runModel.findById(runId);- if (!run) return;-- const dataset = await this.datasetModel.findById(run.datasetId);- if (!dataset) return;-- const benchmark = dataset.benchmarkId- ? await this.benchmarkModel.findById(dataset.benchmarkId)- : null;-- const passThreshold = (run.config?.passThreshold as number) ?? 0.6;- const benchmarkRubrics = benchmark?.rubrics ?? [];-- // Get messages for this topic- const messages = await this.messageModel.query({ topicId: runTopic.topicId });- const assistantMessages = messages.filter((m: { role: string }) => m.role === 'assistant');- const lastAssistantMsg = assistantMessages.at(-1);-- const existingResult = runTopic.evalResult;-- if (!lastAssistantMsg || !lastAssistantMsg.content) {- await this.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {- evalResult: { ...existingResult, error: 'No assistant output', rubricScores: [] },- passed: false,- score: 0,- status: 'error',- });- return;- }-- const testCase = runTopic.testCase;- if (!testCase) return;-- // Resolve rubrics: TestCase evalMode > Dataset evalMode > Benchmark rubrics- const evalMode = (testCase.evalMode ?? dataset.evalMode) as RubricType | null | undefined;- const evalConfig = testCase.evalConfig ?? dataset.evalConfig;-- // ββ External eval mode: agent finished, hand off to external scorer ββ- if (evalMode === 'external') {- await this.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {- evalResult: { ...existingResult, awaitingExternalEval: true },- status: 'external',- });- return;- }-- let effectiveRubrics: EvalBenchmarkRubric[];- if (evalMode) {- effectiveRubrics = [- {- config: (evalConfig ?? {}) as unknown as EvalBenchmarkRubric['config'],- id: `eval-mode-${evalMode}`,- name: evalMode,- type: evalMode,- weight: 1,- },- ];- } else {- effectiveRubrics = benchmarkRubrics ?? [];- }-- // No rubrics to evaluate against β skip evaluation entirely- if (effectiveRubrics.length === 0) return;-- // Run evaluation- const result = await evaluate(- { actual: lastAssistantMsg.content, rubrics: effectiveRubrics, testCase: testCase.content },- { passThreshold },- );-- const evalResult: EvalRunTopicResult = {- ...existingResult,- rubricScores: result.rubricResults.map((r) => ({- reason: r.reason,- rubricId: r.rubricId,- score: r.score,- })),- };-- // Write results to RunTopic- await this.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {- evalResult,- passed: result.passed,- score: result.score,- status: result.passed ? 'passed' : 'failed',- });- }-/*** Check each pending RunTopic individually against the per-case timeout.* If a topic's createdAt + timeout has elapsed, mark it as 'timeout' and write duration.* If all topics reach terminal state after this, finalize the run (aggregate metrics + mark completed).* Returns true if any state was changed.*/- async checkAndHandleRunTimeout(run: {- config?: EvalRunConfig | null;- id: string;- metrics?: EvalRunMetrics | null;- startedAt?: Date | null;- }): Promise<boolean> {- const perCaseTimeout = (run.config?.timeout as number) ?? 1_200_000; // 20 min default- const now = Date.now();-- // Early exit: if run started less than timeout ago, no topic could have timed out- if (run.startedAt && now - new Date(run.startedAt).getTime() < perCaseTimeout) {- return false;- }-- // Single SQL: mark pending topics where created_at + timeout < NOW() as 'timeout'- const timedOutRows = await this.runTopicModel.batchMarkTimeout(run.id, perCaseTimeout);- if (timedOutRows.length === 0) return false;-- // Interrupt running agents before writing timeout state (best-effort)- const agentRuntimeService = new AgentRuntimeService(this.db, this.userId);- for (const row of timedOutRows) {- const opId = (row.evalResult as EvalRunTopicResult)?.operationId;- if (opId) {- try {- await agentRuntimeService.interruptOperation(opId);- } catch {- // best effort β don't block timeout handling- }- }- }-- // Write evalResult with duration for each timed-out topic- for (const row of timedOutRows) {- const duration = row.createdAt ? now - new Date(row.createdAt).getTime() : undefined;- await this.runTopicModel.updateByRunAndTopic(row.runId, row.topicId, {- evalResult: {- ...(row.evalResult as EvalRunTopicResult),- completionReason: 'timeout',- duration,- rubricScores: (row.evalResult as EvalRunTopicResult)?.rubricScores ?? [],- },- passed: false,- score: 0,- });- }-- // Re-aggregate metrics from all RunTopics (including newly timed-out ones)- const allTopics = await this.runTopicModel.findByRunId(run.id);- const pendingCount = allTopics.filter(- (t) => !t.status || t.status === 'pending' || t.status === 'running',- ).length;-- if (pendingCount === 0) {- // All topics in terminal state β finalize with full metrics- const metrics = await this.evaluateAndFinalizeRun({- run: { id: run.id, metrics: run.metrics, startedAt: run.startedAt },- runTopics: allTopics,- });-- const nonSuccessCases = (metrics.errorCases || 0) + (metrics.timeoutCases || 0);- const externalCount = metrics.externalCases || 0;- const runStatus =- externalCount > 0- ? 'external'- : nonSuccessCases >= metrics.totalCases- ? 'failed'- : 'completed';-- await this.runModel.update(run.id, { metrics, status: runStatus });- } else {- // Some topics still running β update real-time metrics so progress reflects timeouts- const completedCount = allTopics.filter(- (t) => (t.evalResult && 'completionReason' in t.evalResult) || t.status === 'timeout',- ).length;- const passedCases = allTopics.filter((t) => t.status === 'passed').length;- const failedCases = allTopics.filter((t) => t.status === 'failed').length;- const errorCases = allTopics.filter((t) => t.status === 'error').length;- const timeoutCases = allTopics.filter((t) => t.status === 'timeout').length;-- await this.runModel.update(run.id, {- metrics: {- ...(run.metrics as EvalRunMetrics),- completedCases: completedCount,- errorCases,- failedCases,- passedCases,- timeoutCases,- },- });- }-- return true;- }-- private async snapshotAgentConfig(agentId: string): Promise<EvalRunAgentSnapshot | undefined> {- const agentConfig = await this.agentService.getAgentConfigById(agentId);- if (!agentConfig) return undefined;-- return {- avatar: agentConfig.avatar,- chatConfig: agentConfig.chatConfig as unknown as Record<string, unknown>,- description: null,- fewShots: agentConfig.fewShots,- model: agentConfig.model,- params: agentConfig.params as Record<string, unknown>,- // Pinned identifiers only β this snapshot is a display-only DTO- // (EvalRunAgentSnapshot.plugins stays string[]), and a disabled entry- // isn't part of what actually ran.- plugins: getActivePluginIds(agentConfig.plugins),- provider: agentConfig.provider,- systemRole: agentConfig.systemRole,- title: agentConfig.title,- };+ checkAndHandleRunTimeout(...args: StageArgs<typeof checkAndHandleRunTimeout>) {+ return checkAndHandleRunTimeout(this.deps, ...args);}}diff --git a/apps/server/src/services/agentEvalRun/resumeExecution.ts b/apps/server/src/services/agentEvalRun/resumeExecution.tsnew file mode 100644index 00000000000..53e7d897ec4--- /dev/null+++ b/apps/server/src/services/agentEvalRun/resumeExecution.ts@@ -0,0 +1,313 @@+import type { EvalThreadResult } from '@lobechat/types';+import { RequestTrigger } from '@lobechat/types';++import { AiAgentService } from '@/server/services/aiAgent';+import {+ AgentEvalRunWorkflow,+ type ResumeAgentTrajectoryPayload,+ type ResumeThreadTrajectoryPayload,+} from '@/server/workflows/agentEvalRun';++import { recordTrajectoryCompletion } from './completion';+import { createEvalRunDeps } from './deps';+import { canResumeTrajectory } from './resumeTarget';+import { recordThreadCompletion } from './thread';+import type { EvalRunDeps } from './types';+import { getEvalContextParams, log } from './utils';++const resetResumedThreadResult = (thread: EvalThreadResult): EvalThreadResult => ({+ threadId: thread.threadId,+ status: thread.status === 'external' ? 'external' : 'running',+});++/**+ * Resume a timed-out single-agent trajectory (pass@1).+ * Claims the runTopic via CAS (timeout β running) for idempotency, then+ * calls execAgent with resume=true so the runtime continues from parentMessageId.+ */+export async function executeResumedTrajectory(+ deps: EvalRunDeps,+ params: ResumeAgentTrajectoryPayload,+) {+ const {+ appContext,+ envPrompt,+ maxSteps,+ parentMessageId,+ runId,+ targetAgentId,+ testCaseId,+ topicId,+ environment,+ } = params;++ const resumeCheck = await canResumeTrajectory(deps, { runId, testCaseId });+ if (!resumeCheck.canResume) {+ return { reason: resumeCheck.reason, status: 'cancelled' as const, topicId };+ }++ // Look up the pre-created RunTopic and reset it for resume+ log(+ 'executeResumedTrajectory: run=%s testCase=%s topicId=%s parentMessageId=%s',+ runId,+ testCaseId,+ topicId,+ parentMessageId,+ );+ const runTopic = await deps.runTopicModel.findByRunAndTestCase(runId, testCaseId);+ if (!runTopic) {+ throw new Error(`RunTopic not found for run=${runId} testCase=${testCaseId}`);+ }++ // Capture accumulated telemetry from previous runs before clearing evalResult+ const prevSteps = runTopic.evalResult?.steps ?? 0;+ const prevCost = runTopic.evalResult?.cost ?? 0;+ const prevLlmCalls = runTopic.evalResult?.llmCalls ?? 0;+ const prevToolCalls = runTopic.evalResult?.toolCalls ?? 0;+ const prevTokens = runTopic.evalResult?.tokens ?? 0;+ log('executeResumedTrajectory: prev telemetry steps=%d cost=%d', prevSteps, prevCost);+ const now = new Date();++ await deps.runTopicModel.updateByRunAndTopic(runId, topicId, {+ createdAt: now, // reset for timeout tracking β resume is a fresh time window+ evalResult: null,+ passed: null,+ score: null,+ status: 'running',+ });++ await deps.runModel.update(runId, { startedAt: now, status: 'running' });++ const aiAgentService = new AiAgentService(deps.db, deps.userId, {+ workspaceId: deps.workspaceId,+ });+ const webhookUrl = '/api/workflows/agent-eval-run/on-trajectory-complete';+ const userId = deps.userId;+ const db = deps.db;++ try {+ const execResult = await aiAgentService.execAgent({+ agentId: targetAgentId,+ appContext,+ autoStart: true,+ trigger: RequestTrigger.Eval,+ hooks: [+ {+ handler: async (event) => {+ // Local mode: directly record completion+ await recordTrajectoryCompletion(createEvalRunDeps(db, userId, deps.workspaceId), {+ runId,+ status: event.status || event.reason || 'done',+ telemetry: {+ completionReason: event.reason,+ cost: (event.cost ?? 0) + prevCost,+ duration: event.duration,+ errorDetail: event.errorDetail,+ errorMessage: event.errorMessage,+ llmCalls: (event.llmCalls ?? 0) + prevLlmCalls,+ steps: (event.steps ?? 0) + prevSteps,+ toolCalls: (event.toolCalls ?? 0) + prevToolCalls,+ totalTokens: (event.totalTokens ?? 0) + prevTokens,+ },+ testCaseId,+ });+ },+ id: 'eval-trajectory-complete',+ type: 'onComplete' as const,+ webhook: {+ body: { runId, testCaseId, userId },+ delivery: 'qstash' as const,+ url: webhookUrl,+ },+ },+ ],+ ...getEvalContextParams(envPrompt, environment, params.caseId),+ initialStepCount: prevSteps,+ maxSteps,+ parentMessageId,+ prompt: '',+ resume: true,+ userInterventionConfig: { approvalMode: 'headless' },+ });++ if (execResult?.operationId) {+ await deps.runTopicModel.updateByRunAndTopic(runId, topicId, {+ evalResult: { operationId: execResult.operationId, rubricScores: [] },+ });+ }++ return { status: 'started' as const, topicId };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : 'Agent execution failed to start';+ console.error(+ `[resume-agent-trajectory] execAgent failed for run=${runId} testCase=${testCaseId}:`,+ error,+ );++ // Record error and finalize the run if all test cases are done+ const { allDone } = await recordTrajectoryCompletion(deps, {+ runId,+ status: 'error',+ telemetry: { completionReason: 'error', errorMessage },+ testCaseId,+ });++ if (allDone) {+ await AgentEvalRunWorkflow.triggerFinalizeRun({ runId, userId: deps.userId });+ }++ return { reason: errorMessage, status: 'error' as const, topicId };+ }+}++/**+ * Resume a timed-out thread trajectory (pass@k).+ * Claims the runTopic via CAS (timeout β running) for idempotency, then+ * calls execAgent with resume=true so the runtime continues from parentMessageId.+ */+export async function executeResumedThreadTrajectory(+ deps: EvalRunDeps,+ params: ResumeThreadTrajectoryPayload,+) {+ const {+ appContext,+ caseId,+ envPrompt,+ maxSteps,+ parentMessageId,+ runId,+ targetAgentId,+ testCaseId,+ threadId,+ environment,+ topicId,+ } = params;++ const resumeCheck = await canResumeTrajectory(deps, { runId, testCaseId, threadId });+ if (!resumeCheck.canResume) {+ return { reason: resumeCheck.reason, status: 'cancelled' as const, threadId, topicId };+ }++ // Look up the pre-created RunTopic and reset it for resume+ const runTopic = await deps.runTopicModel.findByRunAndTestCase(runId, testCaseId);+ if (!runTopic) {+ throw new Error(`RunTopic not found for run=${runId} testCase=${testCaseId}`);+ }++ const currentThread = await deps.threadModel.findById(threadId);+ const currentThreadMeta = (currentThread?.metadata ?? {}) as Record<string, unknown>;+ const prevThreads = runTopic.evalResult?.threads ?? [];+ const nextThreads = prevThreads.some((thread) => thread.threadId === threadId)+ ? prevThreads.map((thread) =>+ thread.threadId === threadId ? resetResumedThreadResult(thread) : thread,+ )+ : [...prevThreads, { status: 'running' as const, threadId }];++ // Capture accumulated telemetry from the target thread only+ const prevSteps = (currentThreadMeta.steps as number | undefined) ?? 0;+ const prevCost = (currentThreadMeta.cost as number | undefined) ?? 0;+ const prevLlmCalls = (currentThreadMeta.llmCalls as number | undefined) ?? 0;+ const prevToolCalls = (currentThreadMeta.toolCalls as number | undefined) ?? 0;+ const prevTokens = (currentThreadMeta.tokens as number | undefined) ?? 0;+ const now = new Date();++ await deps.runTopicModel.updateByRunAndTopic(runId, topicId, {+ createdAt: now,+ evalResult: { threads: nextThreads },+ passed: null,+ score: null,+ status: 'running',+ });++ await deps.threadModel.update(threadId, {+ metadata: { testCaseId } as any,+ });++ await deps.runModel.update(runId, { startedAt: now, status: 'running' });++ const aiAgentService = new AiAgentService(deps.db, deps.userId, {+ workspaceId: deps.workspaceId,+ });+ const webhookUrl = '/api/workflows/agent-eval-run/on-thread-complete';+ const userId = deps.userId;+ const db = deps.db;++ try {+ const execResult = await aiAgentService.execAgent({+ agentId: targetAgentId,+ appContext,+ autoStart: true,+ trigger: RequestTrigger.Eval,+ hooks: [+ {+ handler: async (event) => {+ // Local mode: directly record thread completion+ await recordThreadCompletion(createEvalRunDeps(db, userId, deps.workspaceId), {+ runId,+ status: event.status || event.reason || 'done',+ telemetry: {+ completionReason: event.reason,+ cost: (event.cost ?? 0) + prevCost,+ duration: event.duration,+ errorMessage: event.errorMessage,+ llmCalls: (event.llmCalls ?? 0) + prevLlmCalls,+ steps: (event.steps ?? 0) + prevSteps,+ toolCalls: (event.toolCalls ?? 0) + prevToolCalls,+ totalTokens: (event.totalTokens ?? 0) + prevTokens,+ },+ testCaseId,+ threadId,+ topicId,+ });+ },+ id: 'eval-thread-complete',+ type: 'onComplete' as const,+ webhook: {+ body: { runId, testCaseId, threadId, topicId, userId },+ delivery: 'qstash' as const,+ url: webhookUrl,+ },+ },+ ],+ ...getEvalContextParams(envPrompt, environment, caseId),+ initialStepCount: prevSteps,+ maxSteps,+ parentMessageId,+ prompt: '',+ resume: true,+ userInterventionConfig: { approvalMode: 'headless' },+ });++ // Write operationId to thread metadata+ if (execResult?.operationId) {+ await deps.threadModel.update(threadId, {+ metadata: { operationId: execResult.operationId, testCaseId } as any,+ });+ }++ return { status: 'started' as const, threadId, topicId };+ } catch (error) {+ const errorMessage =+ error instanceof Error ? error.message : 'Thread execution failed to start';+ console.error(+ `[resume-thread-trajectory] execAgent failed for run=${runId} thread=${threadId}:`,+ error,+ );++ // Record error and finalize the run if all test cases are done+ const { allRunDone } = await recordThreadCompletion(deps, {+ runId,+ status: 'error',+ telemetry: { completionReason: 'error', errorMessage },+ testCaseId,+ threadId,+ topicId,+ });++ if (allRunDone) {+ await AgentEvalRunWorkflow.triggerFinalizeRun({ runId, userId: deps.userId });+ }++ return { reason: errorMessage, status: 'error' as const, threadId, topicId };+ }+}diff --git a/apps/server/src/services/agentEvalRun/resumeTarget.ts b/apps/server/src/services/agentEvalRun/resumeTarget.tsnew file mode 100644index 00000000000..438dfbaf44d--- /dev/null+++ b/apps/server/src/services/agentEvalRun/resumeTarget.ts@@ -0,0 +1,414 @@+import { LOADING_FLAT } from '@lobechat/const';+import type { EvalRunTopicResult, EvalThreadResult } from '@lobechat/types';+import pMap from 'p-map';++import type { ThreadModel } from '@/database/models/thread';+import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';++import { loadTrajectoryData } from './trajectory';+import type { EvalRunDeps } from './types';+import { getCaseId, log } from './utils';++const RESUMABLE_THREAD_STATUSES = new Set(['error', 'timeout']);+/** Caps concurrent per-case resume checks (each issues several DB reads). */+const RESUME_CHECK_CONCURRENCY = 5;++interface ResumableCaseTarget {+ caseStatus?: string | null;+ input: string;+ resumeStatus?: 'error' | 'timeout';+ sortOrder: number | null;+ testCaseId: string;+ threadId?: string;+}++interface ResumableThreadResult extends EvalThreadResult {+ status: 'error' | 'timeout';+}++export async function canResumeTrajectory(+ deps: EvalRunDeps,+ params: { runId: string; testCaseId: string; threadId?: string },+) {+ const invalidResumeTargetReason = 'Invalid resume target';+ const trajectoryNotResumableReason = 'Trajectory is not resumable';+ const resumeLimitReachedReason = 'Resume limit reached';++ log('canResumeTrajectory: %O', params);+ const run = await deps.runModel.findById(params.runId);+ if (!run) return { canResume: false, reason: invalidResumeTargetReason };++ if (!['aborted', 'failed', 'running'].includes(run.status)) {+ return { canResume: false, reason: trajectoryNotResumableReason };+ }++ const runTopic = await deps.runTopicModel.findByRunAndTestCase(params.runId, params.testCaseId);+ if (!runTopic) return { canResume: false, reason: invalidResumeTargetReason };++ log('canResumeTrajectory: runTopic.status=%s topicId=%s', runTopic.status, runTopic.topicId);++ const k = run.config?.k ?? 1;+ const hasInvalidThreadTarget = (k === 1 && !!params.threadId) || (k > 1 && !params.threadId);+ if (hasInvalidThreadTarget) {+ return { canResume: false, reason: invalidResumeTargetReason };+ }++ if (!runTopic.topicId) {+ return { canResume: false, reason: invalidResumeTargetReason };+ }++ if (k === 1 && !RESUMABLE_THREAD_STATUSES.has(runTopic.status ?? '')) {+ log('canResumeTrajectory: rejected β runTopic.status=%s', runTopic.status);+ return { canResume: false, reason: trajectoryNotResumableReason };+ }++ if (params.threadId) {+ const thread = await deps.threadModel.findById(params.threadId);++ if (!thread || thread.topicId !== runTopic.topicId || thread.type !== 'eval') {+ return { canResume: false, reason: invalidResumeTargetReason };+ }++ const targetThread = runTopic.evalResult?.threads?.find(+ (item) => item.threadId === params.threadId,+ );++ if (!targetThread || !RESUMABLE_THREAD_STATUSES.has(targetThread.status ?? '')) {+ return { canResume: false, reason: trajectoryNotResumableReason };+ }++ const maxSteps = run.config?.maxSteps;+ const prevSteps =+ ((thread.metadata as Record<string, unknown> | null)?.steps as number | undefined) ?? 0;++ if (maxSteps && prevSteps >= maxSteps) {+ log(+ 'canResumeTrajectory: rejected thread β prevSteps=%d >= maxSteps=%d',+ prevSteps,+ maxSteps,+ );+ return { canResume: false, reason: resumeLimitReachedReason };+ }+ }++ // pass@1 resumes track steps on the runTopic; pass@k uses per-thread metadata above.+ if (k > 1) return { canResume: true as const };++ // Reject if the previous run already exhausted maxSteps+ const maxSteps = run.config?.maxSteps;+ const prevSteps = runTopic.evalResult?.steps ?? 0;+ if (maxSteps && prevSteps >= maxSteps) {+ log('canResumeTrajectory: rejected β prevSteps=%d >= maxSteps=%d', prevSteps, maxSteps);+ return { canResume: false, reason: resumeLimitReachedReason };+ }++ return { canResume: true as const };+}++/**+ * Batch-check which error/timeout cases in a run can be resumed.+ * Returns one entry per candidate case with canResume + optional reason.+ */+export async function getResumableCases(deps: EvalRunDeps, runId: string) {+ const run = await deps.runModel.findById(runId);+ if (!run) return [];++ const allTopics = await deps.runTopicModel.findByRunId(runId);+ const k = run.config?.k ?? 1;+ const candidates = allTopics+ .map((topic) => getResumableCaseTarget(topic, k))+ .filter((topic): topic is ResumableCaseTarget => !!topic);++ const results = await pMap(+ candidates,+ async (candidate) => {+ const check = await canResumeTrajectory(deps, {+ runId,+ testCaseId: candidate.testCaseId,+ threadId: candidate.threadId,+ });+ return {+ caseStatus: candidate.caseStatus,+ canResume: check.canResume,+ input: candidate.input,+ reason: 'reason' in check ? check.reason : undefined,+ resumeStatus: candidate.resumeStatus,+ sortOrder: candidate.sortOrder,+ testCaseId: candidate.testCaseId,+ threadId: candidate.threadId,+ };+ },+ { concurrency: RESUME_CHECK_CONCURRENCY },+ );++ return results;+}++export async function resumeTrajectory(+ deps: EvalRunDeps,+ params: { runId: string; testCaseId: string; threadId?: string },+) {+ log('resumeTrajectory: %O', params);+ const resumeCheck = await canResumeTrajectory(deps, params);+ if (!resumeCheck.canResume) {+ log('resumeTrajectory: canResume=false reason=%s', resumeCheck.reason);+ throw new Error(resumeCheck.reason);+ }++ const target = await resolveTrajectoryResumeTarget(deps, params);+ const { caseId, envPrompt, environment, parentMessageId, run, thread, topicId } = target;+ log(+ 'resumeTrajectory: resolved target β topicId=%s parentMessageId=%s threadId=%s',+ topicId,+ parentMessageId,+ thread?.id,+ );++ if (thread) {+ log('resumeTrajectory: triggering resume-thread-trajectory');+ await AgentEvalRunWorkflow.triggerResumeThreadTrajectory({+ appContext: { threadId: thread.id, topicId },+ caseId,+ envPrompt,+ maxSteps: run.config?.maxSteps,+ parentMessageId,+ runId: run.id,+ targetAgentId: run.targetAgentId ?? undefined,+ testCaseId: params.testCaseId,+ threadId: thread.id,+ topicId,+ environment,+ userId: deps.userId,+ });+ } else {+ log('resumeTrajectory: triggering resume-agent-trajectory');+ await AgentEvalRunWorkflow.triggerResumeAgentTrajectory({+ appContext: { topicId },+ caseId,+ envPrompt,+ maxSteps: run.config?.maxSteps,+ parentMessageId,+ runId: run.id,+ targetAgentId: run.targetAgentId ?? undefined,+ testCaseId: params.testCaseId,+ topicId,+ environment,+ userId: deps.userId,+ });+ }++ const result = {+ mode: thread ? ('thread' as const) : ('single' as const),+ runId: run.id,+ testCaseId: params.testCaseId,+ threadId: thread?.id,+ topicId,+ triggered: true,+ };+ log('resumeTrajectory: done %O', result);+ return result;+}++function getResumableCaseTarget(+ runTopic: {+ evalResult?: EvalRunTopicResult | null;+ status?: string | null;+ testCase?: { content?: { input?: string } | null; sortOrder?: number | null } | null;+ testCaseId: string;+ },+ k: number,+): ResumableCaseTarget | undefined {+ if (k === 1) {+ if (!RESUMABLE_THREAD_STATUSES.has(runTopic.status ?? '')) return undefined;++ return {+ caseStatus: runTopic.status,+ input: runTopic.testCase?.content?.input ?? '',+ resumeStatus: runTopic.status as 'error' | 'timeout',+ sortOrder: runTopic.testCase?.sortOrder ?? null,+ testCaseId: runTopic.testCaseId,+ };+ }++ const resumableThread = getResumableThread(runTopic.evalResult?.threads);+ if (!resumableThread?.status) return undefined;++ return {+ caseStatus: runTopic.status,+ input: runTopic.testCase?.content?.input ?? '',+ resumeStatus: resumableThread.status,+ sortOrder: runTopic.testCase?.sortOrder ?? null,+ testCaseId: runTopic.testCaseId,+ threadId: resumableThread.threadId,+ };+}++function getResumableThread(threads?: EvalThreadResult[]) {+ return threads?.find((thread): thread is ResumableThreadResult =>+ RESUMABLE_THREAD_STATUSES.has(thread.status ?? ''),+ );+}++async function resolveTrajectoryResumeTarget(+ deps: EvalRunDeps,+ params: {+ runId: string;+ testCaseId: string;+ threadId?: string;+ },+) {+ log(+ 'resolveTrajectoryResumeTarget: run=%s testCase=%s thread=%s',+ params.runId,+ params.testCaseId,+ params.threadId,+ );+ const loaded = await loadTrajectoryData(deps, params.runId, params.testCaseId);+ if ('error' in loaded) {+ throw new Error(loaded.error);+ }++ const { envPrompt, environment, run, testCase } = loaded;+ const runTopic = await deps.runTopicModel.findByRunAndTestCase(params.runId, params.testCaseId);+ if (!runTopic?.topicId) throw new Error('RunTopic topicId is required');++ log(+ 'resolveTrajectoryResumeTarget: topicId=%s runTopic.status=%s',+ runTopic.topicId,+ runTopic.status,+ );++ let thread: Awaited<ReturnType<ThreadModel['findById']>> | undefined;++ if (params.threadId) {+ thread = await deps.threadModel.findById(params.threadId);+ if (!thread) throw new Error('Thread not found');+ }++ const { danglingIds, parentMessageId } = await resolveResumeParentMessageId(deps, {+ threadId: thread?.id,+ topicId: runTopic.topicId,+ });++ log(+ 'resolveTrajectoryResumeTarget: parentMessageId=%s danglingIds=%d',+ parentMessageId,+ danglingIds.length,+ );++ // Remove dangling partial messages before resume so the context engine (which+ // re-fetches all topic messages after every tool-call batch) cannot include them.+ if (danglingIds.length > 0) {+ log(+ 'resolveTrajectoryResumeTarget: deleting %d dangling messages: %O',+ danglingIds.length,+ danglingIds,+ );+ await deps.messageModel.deleteMessages(danglingIds);+ }++ return {+ appContext: thread+ ? { threadId: thread.id, topicId: runTopic.topicId }+ : { topicId: runTopic.topicId },+ caseId: getCaseId(testCase.metadata),+ envPrompt,+ parentMessageId,+ run,+ runTopic,+ thread,+ environment,+ topicId: runTopic.topicId,+ };+}++async function resolveResumeParentMessageId(+ deps: EvalRunDeps,+ params: { threadId?: string; topicId: string },+) {+ log('resolveResumeParentMessageId: topicId=%s threadId=%s', params.topicId, params.threadId);+ const messages = await deps.messageModel.query({+ threadId: params.threadId,+ topicId: params.topicId,+ });++ log('resolveResumeParentMessageId: total messages=%d', messages.length);+ log(+ 'resolveResumeParentMessageId: messages (role, id, contentLen, parentId) = %O',+ messages.map((m) => ({+ role: m.role,+ id: m.id,+ contentLen: m.content?.length ?? 0,+ parentId: (m as any).parentId ?? null,+ })),+ );++ // Strategy:+ // - tool results are always complete (atomic, written after execution succeeds)+ // - assistant messages may be partial (LLM stream interrupted mid-way)+ // So: prefer the last tool result with content as the resume point.+ // Only fall back to assistant / user if no tool result exists.++ let parentMessageId: string | undefined;++ // Pass 1: find the last tool result with content+ for (let index = messages.length - 1; index >= 0; index--) {+ const message = messages[index];+ if (message.role === 'tool' && message.content) {+ log(+ 'resolveResumeParentMessageId: found via tool id=%s contentLen=%d',+ message.id,+ message.content.length,+ );+ parentMessageId = message.id;+ break;+ }+ }++ // Pass 2: no tool result β fall back to last substantive assistant, then user+ if (!parentMessageId) {+ for (let index = messages.length - 1; index >= 0; index--) {+ const message = messages[index];++ if (message.role === 'assistant') {+ if (!message.content || message.content === LOADING_FLAT) {+ log('resolveResumeParentMessageId: skip empty/loading assistant msgId=%s', message.id);+ continue;+ }+ log(+ 'resolveResumeParentMessageId: fallback via assistant id=%s contentLen=%d',+ message.id,+ message.content.length,+ );+ parentMessageId = message.id;+ break;+ }++ if (message.role === 'user') {+ log('resolveResumeParentMessageId: fallback via user id=%s', message.id);+ parentMessageId = message.id;+ break;+ }+ }+ }++ if (!parentMessageId) throw new Error('Unable to resolve a valid resume parent message');++ // Build the valid ancestor chain from parentMessageId up to root.+ // Return danglingIds for the caller to delete β keeping this method side-effect-free.+ const parentIdMap = new Map<string, string | null>();+ for (const m of messages) {+ parentIdMap.set(m.id, (m as any).parentId ?? null);+ }++ const ancestorSet = new Set<string>();+ let cursor: string | null = parentMessageId;+ while (cursor) {+ ancestorSet.add(cursor);+ cursor = parentIdMap.get(cursor) ?? null;+ }++ const danglingIds = messages.map((m) => m.id).filter((id) => !ancestorSet.has(id));++ return { danglingIds, parentMessageId };+}diff --git a/apps/server/src/services/agentEvalRun/runLifecycle.ts b/apps/server/src/services/agentEvalRun/runLifecycle.tsnew file mode 100644index 00000000000..7407a3b3ed3--- /dev/null+++ b/apps/server/src/services/agentEvalRun/runLifecycle.ts@@ -0,0 +1,278 @@+import type { EvalRunConfig, EvalRunMetrics, EvalRunTopicResult } from '@lobechat/types';++import { AgentRuntimeService } from '@/server/services/agentRuntime/AgentRuntimeService';++import { evaluateAndFinalizeRun } from './aggregate';+import { createRunTopics } from './createRun';+import type { EvalRunDeps } from './types';++export async function deleteRun(deps: EvalRunDeps, id: string) {+ // 1. Get associated topics before deletion (cascade will remove run_topics rows)+ const runTopics = await deps.runTopicModel.findByRunId(id);+ const topicIds = runTopics.map((rt) => rt.topicId).filter(Boolean);++ // 2. Delete the run (cascades to run_topics)+ const result = await deps.runModel.delete(id);++ // 3. Delete orphaned topics+ if (topicIds.length > 0) {+ await deps.topicModel.batchDelete(topicIds);+ }++ return result;+}++export async function abortRun(deps: EvalRunDeps, runId: string) {+ // 1. Find all running RunTopics and interrupt their agent operations+ const runTopics = await deps.runTopicModel.findByRunId(runId);+ const runningTopics = runTopics.filter((t) => t.status === 'running');++ if (runningTopics.length > 0) {+ const agentRuntimeService = new AgentRuntimeService(deps.db, deps.userId);+ for (const rt of runningTopics) {+ const opId = (rt.evalResult as EvalRunTopicResult)?.operationId;+ if (opId) {+ try {+ await agentRuntimeService.interruptOperation(opId);+ } catch {+ // best effort+ }+ }+ }+ }++ // 2. Mark all pending/running RunTopics as aborted (error + 'Aborted')+ await deps.runTopicModel.batchMarkAborted(runId);++ // 3. Update run status to aborted+ await deps.runModel.update(runId, { status: 'aborted' });+}++export async function retryErrorCases(+ deps: EvalRunDeps,+ runId: string,+): Promise<{ retryCount: number }> {+ const run = await deps.runModel.findById(runId);+ if (!run) throw new Error('Run not found');++ const allTopics = await deps.runTopicModel.findByRunId(runId);+ const errorTopics = allTopics.filter((t) => t.status === 'error' || t.status === 'timeout');++ if (errorTopics.length === 0) return { retryCount: 0 };++ // Collect test case IDs and info for recreation+ const errorTestCases = errorTopics.map((t) => ({+ content: t.testCase?.content ?? { input: '' },+ id: t.testCaseId,+ sortOrder: t.testCase?.sortOrder ?? null,+ }));++ // 1. Delete error/terminal RunTopics (the filter above excludes active+ // running/pending cases, so only terminal rows are ever removed).+ await deps.runTopicModel.deleteErrorRunTopics(runId);++ // 2. Preserve old Topics (old conversations are kept for audit/history);+ // only the RunTopic association is replaced.+ // 3. Create fresh Topics, histories, and pending RunTopics together.+ await createRunTopics(deps, runId, run.targetAgentId, errorTestCases);++ // 4. Set run status to pending+ await deps.runModel.update(runId, { status: 'pending' });++ return { retryCount: errorTopics.length };+}++export async function retrySingleCase(deps: EvalRunDeps, runId: string, testCaseId: string) {+ const run = await deps.runModel.findById(runId);+ if (!run) throw new Error('Run not found');++ const runTopic = await deps.runTopicModel.findByRunAndTestCase(runId, testCaseId);+ if (!runTopic) throw new Error('RunTopic not found');++ // Active associations must not be replaced β surface a conflict.+ if (runTopic.status === 'running' || runTopic.status === 'pending') {+ throw new Error(`Cannot retry: case is ${runTopic.status}`);+ }++ // 1. Delete old RunTopic association+ await deps.runTopicModel.deleteByRunAndTestCase(runId, testCaseId);++ // 2. Preserve the old Topic (conversation history); only re-link.+ // 3. Create a fresh Topic, its history, and its RunTopic together.+ await createRunTopics(deps, runId, run.targetAgentId, [+ {+ content: runTopic.testCase?.content ?? { input: '' },+ id: testCaseId,+ sortOrder: runTopic.testCase?.sortOrder ?? null,+ },+ ]);++ // 5. Set run status to running+ await deps.runModel.update(runId, { status: 'running' });+}++export async function getRunDetails(deps: EvalRunDeps, id: string) {+ let run = await deps.runModel.findById(id);+ if (!run) return null;++ // Check if a 'running' run has timed out+ if (run.status === 'running') {+ const timedOut = await checkAndHandleRunTimeout(deps, run);+ if (timedOut) {+ run = (await deps.runModel.findById(id))!;+ }+ }++ // Get dataset and run topics in parallel+ const [dataset, runTopics] = await Promise.all([+ deps.datasetModel.findById(run.datasetId),+ deps.runTopicModel.findByRunId(id),+ ]);++ // Get target agent display info via AgentService (fallback for runs without snapshot)+ let targetAgent:+ { avatar?: string; id: string; model?: string; provider?: string; title?: string } | undefined;+ if (run.targetAgentId) {+ const agentConfig = await deps.agentService.getAgentConfigById(run.targetAgentId);+ if (agentConfig) {+ targetAgent = {+ avatar: agentConfig.avatar,+ id: run.targetAgentId,+ model: agentConfig.model,+ provider: agentConfig.provider,+ title: agentConfig.title,+ };+ }+ }++ return {+ ...run,+ dataset,+ targetAgent,+ topics: runTopics.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,+ })),+ };+}++export async function getAgentDisplayInfo(deps: EvalRunDeps, agentId: string) {+ const agentConfig = await deps.agentService.getAgentConfigById(agentId);+ if (!agentConfig) return undefined;+ return {+ avatar: agentConfig.avatar,+ id: agentId,+ model: agentConfig.model,+ provider: agentConfig.provider,+ title: agentConfig.title,+ };+}++/**+ * Check each pending RunTopic individually against the per-case timeout.+ * If a topic's createdAt + timeout has elapsed, mark it as 'timeout' and write duration.+ * If all topics reach terminal state after this, finalize the run (aggregate metrics + mark completed).+ * Returns true if any state was changed.+ */+export async function checkAndHandleRunTimeout(+ deps: EvalRunDeps,+ run: {+ config?: EvalRunConfig | null;+ id: string;+ metrics?: EvalRunMetrics | null;+ startedAt?: Date | null;+ },+): Promise<boolean> {+ const perCaseTimeout = (run.config?.timeout as number) ?? 1_200_000; // 20 min default+ const now = Date.now();++ // Early exit: if run started less than timeout ago, no topic could have timed out+ if (run.startedAt && now - new Date(run.startedAt).getTime() < perCaseTimeout) {+ return false;+ }++ // Single SQL: mark pending topics where created_at + timeout < NOW() as 'timeout'+ const timedOutRows = await deps.runTopicModel.batchMarkTimeout(run.id, perCaseTimeout);+ if (timedOutRows.length === 0) return false;++ // Interrupt running agents before writing timeout state (best-effort)+ const agentRuntimeService = new AgentRuntimeService(deps.db, deps.userId);+ for (const row of timedOutRows) {+ const opId = (row.evalResult as EvalRunTopicResult)?.operationId;+ if (opId) {+ try {+ await agentRuntimeService.interruptOperation(opId);+ } catch {+ // best effort β don't block timeout handling+ }+ }+ }++ // Write evalResult with duration for each timed-out topic+ for (const row of timedOutRows) {+ const duration = row.createdAt ? now - new Date(row.createdAt).getTime() : undefined;+ await deps.runTopicModel.updateByRunAndTopic(row.runId, row.topicId, {+ evalResult: {+ ...(row.evalResult as EvalRunTopicResult),+ completionReason: 'timeout',+ duration,+ rubricScores: (row.evalResult as EvalRunTopicResult)?.rubricScores ?? [],+ },+ passed: false,+ score: 0,+ });+ }++ // Re-aggregate metrics from all RunTopics (including newly timed-out ones)+ const allTopics = await deps.runTopicModel.findByRunId(run.id);+ const pendingCount = allTopics.filter(+ (t) => !t.status || t.status === 'pending' || t.status === 'running',+ ).length;++ if (pendingCount === 0) {+ // All topics in terminal state β finalize with full metrics+ const metrics = await evaluateAndFinalizeRun({+ run: { id: run.id, metrics: run.metrics, startedAt: run.startedAt },+ runTopics: allTopics,+ });++ const nonSuccessCases = (metrics.errorCases || 0) + (metrics.timeoutCases || 0);+ const externalCount = metrics.externalCases || 0;+ const runStatus =+ externalCount > 0+ ? 'external'+ : nonSuccessCases >= metrics.totalCases+ ? 'failed'+ : 'completed';++ await deps.runModel.update(run.id, { metrics, status: runStatus });+ } else {+ // Some topics still running β update real-time metrics so progress reflects timeouts+ const completedCount = allTopics.filter(+ (t) => (t.evalResult && 'completionReason' in t.evalResult) || t.status === 'timeout',+ ).length;+ const passedCases = allTopics.filter((t) => t.status === 'passed').length;+ const failedCases = allTopics.filter((t) => t.status === 'failed').length;+ const errorCases = allTopics.filter((t) => t.status === 'error').length;+ const timeoutCases = allTopics.filter((t) => t.status === 'timeout').length;++ await deps.runModel.update(run.id, {+ metrics: {+ ...(run.metrics as EvalRunMetrics),+ completedCases: completedCount,+ errorCases,+ failedCases,+ passedCases,+ timeoutCases,+ },+ });+ }++ return true;+}diff --git a/apps/server/src/services/agentEvalRun/thread.ts b/apps/server/src/services/agentEvalRun/thread.tsnew file mode 100644index 00000000000..f7b9bd6cb04--- /dev/null+++ b/apps/server/src/services/agentEvalRun/thread.ts@@ -0,0 +1,647 @@+import { evaluate } from '@lobechat/eval-rubric';+import type {+ EvalBenchmarkRubric,+ EvalCaseEnvironment,+ EvalRunConfig,+ EvalRunMetrics,+ EvalRunTopicResult,+ EvalTestCaseMetadata,+ EvalThreadResult,+ RubricType,+} from '@lobechat/types';+import { RequestTrigger } from '@lobechat/types';+import pMap from 'p-map';++import { AiAgentService } from '@/server/services/aiAgent';+import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';++import {+ EVAL_AGENT_RUNTIME_QSTASH_RETRIES,+ EVAL_AGENT_RUNTIME_QSTASH_RETRY_DELAY,+ EVAL_HISTORY_TAIL_METADATA_KEY,+ THREAD_TRIGGER_CONCURRENCY,+} from './constants';+import { createEvalRunDeps } from './deps';+import type { EvalRunDeps } from './types';+import { getCaseId, getEvalContextParams, roundCost } from './utils';++const getThreadResultStatus = (+ evalResult: Record<string, unknown>,+): EvalThreadResult['status'] | undefined => {+ const { status } = evalResult;++ if (status === 'completed' || status === 'error' || status === 'external' || status === 'timeout')+ return status;++ if (evalResult.passed === true) return 'passed';+ if (evalResult.passed === false) return 'failed';++ return undefined;+};++/**+ * Execute a test case with K threads (for pass@k).+ * Creates K threads in the pre-existing topic, then triggers K run-thread-trajectory workflows.+ */+export async function executeMultiThreadTrajectory(+ deps: EvalRunDeps,+ params: {+ k: number;+ run: {+ config?: EvalRunConfig | null;+ datasetId: string;+ targetAgentId?: string | null;+ };+ runId: string;+ testCaseId: string;+ },+) {+ const { k, runId, testCaseId } = params;++ const runTopic = await deps.runTopicModel.findByRunAndTestCase(runId, testCaseId);+ if (!runTopic) {+ throw new Error(`RunTopic not found for run=${runId} testCase=${testCaseId}`);+ }++ const topicId = runTopic.topicId;+ const topic = await deps.topicModel.findById(topicId);+ const historyTailMessageId = topic?.metadata?.[EVAL_HISTORY_TAIL_METADATA_KEY];+ const sourceMessageId =+ typeof historyTailMessageId === 'string' ? historyTailMessageId : undefined;++ // Update status from 'pending' to 'running'+ await deps.runTopicModel.updateByRunAndTopic(runId, topicId, { status: 'running' });++ // Create K threads in the topic+ const threadIds: string[] = [];+ for (let i = 0; i < k; i++) {+ const thread = await deps.threadModel.create({+ sourceMessageId,+ topicId,+ type: 'eval',+ });+ if (thread) threadIds.push(thread.id);+ }++ await deps.runTopicModel.updateByRunAndTopic(runId, topicId, {+ evalResult: {+ // Persist thread ids before fan-out so pass@k UIs can render attempts immediately.+ ...(runTopic.evalResult as EvalRunTopicResult | null),+ threads: threadIds.map((threadId) => ({+ status: 'running' as const,+ threadId,+ })),+ } satisfies EvalRunTopicResult,+ });++ // Trigger K run-thread-trajectory workflows with a bounded fan-out. Every+ // thread above is already persisted as running, so one failed dispatch must+ // not stop the rest from being attempted; the first failure is rethrown once+ // all triggers have settled, matching the previous Promise.all rejection.+ let firstTriggerError: { error: unknown } | undefined;+ await pMap(+ threadIds,+ async (threadId) => {+ try {+ await AgentEvalRunWorkflow.triggerRunThreadTrajectory({+ runId,+ testCaseId,+ threadId,+ topicId,+ userId: deps.userId,+ });+ } catch (error) {+ firstTriggerError ??= { error };+ }+ },+ { concurrency: THREAD_TRIGGER_CONCURRENCY },+ );+ if (firstTriggerError) throw firstTriggerError.error;++ return { threadIds, topicId };+}++/**+ * Execute a single thread trajectory (for pass@k).+ * Calls execAgent with topicId + threadId, webhook points to on-thread-complete.+ */+export async function executeThreadTrajectory(+ deps: EvalRunDeps,+ params: {+ envPrompt?: string;+ run: {+ config?: EvalRunConfig | null;+ targetAgentId?: string | null;+ };+ runId: string;+ testCase: {+ content: { input?: string };+ metadata?: EvalTestCaseMetadata | null;+ sortOrder?: number | null;+ };+ testCaseId: string;+ threadId: string;+ topicId: string;+ environment?: EvalCaseEnvironment;+ },+) {+ const { envPrompt, environment, run, runId, testCaseId, threadId, topicId } = params;+ const caseId = getCaseId(params.testCase.metadata);++ const aiAgentService = new AiAgentService(deps.db, deps.userId, {+ workspaceId: deps.workspaceId,+ });+ const webhookUrl = '/api/workflows/agent-eval-run/on-thread-complete';+ const userId = deps.userId;+ const db = deps.db;++ try {+ const execResult = await aiAgentService.execAgent({+ agentId: run.targetAgentId ?? undefined,+ appContext: { threadId, topicId },+ autoStart: true,+ trigger: RequestTrigger.Eval,+ hooks: [+ {+ handler: async (event) => {+ // Local mode: directly record thread completion+ await recordThreadCompletion(createEvalRunDeps(db, userId, deps.workspaceId), {+ runId,+ status: event.status || event.reason || 'done',+ telemetry: {+ completionReason: event.reason,+ cost: event.cost,+ duration: event.duration,+ errorMessage: event.errorMessage,+ llmCalls: event.llmCalls,+ steps: event.steps,+ toolCalls: event.toolCalls,+ totalTokens: event.totalTokens,+ },+ testCaseId,+ threadId,+ topicId,+ });+ },+ id: 'eval-thread-complete',+ type: 'onComplete' as const,+ webhook: {+ body: { runId, testCaseId, threadId, topicId, userId },+ delivery: 'qstash' as const,+ url: webhookUrl,+ },+ },+ ],+ ...getEvalContextParams(envPrompt, environment, caseId),+ maxSteps: run.config?.maxSteps,+ prompt: params.testCase.content.input || '',+ queueRetries: EVAL_AGENT_RUNTIME_QSTASH_RETRIES,+ queueRetryDelay: EVAL_AGENT_RUNTIME_QSTASH_RETRY_DELAY,+ userInterventionConfig: { approvalMode: 'headless' },+ });++ // Write operationId to thread metadata+ if (execResult?.operationId) {+ await deps.threadModel.update(threadId, {+ metadata: { operationId: execResult.operationId, testCaseId },+ } as any);+ }++ return { threadId, topicId };+ } catch (error) {+ const errorMessage =+ error instanceof Error ? error.message : 'Thread execution failed to start';+ console.error(+ `[run-thread-trajectory] execAgent failed for run=${runId} thread=${threadId}:`,+ error,+ );++ // Mark the thread explicitly as error; aggregation and resume-target selection rely on metadata.status.+ await deps.threadModel.update(threadId, {+ metadata: {+ completedAt: new Date().toISOString(),+ error: errorMessage,+ passed: false,+ score: 0,+ status: 'error',+ testCaseId,+ },+ } as any);++ return { error: errorMessage, threadId, topicId };+ }+}++/**+ * Record a single thread's completion (for pass@k).+ * Evaluates the thread's messages, writes result to thread.metadata,+ * then checks if all K threads are done. If so, aggregates into RunTopic.+ */+export async function recordThreadCompletion(+ deps: EvalRunDeps,+ params: {+ runId: string;+ status: string;+ telemetry: {+ completionReason?: string;+ cost?: number;+ duration?: number;+ errorMessage?: string;+ llmCalls?: number;+ steps?: number;+ toolCalls?: number;+ totalTokens?: number;+ };+ testCaseId: string;+ threadId: string;+ topicId: string;+ },+): Promise<{ allRunDone: boolean; allThreadsDone: boolean }> {+ const { runId, testCaseId, threadId, topicId, telemetry, status } = params;++ // 1. Evaluate this thread's messages+ const evalResult = await evaluateThread(deps, {+ runId,+ status,+ telemetry,+ testCaseId,+ threadId,+ topicId,+ });++ // 2. Write eval result to thread.metadata+ await deps.threadModel.update(threadId, {+ metadata: {+ ...evalResult,+ completedAt: new Date().toISOString(),+ // Normalize status into metadata so later aggregation can reconstruct threads[] consistently.+ status: getThreadResultStatus(evalResult),+ testCaseId,+ },+ } as any);++ // 3. Check if all K threads for this topic are done+ const allThreads = await deps.threadModel.queryByTopicId(topicId);+ const evalThreads = allThreads.filter((t) => t.type === 'eval');+ const completedThreads = evalThreads.filter((t) => {+ const meta = t.metadata as Record<string, unknown> | null;+ return meta && 'completedAt' in meta;+ });++ const allThreadsDone = completedThreads.length >= evalThreads.length;++ if (!allThreadsDone) {+ return { allRunDone: false, allThreadsDone: false };+ }++ // 4. All K threads done β aggregate into RunTopic+ await aggregateThreadResults(deps, {+ completedThreads: evalThreads,+ runId,+ testCaseId,+ topicId,+ });++ // 5. Check if the entire run is done (same as recordTrajectoryCompletion)+ const run = await deps.runModel.findById(runId);+ if (!run) return { allRunDone: false, allThreadsDone: true };++ const totalCases = run.metrics?.totalCases;+ if (!totalCases) return { allRunDone: false, allThreadsDone: true };++ const allTopics = await deps.runTopicModel.findByRunId(runId);+ const completedCount = allTopics.filter(+ (t) => (t.evalResult && 'completionReason' in t.evalResult) || t.status === 'timeout',+ ).length;++ // Update run metrics+ const passedCases = allTopics.filter((t) => t.status === 'passed').length;+ const failedCases = allTopics.filter((t) => t.status === 'failed').length;+ const errorCases = allTopics.filter((t) => t.status === 'error').length;+ const externalCasesRT = allTopics.filter((t) => t.status === 'external').length;+ const timeoutCases = allTopics.filter((t) => t.status === 'timeout').length;++ let sumCost = 0;+ let sumTokens = 0;+ let sumSteps = 0;+ let sumLlmCalls = 0;+ let sumToolCalls = 0;+ let actualTotalCost = 0;+ let actualTotalTokens = 0;+ let actualTotalDuration = 0;+ for (const t of allTopics) {+ const r = t.evalResult as Record<string, unknown> | null;+ if (r && ('completionReason' in r || t.status === 'timeout')) {+ if (typeof r.cost === 'number') sumCost += r.cost;+ if (typeof r.tokens === 'number') sumTokens += r.tokens;+ if (typeof r.steps === 'number') sumSteps += r.steps;+ if (typeof r.llmCalls === 'number') sumLlmCalls += r.llmCalls;+ if (typeof r.toolCalls === 'number') sumToolCalls += r.toolCalls;+ const rTotalCost =+ typeof r.totalCost === 'number' ? r.totalCost : typeof r.cost === 'number' ? r.cost : 0;+ const rTotalTokens =+ typeof r.totalTokens === 'number'+ ? r.totalTokens+ : typeof r.tokens === 'number'+ ? r.tokens+ : 0;+ const rTotalDuration =+ typeof r.totalDuration === 'number'+ ? r.totalDuration+ : typeof r.duration === 'number'+ ? r.duration+ : 0;+ actualTotalCost += rTotalCost;+ actualTotalTokens += rTotalTokens;+ actualTotalDuration += rTotalDuration;+ }+ }++ await deps.runModel.update(runId, {+ metrics: {+ ...(run.metrics as EvalRunMetrics),+ completedCases: completedCount,+ cost: sumCost ? roundCost(sumCost) : undefined,+ errorCases,+ externalCases: externalCasesRT || undefined,+ failedCases,+ llmCalls: sumLlmCalls || undefined,+ passedCases,+ perCaseCost: sumCost && completedCount ? roundCost(sumCost / completedCount) : undefined,+ perCaseLlmCalls:+ sumLlmCalls && completedCount+ ? Math.round((sumLlmCalls / completedCount) * 10) / 10+ : undefined,+ perCaseSteps:+ sumSteps && completedCount ? Math.round((sumSteps / completedCount) * 10) / 10 : undefined,+ perCaseTokens:+ sumTokens && completedCount ? Math.round(sumTokens / completedCount) : undefined,+ perCaseToolCalls:+ sumToolCalls && completedCount+ ? Math.round((sumToolCalls / completedCount) * 10) / 10+ : undefined,+ steps: sumSteps || undefined,+ timeoutCases,+ tokens: sumTokens || undefined,+ toolCalls: sumToolCalls || undefined,+ totalCost: actualTotalCost ? roundCost(actualTotalCost) : undefined,+ totalDuration: actualTotalDuration || undefined,+ totalTokens: actualTotalTokens || undefined,+ },+ });++ return { allRunDone: completedCount >= totalCases, allThreadsDone: true };+}++/**+ * Evaluate a single thread's messages against rubrics.+ * Returns the eval result to write into thread.metadata.+ */+async function evaluateThread(+ deps: EvalRunDeps,+ params: {+ runId: string;+ status: string;+ telemetry: {+ completionReason?: string;+ cost?: number;+ duration?: number;+ errorDetail?: unknown;+ errorMessage?: string;+ llmCalls?: number;+ steps?: number;+ toolCalls?: number;+ totalTokens?: number;+ };+ testCaseId: string;+ threadId: string;+ topicId: string;+ },+): Promise<Record<string, unknown>> {+ const { runId, status, telemetry, testCaseId, threadId } = params;++ const baseMeta: Record<string, unknown> = {+ completionReason: telemetry.completionReason,+ cost: telemetry.cost != null ? roundCost(telemetry.cost) : undefined,+ duration: telemetry.duration,+ llmCalls: telemetry.llmCalls,+ steps: telemetry.steps,+ tokens: telemetry.totalTokens,+ toolCalls: telemetry.toolCalls,+ };++ // Error case β skip evaluation+ if (status === 'error') {+ return {+ ...baseMeta,+ error:+ telemetry.errorMessage || `Execution error: ${telemetry.completionReason || 'unknown'}`,+ errorDetail: telemetry.errorDetail,+ passed: false,+ score: 0,+ };+ }++ // Load run β dataset β benchmark for rubrics+ const run = await deps.runModel.findById(runId);+ if (!run) return { ...baseMeta, error: 'Run not found', passed: false, score: 0 };++ const dataset = await deps.datasetModel.findById(run.datasetId);+ if (!dataset) return { ...baseMeta, error: 'Dataset not found', passed: false, score: 0 };++ // A dataset need not belong to a benchmark; such a dataset simply+ // contributes no benchmark-level rubrics, and scoring falls back to the+ // per-case / per-dataset evalMode. Bailing here would leave every case in a+ // captured dataset permanently unscored.+ const benchmark = dataset.benchmarkId+ ? await deps.benchmarkModel.findById(dataset.benchmarkId)+ : null;++ const testCase = await deps.testCaseModel.findById(testCaseId);+ if (!testCase) return { ...baseMeta, error: 'Test case not found', passed: false, score: 0 };++ const passThreshold = (run.config?.passThreshold as number) ?? 0.6;++ // Get messages for this thread+ const messages = await deps.messageModel.query({ threadId, topicId: params.topicId });+ const assistantMessages = messages.filter((m: { role: string }) => m.role === 'assistant');+ const lastAssistantMsg = assistantMessages.at(-1);++ if (!lastAssistantMsg || !lastAssistantMsg.content) {+ return {+ ...baseMeta,+ error: 'No assistant output',+ passed: false,+ rubricScores: [],+ score: 0,+ };+ }++ // Resolve rubrics+ const evalMode = (testCase.evalMode ?? dataset.evalMode) as RubricType | null | undefined;+ const evalConfig = testCase.evalConfig ?? dataset.evalConfig;++ // ββ External eval mode: agent finished, hand off to external scorer ββ+ if (evalMode === 'external') {+ return {+ ...baseMeta,+ awaitingExternalEval: true,+ passed: undefined,+ score: undefined,+ status: 'external',+ };+ }++ let effectiveRubrics: EvalBenchmarkRubric[];+ if (evalMode) {+ effectiveRubrics = [+ {+ config: (evalConfig ?? {}) as unknown as EvalBenchmarkRubric['config'],+ id: `eval-mode-${evalMode}`,+ name: evalMode,+ type: evalMode,+ weight: 1,+ },+ ];+ } else {+ effectiveRubrics = benchmark?.rubrics ?? [];+ }++ // Run evaluation+ const result = await evaluate(+ { actual: lastAssistantMsg.content, rubrics: effectiveRubrics, testCase: testCase.content },+ { passThreshold },+ );++ return {+ ...baseMeta,+ passed: result.passed,+ rubricScores: result.rubricResults.map((r) => ({+ reason: r.reason,+ rubricId: r.rubricId,+ score: r.score,+ })),+ score: result.score,+ };+}++/**+ * Aggregate all completed thread results into RunTopic.+ * Writes threads[] array, plus top-level score/passed using pass@k logic.+ */+async function aggregateThreadResults(+ deps: EvalRunDeps,+ params: {+ completedThreads: Array<{ id: string; metadata?: Record<string, unknown> | null }>;+ runId: string;+ testCaseId: string;+ topicId: string;+ },+) {+ const { completedThreads, runId, topicId } = params;++ // Build threads array from metadata+ const threadResults: Array<{+ completionReason?: string;+ cost?: number;+ duration?: number;+ error?: string;+ llmCalls?: number;+ passed?: boolean;+ rubricScores?: Array<{ reason?: string; rubricId: string; score: number }>;+ score?: number;+ status?: 'error' | 'external' | 'failed' | 'passed' | 'running' | 'timeout';+ steps?: number;+ threadId: string;+ tokens?: number;+ toolCalls?: number;+ }> = completedThreads.map((t) => {+ const meta = (t.metadata ?? {}) as Record<string, unknown>;+ return {+ completionReason: meta.completionReason as string | undefined,+ cost: meta.cost as number | undefined,+ duration: meta.duration as number | undefined,+ error: meta.error as string | undefined,+ llmCalls: meta.llmCalls as number | undefined,+ passed: meta.passed as boolean | undefined,+ rubricScores: meta.rubricScores as any,+ score: meta.score as number | undefined,+ status: meta.status as+ 'error' | 'external' | 'failed' | 'passed' | 'running' | 'timeout' | undefined,+ steps: meta.steps as number | undefined,+ threadId: t.id,+ tokens: meta.tokens as number | undefined,+ toolCalls: meta.toolCalls as number | undefined,+ };+ });++ // ββ External eval mode: if all threads await external scoring, propagate that status ββ+ const allExternal = threadResults.every((t) => t.status === 'external');+ if (allExternal) {+ await deps.runTopicModel.updateByRunAndTopic(runId, topicId, {+ evalResult: {+ awaitingExternalEval: true,+ completionReason: 'external',+ threads: threadResults,+ } satisfies EvalRunTopicResult,+ status: 'external',+ });+ return;+ }++ // pass@k: at least one thread passed+ const anyPassed = threadResults.some((t) => t.passed === true);+ // pass^k: all threads passed+ const allPassed = threadResults.every((t) => t.passed === true);++ // Best score (used as the representative score)+ const scores = threadResults.filter((t) => t.score != null).map((t) => t.score!);+ const bestScore = scores.length > 0 ? Math.max(...scores) : 0;++ // Aggregate metrics as totals across K threads+ let totalCost = 0;+ let totalDuration = 0;+ let totalTokens = 0;+ let totalSteps = 0;+ let totalLlmCalls = 0;+ let totalToolCalls = 0;+ for (const t of threadResults) {+ if (t.cost) totalCost += t.cost;+ if (t.duration) totalDuration += t.duration;+ if (t.tokens) totalTokens += t.tokens;+ if (t.steps) totalSteps += t.steps;+ if (t.llmCalls) totalLlmCalls += t.llmCalls;+ if (t.toolCalls) totalToolCalls += t.toolCalls;+ }++ // Compute per-case averages (primary fields = avg)+ const k = threadResults.length;++ // The topic-level completionReason: use "completed" if any succeeded+ const completionReason = anyPassed ? 'completed' : 'failed';++ // Write aggregated result to RunTopic+ // Primary fields (cost/tokens/duration/steps/llmCalls/toolCalls) = average per execution+ // total* fields = cumulative across K threads+ await deps.runTopicModel.updateByRunAndTopic(runId, topicId, {+ evalResult: {+ completionReason,+ cost: totalCost ? roundCost(totalCost / k) : undefined,+ duration: totalDuration ? totalDuration / k : undefined,+ llmCalls: totalLlmCalls ? Math.round((totalLlmCalls / k) * 10) / 10 : undefined,+ passAllK: allPassed,+ passAtK: anyPassed,+ steps: totalSteps ? Math.round((totalSteps / k) * 10) / 10 : undefined,+ threads: threadResults,+ tokens: totalTokens ? totalTokens / k : undefined,+ toolCalls: totalToolCalls ? Math.round((totalToolCalls / k) * 10) / 10 : undefined,+ totalCost: totalCost ? roundCost(totalCost) : undefined,+ totalDuration: totalDuration || undefined,+ totalTokens: totalTokens || undefined,+ } satisfies EvalRunTopicResult,+ // pass@k: passed if any thread passed+ passed: anyPassed,+ score: bestScore,+ status: anyPassed ? 'passed' : 'failed',+ });+}diff --git a/apps/server/src/services/agentEvalRun/trajectory.ts b/apps/server/src/services/agentEvalRun/trajectory.tsnew file mode 100644index 00000000000..f05c5ec9435--- /dev/null+++ b/apps/server/src/services/agentEvalRun/trajectory.ts@@ -0,0 +1,282 @@+import type { EvalCaseEnvironment, EvalRunConfig, EvalTestCaseMetadata } from '@lobechat/types';+import { RequestTrigger } from '@lobechat/types';++import { AiAgentService } from '@/server/services/aiAgent';++import { recordTrajectoryCompletion } from './completion';+import {+ EVAL_AGENT_RUNTIME_QSTASH_RETRIES,+ EVAL_AGENT_RUNTIME_QSTASH_RETRY_DELAY,+} from './constants';+import { createRunTopics } from './createRun';+import { createEvalRunDeps } from './deps';+import type { EvalRunDeps } from './types';+import { getCaseId, getEvalContextParams } from './utils';++export async function loadTrajectoryData(deps: EvalRunDeps, runId: string, testCaseId: string) {+ const run = await deps.runModel.findById(runId);+ if (!run) return { error: 'Run not found' as const };++ const testCase = await deps.testCaseModel.findById(testCaseId);+ if (!testCase) return { error: 'Test case not found' as const };++ let envPrompt: string | undefined;+ let environment: EvalCaseEnvironment | undefined;+ if (run.datasetId) {+ const dataset = await deps.datasetModel.findById(run.datasetId);+ envPrompt = dataset?.evalConfig?.envPrompt;+ environment = testCase.content.environment;+ }++ return { envPrompt, environment, run, testCase };+}++export async function executeTrajectory(+ deps: EvalRunDeps,+ params: {+ envPrompt?: string;+ run: {+ config?: EvalRunConfig | null;+ datasetId: string;+ targetAgentId?: string | null;+ };+ runId: string;+ testCase: {+ content: { input?: string };+ metadata?: EvalTestCaseMetadata | null;+ sortOrder?: number | null;+ };+ testCaseId: string;+ environment?: EvalCaseEnvironment;+ },+) {+ const { runId, testCaseId } = params;++ // Look up the pre-created RunTopic (created during createRun)+ const runTopic = await deps.runTopicModel.findByRunAndTestCase(runId, testCaseId);+ if (!runTopic) {+ throw new Error(`RunTopic not found for run=${runId} testCase=${testCaseId}`);+ }++ return executeTrajectoryCore(deps, { ...params, topicId: runTopic.topicId });+}++/**+ * Shared trajectory execution once the target topic is known. Marks the+ * RunTopic running and starts the agent via execAgent.+ */+async function executeTrajectoryCore(+ deps: EvalRunDeps,+ params: {+ /** Route execution to an enrolled device (native AgentRuntime). */+ deviceId?: string;+ envPrompt?: string;+ run: {+ config?: EvalRunConfig | null;+ datasetId: string;+ targetAgentId?: string | null;+ };+ runId: string;+ testCase: {+ content: { input?: string };+ metadata?: EvalTestCaseMetadata | null;+ sortOrder?: number | null;+ };+ testCaseId: string;+ topicId: string;+ environment?: EvalCaseEnvironment;+ },+) {+ const { envPrompt, environment, run, runId, testCaseId, topicId } = params;+ const caseId = getCaseId(params.testCase.metadata);++ // Update status from 'pending' to 'running'+ await deps.runTopicModel.updateByRunAndTopic(runId, topicId, { status: 'running' });++ const aiAgentService = new AiAgentService(deps.db, deps.userId, {+ workspaceId: deps.workspaceId,+ });+ const webhookUrl = '/api/workflows/agent-eval-run/on-trajectory-complete';+ const userId = deps.userId;+ const db = deps.db;++ try {+ const execResult = await aiAgentService.execAgent({+ agentId: run.targetAgentId ?? undefined,+ appContext: { topicId },+ autoStart: true,+ ...(params.deviceId && { deviceId: params.deviceId }),+ trigger: RequestTrigger.Eval,+ hooks: [+ {+ handler: async (event) => {+ // Local mode: directly record completion+ await recordTrajectoryCompletion(createEvalRunDeps(db, userId, deps.workspaceId), {+ runId,+ status: event.status || event.reason || 'done',+ telemetry: {+ completionReason: event.reason,+ cost: event.cost,+ duration: event.duration,+ errorDetail: event.errorDetail,+ errorMessage: event.errorMessage,+ llmCalls: event.llmCalls,+ steps: event.steps,+ toolCalls: event.toolCalls,+ totalTokens: event.totalTokens,+ },+ testCaseId,+ });+ },+ id: 'eval-trajectory-complete',+ type: 'onComplete' as const,+ webhook: {+ body: { runId, testCaseId, userId },+ delivery: 'qstash' as const,+ url: webhookUrl,+ },+ },+ ],+ ...getEvalContextParams(envPrompt, environment, caseId),+ maxSteps: run.config?.maxSteps,+ prompt: params.testCase.content.input || '',+ queueRetries: EVAL_AGENT_RUNTIME_QSTASH_RETRIES,+ queueRetryDelay: EVAL_AGENT_RUNTIME_QSTASH_RETRY_DELAY,+ userInterventionConfig: { approvalMode: 'headless' },+ });++ if (execResult?.operationId) {+ await deps.runTopicModel.updateByRunAndTopic(runId, topicId, {+ evalResult: { operationId: execResult.operationId, rubricScores: [] },+ });+ }++ return { operationId: execResult?.operationId, topicId };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : 'Agent execution failed to start';+ console.error(+ `[run-agent-trajectory] execAgent failed for run=${runId} testCase=${testCaseId}:`,+ error,+ );++ await deps.runTopicModel.updateByRunAndTopic(runId, topicId, {+ evalResult: { completionReason: 'error', error: errorMessage, rubricScores: [] },+ passed: false,+ score: 0,+ status: 'error',+ });++ return { error: errorMessage, topicId };+ }+}++/**+ * Atomically claim a pending external run (pending -> running) and return+ * everything a worker needs: the run, its dataset, all test cases (each+ * exposing the dataset-native `metadata.caseId`), and the agent snapshot.+ * Throws when the run is not owned or not currently pending.+ */+export async function claimRun(deps: EvalRunDeps, runId: string) {+ const run = await deps.runModel.claim(runId);+ if (!run) throw new Error('Run is not pending or already claimed');++ const [dataset, testCases] = await Promise.all([+ deps.datasetModel.findById(run.datasetId),+ deps.testCaseModel.findByDatasetId(run.datasetId),+ ]);++ return {+ agentSnapshot: (run.config as EvalRunConfig | null)?.agentSnapshot,+ dataset: dataset+ ? {+ evalConfig: dataset.evalConfig,+ id: dataset.id,+ identifier: dataset.identifier,+ metadata: dataset.metadata,+ name: dataset.name,+ }+ : undefined,+ run,+ testCases: testCases.map((tc) => ({+ content: tc.content,+ id: tc.id,+ metadata: tc.metadata,+ sortOrder: tc.sortOrder,+ })),+ };+}++/**+ * External worker entry point: execute a single case of a claimed run by its+ * dataset-native `metadata.caseId` (falling back to the internal test case+ * id). Creates the Topic/RunTopic on demand (external runs pre-create none),+ * then runs the trajectory. Idempotent for terminal cases β the old RunTopic+ * association is replaced with a fresh Topic; an active case is rejected.+ */+export async function executeTrajectoryOnDemand(+ deps: EvalRunDeps,+ params: {+ caseId: string;+ /** Route execution to an enrolled device (native AgentRuntime). */+ deviceId?: string;+ prompt?: string;+ runId: string;+ },+) {+ const { runId, caseId } = params;++ const run = await deps.runModel.findById(runId);+ if (!run) throw new Error('Run not found');+ if (run.status !== 'running') {+ throw new Error(`Run is not running (status=${run.status}); claim it first`);+ }+ if (((run.config as EvalRunConfig | null)?.k ?? 1) > 1) {+ throw new Error('External execution only supports k=1');+ }++ // Resolve the dataset-native caseId to an internal test case.+ let testCase = await deps.testCaseModel.findByDatasetIdAndCaseId(run.datasetId, caseId);+ if (!testCase) {+ const byId = await deps.testCaseModel.findById(caseId);+ if (byId && byId.datasetId === run.datasetId) testCase = byId;+ }+ if (!testCase) throw new Error(`Test case not found for caseId=${caseId}`);++ const testCaseId = testCase.id;+ const dataset = await deps.datasetModel.findById(run.datasetId);+ const envPrompt = dataset?.evalConfig?.envPrompt;+ const environment = testCase.content.environment;++ // Idempotent re-run of a terminal case: drop only the old RunTopic+ // association (the old Topic is preserved) and link a fresh one.+ const existing = await deps.runTopicModel.findByRunAndTestCase(runId, testCaseId);+ if (existing) {+ if (existing.status === 'running' || existing.status === 'pending') {+ throw new Error(`Case ${caseId} is already active for this run`);+ }+ await deps.runTopicModel.deleteByRunAndTestCase(runId, testCaseId);+ }++ const topicId = (+ await createRunTopics(deps, runId, run.targetAgentId, [+ { content: testCase.content, id: testCaseId, sortOrder: testCase.sortOrder },+ ])+ )[0]!;++ const result = await executeTrajectoryCore(deps, {+ deviceId: params.deviceId,+ envPrompt,+ run: { config: run.config, datasetId: run.datasetId, targetAgentId: run.targetAgentId },+ runId,+ testCase: {+ content: { ...testCase.content, input: params.prompt ?? testCase.content.input },+ metadata: testCase.metadata,+ sortOrder: testCase.sortOrder,+ },+ testCaseId,+ topicId,+ environment,+ });++ return { ...result, testCaseId };+}diff --git a/apps/server/src/services/agentEvalRun/types.ts b/apps/server/src/services/agentEvalRun/types.tsnew file mode 100644index 00000000000..c861300ae58--- /dev/null+++ b/apps/server/src/services/agentEvalRun/types.ts@@ -0,0 +1,35 @@+import type { LobeChatDatabase } from '@lobechat/database';++import type {+ AgentEvalBenchmarkModel,+ AgentEvalDatasetModel,+ AgentEvalExperimentModel,+ AgentEvalRunModel,+ AgentEvalRunTopicModel,+ AgentEvalTestCaseModel,+} from '@/database/models/agentEval';+import type { MessageModel } from '@/database/models/message';+import type { ThreadModel } from '@/database/models/thread';+import type { TopicModel } from '@/database/models/topic';+import type { AgentService } from '@/server/services/agent';++/**+ * What every stage of an eval run works with: the owner it runs as and the+ * models scoped to that owner. `AgentEvalRunService` builds it once and passes+ * it to the stage functions explicitly.+ */+export interface EvalRunDeps {+ agentService: AgentService;+ benchmarkModel: AgentEvalBenchmarkModel;+ datasetModel: AgentEvalDatasetModel;+ db: LobeChatDatabase;+ experimentModel: AgentEvalExperimentModel;+ messageModel: MessageModel;+ runModel: AgentEvalRunModel;+ runTopicModel: AgentEvalRunTopicModel;+ testCaseModel: AgentEvalTestCaseModel;+ threadModel: ThreadModel;+ topicModel: TopicModel;+ userId: string;+ workspaceId?: string;+}diff --git a/apps/server/src/services/agentEvalRun/utils.ts b/apps/server/src/services/agentEvalRun/utils.tsnew file mode 100644index 00000000000..7a011c33f9f--- /dev/null+++ b/apps/server/src/services/agentEvalRun/utils.ts@@ -0,0 +1,29 @@+import type { EvalCaseEnvironment, EvalTestCaseMetadata } from '@lobechat/types';+import debug from 'debug';++import type { EvalRuntimeContext } from '@/server/services/agentRuntime/types';++/** Round cost to at most 6 decimal places to avoid floating-point noise */+export const roundCost = (v: number): number => Math.round(v * 1e6) / 1e6;++export const getEvalContextParams = (+ envPrompt?: string,+ environment?: EvalCaseEnvironment,+ caseId?: string,+) => {+ const mergedEnvPrompt =+ [envPrompt, environment?.envPrompt].filter(Boolean).join('\n\n') || undefined;+ const evalRuntime: EvalRuntimeContext | undefined =+ caseId || environment?.toolForwarding+ ? { ...(caseId && { caseId }), toolForwarding: environment?.toolForwarding }+ : undefined;++ return {+ ...(mergedEnvPrompt && { evalContext: { envPrompt: mergedEnvPrompt } }),+ ...(evalRuntime && { evalRuntime }),+ };+};++export const getCaseId = (metadata?: EvalTestCaseMetadata | null) => metadata?.caseId;++export const log = debug('lobe-server:eval-run-service');