Skip to content

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

✨ feat(lobe-bench): add benchmark runtime, isolated eval memory and run queue (#22482)

Robin Zhang97d809638a07
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentEval.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentEval.test.ts
new file mode 100644
index 00000000000..69ed6e840d3
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentEval.test.ts
@@ -0,0 +1,68 @@
+import { type AgentState } from '@lobechat/agent-runtime';
+import { type ChatToolPayload, RequestTrigger } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { type RuntimeExecutorContext } from '../context';
+import { buildServerVirtualSubAgentRunner } from '../executorHelpers';
+
+/**
+ * A `callSubAgent` child forked inside an eval attempt must stay inside the
+ * attempt's sandbox. Before this, the child ran with no eval context at all:
+ * its tool calls went to the real services instead of the case mocks, its
+ * Memory was the caller's own, it saw the wall clock, and it had no step cap.
+ */
+describe('buildServerVirtualSubAgentRunner eval inheritance', () => {
+ const evalRuntime = {
+ caseId: 'case-7',
+ memory: { fixtureHash: 'hash', runId: 'run-1', topicId: 'topic-1' },
+ toolForwarding: { twitter: { endpoint: 'http://mock/twitter' } },
+ };
+ const evalContext = { sessionDate: '2026-07-24', timezone: 'America/New_York' };
+
+ const buildRunner = (state: Partial<AgentState>) => {
+ const execVirtualSubAgent = vi.fn().mockResolvedValue({ operationId: 'child-op' });
+ const ctx = {
+ execVirtualSubAgent,
+ messageModel: { create: vi.fn().mockResolvedValue({ id: 'placeholder-id' }) },
+ operationId: 'parent-op',
+ topicId: 'topic-1',
+ } as unknown as RuntimeExecutorContext;
+
+ const runner = buildServerVirtualSubAgentRunner(
+ ctx,
+ { operationId: 'parent-op', ...state } as AgentState,
+ { id: 'tool-call-1' } as ChatToolPayload,
+ 'parent-message-1',
+ );
+
+ return { execVirtualSubAgent, runner };
+ };
+
+ it('hands the attempt clock, runtime and step cap to the child of an eval run', async () => {
+ const { execVirtualSubAgent, runner } = buildRunner({
+ maxSteps: 20,
+ origin: { agentId: 'agent-1', topicId: 'topic-1', trigger: RequestTrigger.Eval },
+ plan: { eval: evalRuntime },
+ world: { eval: evalContext } as any,
+ });
+
+ await runner!.run({ description: 'task', instruction: 'do it' });
+
+ expect(execVirtualSubAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ eval: { context: evalContext, maxSteps: 20, runtime: evalRuntime },
+ }),
+ );
+ });
+
+ it('passes nothing eval-related for an ordinary chat run', async () => {
+ const { execVirtualSubAgent, runner } = buildRunner({
+ maxSteps: 20,
+ origin: { agentId: 'agent-1', topicId: 'topic-1', trigger: RequestTrigger.Chat },
+ });
+
+ await runner!.run({ description: 'task', instruction: 'do it' });
+
+ expect(execVirtualSubAgent.mock.calls[0][0]).not.toHaveProperty('eval');
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.stop.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.stop.test.ts
index 575442434a1..68c091033fe 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.stop.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.stop.test.ts
@@ -142,6 +142,24 @@ afterEach(() => {
});
describe('environment stop between tool steps', () => {
+ it('intercepts a native tool before the real executor or client dispatch', async () => {
+ const fixture = setup([
+ {
+ id: 'eval-contract',
+ type: 'beforeToolCall',
+ handler: async (event) => {
+ (event as any).mock({ content: 'Frozen fixture response', success: true });
+ },
+ },
+ ]);
+ await fixture.step([
+ { ...call(), identifier: 'lobe-web-browsing', apiName: 'search', executor: 'server' },
+ ]);
+ expect(fixture.execute).not.toHaveBeenCalled();
+ expect(dispatchClient).not.toHaveBeenCalled();
+ expect(JSON.stringify(fixture.rows)).toContain('Frozen fixture response');
+ });
+
it('does not launch another server tool after the persisted interrupt, before local polling catches up', async () => {
const controller = new AbortController();
const fixture = setup([], controller.signal);
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index 32948172579..cffe899feb4 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -17,6 +17,7 @@ import {
tracer as agentRuntimeTracer,
} from '@lobechat/observability-otel/modules/agent-runtime';
import type { ChatToolPayload } from '@lobechat/types';
+import { RequestTrigger } from '@lobechat/types';
import { AgentModel } from '@/database/models/agent';
import { AgentOperationModel } from '@/database/models/agentOperation';
@@ -306,6 +307,9 @@ export class ServerToolTransport implements ToolTransport {
: undefined,
localSandboxNetwork:
context.state.world?.agent?.agencyConfig?.localSandboxNetwork === true,
+ evalMemory: context.state.plan?.eval?.memory,
+ isEval: context.state.origin?.trigger === RequestTrigger.Eval,
+ memoryEffort: context.state.world?.agent?.chatConfig?.memory?.effort,
memoryToolPermission: context.state.world?.agent?.chatConfig?.memory?.toolPermission,
messageId: context.state.origin?.sourceMessageId,
operationId,
diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
index 8147e8942db..e0643e8574c 100644
--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts
+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
@@ -11,6 +11,7 @@ import { type ToolType } from '@lobechat/observability-otel/modules/agent-runtim
import {
type ChatToolPayload,
type LobeAgentConfig,
+ RequestTrigger,
type WorkAccessScope,
type WorkRegistrationIntent,
} from '@lobechat/types';
@@ -266,6 +267,16 @@ export const buildServerVirtualSubAgentRunner = (
// `callAgent` target only takes it as its `local` device, keeping its own
// execution target.
const parentDeviceId = resolveRunActiveDeviceId(state);
+ // A child forked inside an eval attempt stays inside that attempt's sandbox:
+ // same session clock, same tool forwarding and Memory scope, same step cap.
+ const parentEval =
+ state.origin?.trigger === RequestTrigger.Eval
+ ? {
+ ...(state.world?.eval && { context: state.world.eval }),
+ ...(state.maxSteps && { maxSteps: state.maxSteps }),
+ ...(state.plan?.eval && { runtime: state.plan.eval }),
+ }
+ : undefined;
return {
run: async ({
@@ -338,6 +349,7 @@ export const buildServerVirtualSubAgentRunner = (
background,
chatConfig: subAgentChatConfig,
deviceId: targetAgentId ? undefined : parentDeviceId,
+ ...(parentEval && { eval: parentEval }),
groupId: state.origin?.groupId ?? undefined,
instruction,
localDeviceId: parentDeviceId,
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/handlers/onThreadComplete.test.ts b/apps/server/src/router-hono/workflows/agent-eval-run/handlers/onThreadComplete.test.ts
new file mode 100644
index 00000000000..bdee0b05268
--- /dev/null
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/handlers/onThreadComplete.test.ts
@@ -0,0 +1,95 @@
+import type { Context } from 'hono';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { onThreadComplete } from './onThreadComplete';
+
+const mocks = vi.hoisted(() => ({
+ complete: vi.fn(),
+ finalize: vi.fn(),
+ findRun: vi.fn(),
+}));
+
+vi.mock('@/database/server', () => ({ getServerDB: vi.fn().mockResolvedValue({}) }));
+vi.mock('@/database/models/agentEval', () => ({
+ AgentEvalRunModel: vi.fn().mockImplementation(function () {
+ return { findSummaryById: mocks.findRun };
+ }),
+}));
+vi.mock('@/server/services/agentEvalRun', () => ({
+ AgentEvalRunService: vi.fn().mockImplementation(function () {
+ return { recordThreadCompletion: mocks.complete };
+ }),
+}));
+vi.mock('@/server/workflows/agentEvalRun', () => ({
+ AgentEvalRunWorkflow: { triggerFinalizeRun: mocks.finalize },
+}));
+vi.mock('@/server/workflows/agentEvalRun/utils', () => ({
+ resolveAgentEvalRunWorkspace: vi.fn().mockResolvedValue('workspace'),
+}));
+
+const invoke = async (extra: Record<string, unknown> = {}) => {
+ const json = vi.fn((body: unknown, status = 200) => ({ body, status }));
+ const context = {
+ json,
+ req: {
+ json: async () => ({
+ operationId: 'operation',
+ reason: 'stop',
+ runId: 'run',
+ status: 'completed',
+ testCaseId: 'case',
+ threadId: 'thread',
+ topicId: 'topic',
+ userId: 'user',
+ ...extra,
+ }),
+ },
+ } as unknown as Context;
+ await onThreadComplete(context);
+ return json;
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.findRun.mockResolvedValue({ status: 'running' });
+ mocks.complete.mockResolvedValue({ allRunDone: false, allThreadsDone: false });
+});
+
+describe('onThreadComplete generation boundary', () => {
+ it('forwards the execution identity with its thread before finalizing accepted results', async () => {
+ mocks.complete.mockResolvedValue({ allRunDone: true, allThreadsDone: true });
+ await invoke({ executionId: 'generation-2' });
+ expect(mocks.complete).toHaveBeenCalledWith(
+ expect.objectContaining({
+ executionId: 'generation-2',
+ runId: 'run',
+ testCaseId: 'case',
+ threadId: 'thread',
+ topicId: 'topic',
+ }),
+ );
+ expect(mocks.finalize).toHaveBeenCalledExactlyOnceWith({ runId: 'run', userId: 'user' });
+ });
+
+ it('does not finalize when the service rejects a stale generation', async () => {
+ const json = await invoke({ executionId: 'generation-1' });
+ expect(mocks.complete.mock.calls[0][0].executionId).toBe('generation-1');
+ expect(mocks.finalize).not.toHaveBeenCalled();
+ expect(json).toHaveBeenCalledWith({ allRunDone: false, allThreadsDone: false, success: true });
+ });
+
+ it('leaves a missing legacy identity undefined for the service to validate', async () => {
+ await invoke();
+ expect(mocks.complete).toHaveBeenCalledTimes(1);
+ expect(mocks.complete.mock.calls[0][0].executionId).toBeUndefined();
+ expect(mocks.finalize).not.toHaveBeenCalled();
+ });
+
+ it('does not deliver or finalize callbacks for an aborted run', async () => {
+ mocks.findRun.mockResolvedValue({ status: 'aborted' });
+ const json = await invoke({ executionId: 'generation-1' });
+ expect(mocks.complete).not.toHaveBeenCalled();
+ expect(mocks.finalize).not.toHaveBeenCalled();
+ expect(json).toHaveBeenCalledWith({ cancelled: true });
+ });
+});
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/handlers/onThreadComplete.ts b/apps/server/src/router-hono/workflows/agent-eval-run/handlers/onThreadComplete.ts
index 216bd262c93..72e925a6528 100644
--- a/apps/server/src/router-hono/workflows/agent-eval-run/handlers/onThreadComplete.ts
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/handlers/onThreadComplete.ts
@@ -37,6 +37,7 @@ export const onThreadComplete = async (c: Context) => {
cost,
duration,
errorMessage,
+ executionId,
llmCalls,
steps,
toolCalls,
@@ -62,7 +63,7 @@ export const onThreadComplete = async (c: Context) => {
// Check if run was aborted β€” skip processing to avoid overwriting abort state
const runModel = new AgentEvalRunModel(db, userId, wsId);
- const run = await runModel.findById(runId);
+ const run = await runModel.findSummaryById(runId);
if (run?.status === 'aborted') {
log('Run aborted, skipping: runId=%s testCaseId=%s threadId=%s', runId, testCaseId, threadId);
return c.json({ cancelled: true });
@@ -71,6 +72,7 @@ export const onThreadComplete = async (c: Context) => {
const service = new AgentEvalRunService(db, userId, wsId);
const { allThreadsDone, allRunDone } = await service.recordThreadCompletion({
+ executionId,
runId,
status,
telemetry: {
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/handlers/onTrajectoryComplete.test.ts b/apps/server/src/router-hono/workflows/agent-eval-run/handlers/onTrajectoryComplete.test.ts
new file mode 100644
index 00000000000..ca36e44db11
--- /dev/null
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/handlers/onTrajectoryComplete.test.ts
@@ -0,0 +1,97 @@
+import type { Context } from 'hono';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { onTrajectoryComplete } from './onTrajectoryComplete';
+
+const mocks = vi.hoisted(() => ({
+ complete: vi.fn(),
+ finalize: vi.fn(),
+ findRun: vi.fn(),
+}));
+
+vi.mock('@/database/server', () => ({ getServerDB: vi.fn().mockResolvedValue({}) }));
+vi.mock('@/database/models/agentEval', () => ({
+ AgentEvalRunModel: vi.fn().mockImplementation(function () {
+ return { findSummaryById: mocks.findRun };
+ }),
+}));
+vi.mock('@/server/services/agentEvalRun', () => ({
+ AgentEvalRunService: vi.fn().mockImplementation(function () {
+ return { recordTrajectoryCompletion: mocks.complete };
+ }),
+}));
+vi.mock('@/server/workflows/agentEvalRun', () => ({
+ AgentEvalRunWorkflow: { triggerFinalizeRun: mocks.finalize },
+}));
+vi.mock('@/server/workflows/agentEvalRun/utils', () => ({
+ resolveAgentEvalRunWorkspace: vi.fn().mockResolvedValue('workspace'),
+}));
+
+const invoke = async (extra: Record<string, unknown> = {}) => {
+ const json = vi.fn((body: unknown, status = 200) => ({ body, status }));
+ const context = {
+ json,
+ req: {
+ json: async () => ({
+ operationId: 'operation',
+ reason: 'stop',
+ runId: 'run',
+ status: 'completed',
+ testCaseId: 'case',
+ userId: 'user',
+ ...extra,
+ }),
+ },
+ } as unknown as Context;
+ await onTrajectoryComplete(context);
+ return json;
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.findRun.mockResolvedValue({ status: 'running' });
+ mocks.complete.mockResolvedValue({ allDone: false, completedCount: 0 });
+});
+
+describe('onTrajectoryComplete generation boundary', () => {
+ it('forwards the execution and topic identities before finalizing an accepted completion', async () => {
+ mocks.complete.mockResolvedValue({ allDone: true, completedCount: 1 });
+ await invoke({ executionId: 'generation-2', topicId: 'topic-2' });
+ expect(mocks.complete).toHaveBeenCalledWith(
+ expect.objectContaining({
+ executionId: 'generation-2',
+ runId: 'run',
+ testCaseId: 'case',
+ topicId: 'topic-2',
+ }),
+ );
+ expect(mocks.finalize).toHaveBeenCalledExactlyOnceWith({ runId: 'run', userId: 'user' });
+ });
+
+ it('does not finalize when the service rejects a stale generation', async () => {
+ const json = await invoke({ executionId: 'generation-1', topicId: 'old-topic' });
+ expect(mocks.complete.mock.calls[0][0]).toMatchObject({
+ executionId: 'generation-1',
+ topicId: 'old-topic',
+ });
+ expect(mocks.finalize).not.toHaveBeenCalled();
+ expect(json).toHaveBeenCalledWith({ success: true });
+ });
+
+ it('leaves missing legacy identities undefined for the service to reject against a new generation', async () => {
+ const json = await invoke();
+ expect(mocks.complete).toHaveBeenCalledTimes(1);
+ expect(mocks.complete.mock.calls[0][0].executionId).toBeUndefined();
+ expect(mocks.complete.mock.calls[0][0].topicId).toBeUndefined();
+ expect(mocks.finalize).not.toHaveBeenCalled();
+ expect(json).toHaveBeenCalledWith({ success: true });
+ });
+
+ it('does not deliver or finalize callbacks for an aborted run', async () => {
+ mocks.findRun.mockResolvedValue({ status: 'aborted' });
+ const json = await invoke({ executionId: 'generation-1', topicId: 'topic' });
+ expect(mocks.complete).not.toHaveBeenCalled();
+ expect(mocks.finalize).not.toHaveBeenCalled();
+ expect(json).toHaveBeenCalledWith({ cancelled: true });
+ });
+});
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/handlers/onTrajectoryComplete.ts b/apps/server/src/router-hono/workflows/agent-eval-run/handlers/onTrajectoryComplete.ts
index 34716c12972..178fc3eddbe 100644
--- a/apps/server/src/router-hono/workflows/agent-eval-run/handlers/onTrajectoryComplete.ts
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/handlers/onTrajectoryComplete.ts
@@ -35,9 +35,11 @@ export const onTrajectoryComplete = async (c: Context) => {
duration,
errorDetail,
errorMessage,
+ executionId,
llmCalls,
steps,
toolCalls,
+ topicId,
totalTokens,
} = body;
@@ -63,7 +65,7 @@ export const onTrajectoryComplete = async (c: Context) => {
// Check if run was aborted β€” skip processing to avoid overwriting abort state
const runModel = new AgentEvalRunModel(db, userId, wsId);
- const run = await runModel.findById(runId);
+ const run = await runModel.findSummaryById(runId);
if (run?.status === 'aborted') {
log('Run aborted, skipping: runId=%s testCaseId=%s', runId, testCaseId);
return c.json({ cancelled: true });
@@ -72,6 +74,7 @@ export const onTrajectoryComplete = async (c: Context) => {
const service = new AgentEvalRunService(db, userId, wsId);
const { allDone, completedCount } = await service.recordTrajectoryCompletion({
+ executionId,
runId,
status,
telemetry: {
@@ -86,6 +89,7 @@ export const onTrajectoryComplete = async (c: Context) => {
totalTokens,
},
testCaseId,
+ topicId,
});
log('Completion check: %d completed, allDone=%s', completedCount, allDone);
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/__tests__/runBenchmark.test.ts b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/__tests__/runBenchmark.test.ts
new file mode 100644
index 00000000000..006a833074d
--- /dev/null
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/__tests__/runBenchmark.test.ts
@@ -0,0 +1,129 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createStepRunner } from '@/server/workflows/testing/stepContext';
+
+import { runBenchmarkHandler } from '../runBenchmark';
+
+const mocks = vi.hoisted(() => ({
+ filterTestCasesNeedingExecution: vi.fn(),
+ findByDatasetId: vi.fn(),
+ findSummaryById: vi.fn(),
+ finalize: vi.fn(),
+ triggerPaginateTestCases: vi.fn(),
+ update: vi.fn(),
+}));
+
+vi.mock('@/database/server', () => ({ getServerDB: vi.fn().mockResolvedValue({}) }));
+vi.mock('@/database/models/agentEval', () => ({
+ AgentEvalRunModel: class {
+ findSummaryById = mocks.findSummaryById;
+ finalize = mocks.finalize;
+ update = mocks.update;
+ },
+ // A fresh run has no RunTopic yet: nothing is counted before it starts.
+ AgentEvalRunTopicModel: class {
+ findByRunId = async () => [];
+ },
+ AgentEvalTestCaseModel: class {
+ findByDatasetId = mocks.findByDatasetId;
+ },
+}));
+vi.mock('@/server/workflows/agentEvalRun', () => ({
+ AgentEvalRunWorkflow: {
+ filterTestCasesNeedingExecution: mocks.filterTestCasesNeedingExecution,
+ triggerPaginateTestCases: mocks.triggerPaginateTestCases,
+ },
+}));
+vi.mock('@/server/workflows/agentEvalRun/utils', () => ({
+ resolveAgentEvalRunWorkspace: vi.fn().mockResolvedValue(undefined),
+}));
+
+const cases = ['a', 'b', 'c'].map((caseId) => ({ id: `case-${caseId}`, metadata: { caseId } }));
+
+const context = (payload: Record<string, unknown>) =>
+ ({
+ requestPayload: { runId: 'run-1', userId: 'u1', ...payload },
+ run: createStepRunner(),
+ }) as any;
+
+describe('runBenchmarkHandler', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.findByDatasetId.mockResolvedValue(cases);
+ // Every case the run owns still has a pending topic.
+ mocks.filterTestCasesNeedingExecution.mockImplementation(
+ async (_db, { testCaseIds }) => testCaseIds,
+ );
+ });
+
+ it('settles a previously created empty internal run with a generation-guarded failure', async () => {
+ const startedAt = new Date('2026-11-01T12:00:00Z');
+ mocks.findSummaryById.mockResolvedValue({
+ config: { caseSelection: { caseIds: ['a', 'b', 'c'], mode: 'exclude' } },
+ datasetId: 'ds-1',
+ startedAt,
+ status: 'pending',
+ });
+
+ expect(await runBenchmarkHandler(context({}))).toMatchObject({
+ success: false,
+ totalTestCases: 0,
+ });
+ expect(mocks.finalize).toHaveBeenCalledWith(
+ 'run-1',
+ { status: 'failed' },
+ { startedAt: startedAt.toISOString() },
+ );
+ expect(mocks.triggerPaginateTestCases).not.toHaveBeenCalled();
+ });
+
+ it.each([{ dryRun: true }, { external: true }])(
+ 'does not settle empty dry or external runs (%j)',
+ async ({ dryRun, external }) => {
+ mocks.findSummaryById.mockResolvedValue({
+ config: { executionMode: external ? 'external' : 'internal' },
+ datasetId: 'ds-1',
+ status: 'pending',
+ });
+ mocks.findByDatasetId.mockResolvedValue([]);
+ await runBenchmarkHandler(context({ dryRun }));
+ expect(mocks.finalize).not.toHaveBeenCalled();
+ },
+ );
+
+ it('counts only the cases the run selected as totalCases', async () => {
+ mocks.findSummaryById.mockResolvedValue({
+ config: { caseSelection: { caseIds: ['b'], mode: 'include' } },
+ datasetId: 'ds-1',
+ status: 'idle',
+ });
+
+ const result = await runBenchmarkHandler(context({}));
+
+ expect(result).toMatchObject({ success: true, toExecute: 1, totalTestCases: 1 });
+ expect(mocks.filterTestCasesNeedingExecution).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ testCaseIds: ['case-b'] }),
+ );
+ expect(mocks.update).toHaveBeenCalledWith(
+ 'run-1',
+ expect.objectContaining({
+ metrics: expect.objectContaining({ totalCases: 1 }),
+ status: 'running',
+ }),
+ );
+ expect(mocks.triggerPaginateTestCases).toHaveBeenCalledWith({ runId: 'run-1', userId: 'u1' });
+ });
+
+ it('counts the whole dataset when the run has no case selection', async () => {
+ mocks.findSummaryById.mockResolvedValue({ config: {}, datasetId: 'ds-1', status: 'idle' });
+
+ const result = await runBenchmarkHandler(context({}));
+
+ expect(result).toMatchObject({ success: true, totalTestCases: 3 });
+ expect(mocks.update).toHaveBeenCalledWith(
+ 'run-1',
+ expect.objectContaining({ metrics: expect.objectContaining({ totalCases: 3 }) }),
+ );
+ });
+});
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/checkpointPayloads.test.ts b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/checkpointPayloads.test.ts
new file mode 100644
index 00000000000..225be734e21
--- /dev/null
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/checkpointPayloads.test.ts
@@ -0,0 +1,222 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { serializeStepResult } from '@/server/workflows/testing/stepContext';
+
+import { executeTestCaseHandler } from './executeTestCase';
+import { finalizeRunHandler } from './finalizeRun';
+import { runBenchmarkHandler } from './runBenchmark';
+
+const mocks = vi.hoisted(() => ({
+ aggregate: vi.fn(),
+ cases: vi.fn(),
+ finalize: vi.fn(),
+ findFull: vi.fn(),
+ findSummary: vi.fn(),
+ topics: vi.fn(),
+ triggerTrajectory: vi.fn(),
+ update: vi.fn(),
+}));
+vi.mock('@/database/server', () => ({ getServerDB: vi.fn().mockResolvedValue({}) }));
+vi.mock('@/database/models/agentEval', () => ({
+ AgentEvalRunModel: class {
+ findById = mocks.findFull;
+ findSummaryById = mocks.findSummary;
+ finalize = mocks.finalize;
+ update = mocks.update;
+ },
+ AgentEvalTestCaseModel: class {
+ findByDatasetId = mocks.cases;
+ },
+ AgentEvalRunTopicModel: class {
+ findByRunId = mocks.topics;
+ },
+}));
+vi.mock('@/server/services/agentEvalRun', () => ({
+ AgentEvalRunService: class {
+ evaluateAndFinalizeRun = mocks.aggregate;
+ },
+}));
+vi.mock('@/server/workflows/agentEvalRun', () => ({
+ AgentEvalRunWorkflow: {
+ filterTestCasesNeedingExecution: async (
+ _: unknown,
+ { testCaseIds }: { testCaseIds: string[] },
+ ) => testCaseIds,
+ triggerPaginateTestCases: vi.fn(),
+ triggerRunAgentTrajectory: mocks.triggerTrajectory,
+ },
+}));
+vi.mock('@/server/workflows/agentEvalRun/utils', () => ({
+ resolveAgentEvalRunWorkspace: vi.fn().mockResolvedValue(undefined),
+}));
+
+const bulkyRun = (caseCount: number) => ({
+ config: {
+ k: 3,
+ connectorSnapshots: Object.fromEntries(
+ Array.from({ length: caseCount }, (_, index) => [
+ `case-${index}`,
+ { manifest: 'large frozen original contract '.repeat(2000) },
+ ]),
+ ),
+ },
+ datasetId: 'dataset',
+ id: 'run',
+ metrics: { totalCases: 50 },
+ startedAt: new Date('2026-11-04T12:00:00Z'),
+ status: 'idle',
+});
+const checkpointContext = (legacy: Record<string, unknown> = {}) => {
+ const outputs: Record<string, unknown> = {};
+ const context = {
+ requestPayload: { runId: 'run', testCaseId: 'case-0', userId: 'owner' },
+ run: vi.fn(async (name: string, callback: () => Promise<unknown>) => {
+ const value = Object.hasOwn(legacy, name) ? legacy[name] : await callback();
+ outputs[name] = serializeStepResult(value);
+ return outputs[name];
+ }),
+ };
+ return { context: context as any, outputs };
+};
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.findFull.mockRejectedValue(new Error('Workflow must not read a full run'));
+ mocks.findSummary.mockResolvedValue(bulkyRun(50));
+ mocks.cases.mockResolvedValue([
+ { content: { input: 'Private case body'.repeat(1000) }, id: 'case-0' },
+ ]);
+ mocks.update.mockResolvedValue(bulkyRun(50));
+ mocks.finalize.mockResolvedValue(bulkyRun(50));
+ mocks.topics.mockResolvedValue([
+ {
+ passed: true,
+ runId: 'run',
+ score: 1,
+ status: 'passed',
+ topicId: 'topic',
+ testCase: { content: 'Huge body'.repeat(1000) },
+ topic: { metadata: 'Unneeded joined topic' },
+ },
+ ]);
+ mocks.aggregate.mockResolvedValue({ averageScore: 1, passedCases: 1, totalCases: 1 });
+});
+
+describe('Evaluation workflow checkpoint boundaries', () => {
+ it('keeps execute-test-case status/k output independent of unrelated case snapshots', async () => {
+ const sizes: number[] = [];
+ for (const count of [1, 50]) {
+ mocks.findSummary.mockResolvedValue(bulkyRun(count));
+ const { context, outputs } = checkpointContext();
+ expect(await executeTestCaseHandler(context)).toMatchObject({ k: 3, success: true });
+ expect(outputs['agent-eval-run:get-run']).toEqual({ config: { k: 3 }, status: 'idle' });
+ sizes.push(Buffer.byteLength(JSON.stringify(outputs)));
+ }
+ expect(sizes[0]).toBe(sizes[1]);
+ expect(mocks.findFull).not.toHaveBeenCalled();
+ });
+
+ it('checkpoints selected case IDs and discards unused update return rows', async () => {
+ const { context, outputs } = checkpointContext();
+ await runBenchmarkHandler(context);
+ expect(outputs['agent-eval-run:get-test-cases']).toEqual(['case-0']);
+ expect(outputs['agent-eval-run:update-status']).toBeUndefined();
+ expect(JSON.stringify(outputs)).not.toMatch(
+ /connectorSnapshots|Private case body|large frozen/,
+ );
+ expect(Buffer.byteLength(JSON.stringify(outputs))).toBeLessThan(500);
+ expect(mocks.update).toHaveBeenCalledWith(
+ 'run',
+ expect.objectContaining({ metrics: expect.objectContaining({ totalCases: 1 }) }),
+ );
+ });
+
+ it('counts the cases a rerun keeps as soon as the run restarts, not 0 done', async () => {
+ mocks.topics.mockResolvedValue([
+ {
+ evalResult: { completionReason: 'stop', cost: 0.01 },
+ passed: true,
+ runId: 'run',
+ status: 'passed',
+ topicId: 'kept',
+ },
+ { evalResult: null, passed: null, runId: 'run', status: 'pending', topicId: 'rerun' },
+ ]);
+ const { context } = checkpointContext();
+ await runBenchmarkHandler(context);
+ expect(mocks.update).toHaveBeenCalledWith(
+ 'run',
+ expect.objectContaining({
+ metrics: expect.objectContaining({ completedCases: 1, passedCases: 1, totalCases: 1 }),
+ status: 'running',
+ }),
+ );
+ });
+
+ it('continues replay of an older full run and full case-object checkpoint', async () => {
+ const { context } = checkpointContext({
+ 'agent-eval-run:get-run': bulkyRun(50),
+ 'agent-eval-run:get-test-cases': [
+ { id: 'legacy-case', content: { input: 'Old checkpoint content' } },
+ ],
+ });
+ expect(await runBenchmarkHandler(context)).toMatchObject({ success: true, totalTestCases: 1 });
+ expect(mocks.findSummary).not.toHaveBeenCalled();
+ expect(mocks.cases).not.toHaveBeenCalled();
+ expect(mocks.update).toHaveBeenCalledWith(
+ 'run',
+ expect.objectContaining({ metrics: expect.objectContaining({ totalCases: 1 }) }),
+ );
+ });
+
+ it('stores only aggregate topic fields and a boolean finalization result', async () => {
+ const { context, outputs } = checkpointContext();
+ await finalizeRunHandler(context);
+ expect(outputs['agent-eval-run:update-run']).toBe(true);
+ expect(JSON.stringify(outputs)).not.toMatch(
+ /connectorSnapshots|Huge body|Unneeded joined topic|large frozen/,
+ );
+ expect(outputs['agent-eval-run:get-run-topics']).toEqual([
+ { passed: true, runId: 'run', score: 1, status: 'passed', topicId: 'topic' },
+ ]);
+ expect(mocks.finalize).toHaveBeenCalledWith('run', expect.anything(), {
+ startedAt: '2026-11-04T12:00:00.000Z',
+ });
+ });
+
+ it.each([
+ ['cancelled', false],
+ ['legacy row', { id: 'legacy-finalized-run', config: bulkyRun(50).config }],
+ ])('accepts a %s finalization checkpoint', async (_, finalized) => {
+ const { context } = checkpointContext({ 'agent-eval-run:update-run': finalized });
+ expect(await finalizeRunHandler(context)).toMatchObject(
+ finalized ? { success: true } : { cancelled: true },
+ );
+ expect(mocks.finalize).not.toHaveBeenCalled();
+ });
+
+ it('finalizes with metrics from the verdicts as they are when it finalizes, not the earlier checkpoint', async () => {
+ const stale = [
+ { passed: false, runId: 'run', score: 0, status: 'failed', topicId: 'a' },
+ { passed: null, runId: 'run', score: null, status: 'running', topicId: 'b' },
+ ];
+ const current = [
+ { passed: false, runId: 'run', score: 0, status: 'failed', topicId: 'a' },
+ { passed: true, runId: 'run', score: 1, status: 'passed', topicId: 'b' },
+ ];
+ const { context } = checkpointContext({ 'agent-eval-run:get-run-topics': stale });
+ mocks.topics.mockResolvedValue(current);
+ mocks.aggregate.mockImplementation(async ({ runTopics }) => ({
+ averageScore: 0.5,
+ passedCases: runTopics.filter((topic: { status: string }) => topic.status === 'passed')
+ .length,
+ totalCases: runTopics.length,
+ }));
+ await finalizeRunHandler(context);
+ expect(mocks.finalize).toHaveBeenCalledWith(
+ 'run',
+ { metrics: expect.objectContaining({ passedCases: 1, totalCases: 2 }), status: 'completed' },
+ expect.anything(),
+ );
+ });
+});
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/executeTestCase.ts b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/executeTestCase.ts
index 9d5ce5932b5..b6f7ae63048 100644
--- a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/executeTestCase.ts
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/executeTestCase.ts
@@ -30,7 +30,9 @@ export const executeTestCaseHandler = async (context: WorkflowContext<ExecuteTes
// Get run to get K value from config
const run = await runStep(context, 'agent-eval-run:get-run', async () => {
const runModel = new AgentEvalRunModel(db, userId, wsId);
- return runModel.findById(runId);
+ const run = await runModel.findSummaryById(runId);
+ // Keep the consumed shape compatible with older full-row checkpoints.
+ return run ? { config: { k: run.config?.k }, status: run.status } : undefined;
});
if (!run) {
@@ -58,10 +60,17 @@ export const executeTestCaseHandler = async (context: WorkflowContext<ExecuteTes
return { k, success: true, testCaseId };
};
+/**
+ * How many cases of all runs execute at once. The default suits a cloud deployment; a single
+ * provider route (one OpenRouter model, a dev machine) drops requests well below it, so
+ * AGENT_EVAL_CASE_PARALLELISM lowers it without a code change.
+ */
+const CASE_PARALLELISM = Number(process.env.AGENT_EVAL_CASE_PARALLELISM) || 200;
+
export const executeTestCaseWorkflowOptions = {
flowControl: {
key: 'agent-eval-run.execute-test-case',
- parallelism: 200,
+ parallelism: CASE_PARALLELISM,
ratePerSecond: 5,
},
};
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/finalizeRun.ts b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/finalizeRun.ts
index 2d21b4094f2..48e4241eea2 100644
--- a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/finalizeRun.ts
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/finalizeRun.ts
@@ -21,6 +21,15 @@ const log = debug('lobe-server:workflows:finalize-run');
* 3. Aggregate metrics across all RunTopics
* 4. Update run status to 'completed'
*/
+type RunMetrics = Awaited<ReturnType<AgentEvalRunService['evaluateAndFinalizeRun']>>;
+
+/** external: a topic awaits external scoring; failed: every case errored or timed out. */
+const statusOf = (metrics: RunMetrics) => {
+ const nonSuccessCases = (metrics.errorCases || 0) + (metrics.timeoutCases || 0);
+ if ((metrics.externalCases || 0) > 0) return 'external' as const;
+ return nonSuccessCases >= metrics.totalCases ? ('failed' as const) : ('completed' as const);
+};
+
export const finalizeRunHandler = async (context: WorkflowContext<FinalizeRunPayload>) => {
const { runId, userId } = context.requestPayload ?? {};
@@ -36,7 +45,15 @@ export const finalizeRunHandler = async (context: WorkflowContext<FinalizeRunPay
// Step 1: Get run details
const run = await runStep(context, 'agent-eval-run:get-run', async () => {
const runModel = new AgentEvalRunModel(db, userId, wsId);
- return runModel.findById(runId);
+ const row = await runModel.findSummaryById(runId);
+ return row
+ ? {
+ config: { k: row.config?.k },
+ metrics: row.metrics,
+ startedAt: row.startedAt,
+ status: row.status,
+ }
+ : undefined;
});
if (!run) {
@@ -51,7 +68,16 @@ export const finalizeRunHandler = async (context: WorkflowContext<FinalizeRunPay
// Step 2: Get all RunTopics (already evaluated in recordTrajectoryCompletion)
const runTopics = await runStep(context, 'agent-eval-run:get-run-topics', async () => {
const runTopicModel = new AgentEvalRunTopicModel(db, userId, wsId);
- return runTopicModel.findByRunId(runId);
+ return (await runTopicModel.findByRunId(runId)).map(
+ ({ evalResult, passed, runId, score, status, topicId }) => ({
+ evalResult,
+ passed,
+ runId,
+ score,
+ status,
+ topicId,
+ }),
+ );
});
log('Total RunTopics: %d', runTopics.length);
@@ -71,16 +97,37 @@ export const finalizeRunHandler = async (context: WorkflowContext<FinalizeRunPay
// external: any topic awaits external scoring β†’ whole run waits too
// failed: all cases are non-success (error/timeout)
// completed: everything else
- const nonSuccessCases = (metrics.errorCases || 0) + (metrics.timeoutCases || 0);
- const externalCount = metrics.externalCases || 0;
- const runStatus =
- externalCount > 0 ? 'external' : nonSuccessCases >= metrics.totalCases ? 'failed' : 'completed';
+ const runStatus = statusOf(metrics);
- await runStep(context, 'agent-eval-run:update-run', async () => {
+ const finalized = await runStep(context, 'agent-eval-run:update-run', async () => {
+ // Steps 2-3 are checkpoints that may predate the last verdicts: finalization
+ // only succeeds once no case is pending or running, so it must write metrics
+ // aggregated from the topics as they are now, in this same step.
+ const runTopicModel = new AgentEvalRunTopicModel(db, userId, wsId);
+ const currentTopics = (await runTopicModel.findByRunId(runId)).map(
+ ({ evalResult, passed, runId, score, status, topicId }) => ({
+ evalResult,
+ passed,
+ runId,
+ score,
+ status,
+ topicId,
+ }),
+ );
+ const current = await new AgentEvalRunService(db, userId, wsId).evaluateAndFinalizeRun({
+ run: { config: run.config, id: runId, metrics: run.metrics, startedAt: run.startedAt },
+ runTopics: currentTopics,
+ });
const runModel = new AgentEvalRunModel(db, userId, wsId);
- return runModel.update(runId, { metrics, status: runStatus });
+ return !!(await runModel.finalize(
+ runId,
+ { metrics: current, status: statusOf(current) },
+ { startedAt: run.startedAt },
+ ));
});
+ if (!finalized) return { cancelled: true };
+
console.info(
`[finalize-run] Run ${runId} ${runStatus}: score=${metrics.averageScore.toFixed(2)} pass=${metrics.passedCases}/${metrics.totalCases} error=${metrics.errorCases || 0}`,
);
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/paginateTestCases.ts b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/paginateTestCases.ts
index 6b47cc5d0fb..a4676490c49 100644
--- a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/paginateTestCases.ts
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/paginateTestCases.ts
@@ -4,6 +4,7 @@ import { chunk } from 'es-toolkit/compat';
import { AgentEvalRunModel, AgentEvalTestCaseModel } from '@/database/models/agentEval';
import { getServerDB } from '@/database/server';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
import {
AgentEvalRunWorkflow,
type PaginateTestCasesPayload,
@@ -59,7 +60,7 @@ export const paginateTestCasesHandler = async (
// Check if run was aborted before paginating
const runStatus = await runStep(context, 'agent-eval-run:check-abort', async () => {
const runModel = new AgentEvalRunModel(db, userId, wsId);
- const run = await runModel.findById(runId);
+ const run = await runModel.findSummaryById(runId);
return run?.status;
});
@@ -68,11 +69,23 @@ export const paginateTestCasesHandler = async (
return { cancelled: true };
}
+ // A run with a concurrency limit starts only as many cases as it allows; each
+ // case that ends starts the next waiting one (see services/agentEvalRun/queue).
+ if (!cursor) {
+ const queued = await runStep(context, 'agent-eval-run:dispatch-queued', () =>
+ new AgentEvalRunService(db, userId, wsId).dispatchQueuedCases(runId),
+ );
+ if (queued) {
+ log('Queued run: started %d cases', queued.length);
+ return { queuedStarted: queued.length, success: true };
+ }
+ }
+
// Paginate through test cases
const testCaseBatch = await runStep(context, 'agent-eval-run:get-test-cases-page', async () => {
// Get run to find datasetId and userId
const runModel = new AgentEvalRunModel(db, userId, wsId);
- const run = await runModel.findById(runId);
+ const run = await runModel.findSummaryById(runId);
if (!run) return { ids: [] };
// Get test cases for this dataset
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runAgentTrajectory.test.ts b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runAgentTrajectory.test.ts
new file mode 100644
index 00000000000..067b3a54b22
--- /dev/null
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runAgentTrajectory.test.ts
@@ -0,0 +1,62 @@
+import type { WorkflowContext } from '@upstash/workflow';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { RunAgentTrajectoryPayload } from '@/server/workflows/agentEvalRun';
+
+import { runAgentTrajectoryHandler } from './runAgentTrajectory';
+
+const mocks = vi.hoisted(() => ({
+ complete: vi.fn(),
+ execute: vi.fn(),
+ load: vi.fn(),
+ multi: vi.fn(),
+}));
+vi.mock('@/database/server', () => ({ getServerDB: vi.fn().mockResolvedValue({}) }));
+vi.mock('@/server/services/agentEvalRun', () => ({
+ AgentEvalRunService: vi.fn().mockImplementation(function () {
+ return {
+ executeMultiThreadTrajectory: mocks.multi,
+ executeTrajectory: mocks.execute,
+ loadTrajectoryData: mocks.load,
+ recordTrajectoryCompletion: mocks.complete,
+ };
+ }),
+}));
+vi.mock('@/server/workflows/agentEvalRun', () => ({
+ AgentEvalRunWorkflow: { triggerFinalizeRun: vi.fn() },
+}));
+vi.mock('@/server/workflows/agentEvalRun/utils', () => ({
+ resolveAgentEvalRunWorkspace: vi.fn().mockResolvedValue(undefined),
+}));
+vi.mock('@/server/workflows/step', () => ({
+ runStep: (_: unknown, __: string, fn: () => unknown) => fn(),
+}));
+const context = {
+ requestPayload: { runId: 'run', testCaseId: 'case', userId: 'user' },
+} as WorkflowContext<RunAgentTrajectoryPayload>;
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.execute.mockReset();
+ mocks.multi.mockReset();
+ mocks.complete.mockResolvedValue({ allDone: false });
+});
+
+describe('runAgentTrajectory generation boundary', () => {
+ it.each([1, 2])('returns cancellation when k=%s loses its execution claim', async (k) => {
+ mocks.load.mockResolvedValue({ run: { config: { k } }, testCase: {} });
+ expect(await runAgentTrajectoryHandler(context)).toEqual({ cancelled: true });
+ expect(mocks.complete).not.toHaveBeenCalled();
+ });
+ it('forwards a startup failure with its claimed execution and topic IDs', async () => {
+ mocks.load.mockResolvedValue({ run: {}, testCase: {} });
+ mocks.execute.mockResolvedValue({
+ error: 'provider unavailable',
+ executionId: 'generation',
+ topicId: 'topic',
+ });
+ await runAgentTrajectoryHandler(context);
+ expect(mocks.complete).toHaveBeenCalledWith(
+ expect.objectContaining({ executionId: 'generation', topicId: 'topic', status: 'error' }),
+ );
+ });
+});
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runAgentTrajectory.ts b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runAgentTrajectory.ts
index 8c4f095d825..5e484868917 100644
--- a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runAgentTrajectory.ts
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runAgentTrajectory.ts
@@ -57,6 +57,8 @@ export const runAgentTrajectoryHandler = async (
service.executeMultiThreadTrajectory({ k, run, runId, testCaseId }),
);
+ if (!result) return { cancelled: true };
+
log(
'Multi-thread started: runId=%s testCaseId=%s k=%d threads=%d',
runId,
@@ -79,10 +81,14 @@ export const runAgentTrajectoryHandler = async (
service.executeTrajectory({ environment, envPrompt, run, runId, testCase, testCaseId }),
);
+ if (!result || ('cancelled' in result && result.cancelled)) return { cancelled: true };
+
// If execAgent failed, record completion and check if run should be finalized
if ('error' in result) {
await runStep(context, 'agent-eval-run:handle-exec-error', async () => {
const { allDone } = await service.recordTrajectoryCompletion({
+ executionId: result.executionId,
+ topicId: result.topicId,
runId,
status: 'error',
telemetry: { completionReason: 'error', errorMessage: result.error as string },
@@ -112,10 +118,13 @@ export const runAgentTrajectoryHandler = async (
};
};
+/** Trajectories (one per attempt, pass@k threads included) in flight at once; see executeTestCase. */
+const TRAJECTORY_PARALLELISM = Number(process.env.AGENT_EVAL_TRAJECTORY_PARALLELISM) || 500;
+
export const runAgentTrajectoryWorkflowOptions = {
flowControl: {
key: 'agent-eval-run.run-agent-trajectory',
- parallelism: 500,
+ parallelism: TRAJECTORY_PARALLELISM,
ratePerSecond: 20,
},
};
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runBenchmark.ts b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runBenchmark.ts
index 2e78acdc018..8f8c36b1875 100644
--- a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runBenchmark.ts
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runBenchmark.ts
@@ -1,8 +1,14 @@
import { type WorkflowContext } from '@upstash/workflow';
import debug from 'debug';
-import { AgentEvalRunModel, AgentEvalTestCaseModel } from '@/database/models/agentEval';
+import {
+ AgentEvalRunModel,
+ AgentEvalRunTopicModel,
+ AgentEvalTestCaseModel,
+} from '@/database/models/agentEval';
import { getServerDB } from '@/database/server';
+import { selectCases } from '@/server/services/agentEvalRun/caseSelection';
+import { runProgressOf } from '@/server/services/agentEvalRun/progress';
import { AgentEvalRunWorkflow, type RunBenchmarkPayload } from '@/server/workflows/agentEvalRun';
import { resolveAgentEvalRunWorkspace } from '@/server/workflows/agentEvalRun/utils';
import { runStep } from '@/server/workflows/step';
@@ -32,7 +38,20 @@ export const runBenchmarkHandler = async (context: WorkflowContext<RunBenchmarkP
const runModel = new AgentEvalRunModel(db, userId, wsId);
// Get run info
- const run = await runStep(context, 'agent-eval-run:get-run', () => runModel.findById(runId));
+ const run = await runStep(context, 'agent-eval-run:get-run', async () => {
+ const row = await runModel.findSummaryById(runId);
+ return row
+ ? {
+ config: {
+ caseSelection: row.config?.caseSelection,
+ executionMode: row.config?.executionMode,
+ },
+ datasetId: row.datasetId,
+ startedAt: row.startedAt,
+ status: row.status,
+ }
+ : undefined;
+ });
if (!run) {
return { error: 'Run not found', success: false };
@@ -43,19 +62,36 @@ export const runBenchmarkHandler = async (context: WorkflowContext<RunBenchmarkP
return { error: 'Run is already running', success: false };
}
- // Get all test cases
+ // The run's cases: the dataset narrowed by `config.caseSelection`, the same
+ // rule createRun pre-created the run's topics with. Counting the whole
+ // dataset here would set a `totalCases` a partial run can never reach, so
+ // it would stay `running` after its last case finished.
const testCaseModel = new AgentEvalTestCaseModel(db, userId, wsId);
- const allTestCases = await runStep(context, 'agent-eval-run:get-test-cases', () =>
- testCaseModel.findByDatasetId(run.datasetId),
+ const allTestCases = await runStep(
+ context,
+ 'agent-eval-run:get-test-cases',
+ async (): Promise<Array<string | { id: string }>> =>
+ selectCases(
+ await testCaseModel.findByDatasetId(run.datasetId),
+ run.config?.caseSelection,
+ ).map((testCase) => testCase.id),
);
- const allTestCaseIds = allTestCases.map((tc: { id: string }) => tc.id);
+ // Existing durable checkpoints contain full case objects; new ones contain only IDs.
+ const allTestCaseIds = allTestCases.map((testCase) =>
+ typeof testCase === 'string' ? testCase : testCase.id,
+ );
log('Total test cases: %d', allTestCaseIds.length);
if (allTestCaseIds.length === 0) {
+ if (!dryRun && run.config?.executionMode !== 'external') {
+ await runStep(context, 'agent-eval-run:fail-empty-selection', async () => {
+ await runModel.finalize(runId, { status: 'failed' }, { startedAt: run.startedAt });
+ });
+ }
return {
- error: 'No test cases in dataset',
+ error: 'No test cases selected for this run',
success: false,
totalTestCases: 0,
};
@@ -101,19 +137,21 @@ export const runBenchmarkHandler = async (context: WorkflowContext<RunBenchmarkP
}
// Update run status to 'running'
- await runStep(context, 'agent-eval-run:update-status', () =>
- runModel.update(runId, {
+ await runStep(context, 'agent-eval-run:update-status', async () => {
+ // Cases kept from before (a rerun replaces only the unverified ones) count
+ // from the start, instead of showing 0 done until the next case ends.
+ const kept = await new AgentEvalRunTopicModel(db, userId, wsId).findByRunId(runId);
+ await runModel.update(runId, {
metrics: {
averageScore: 0,
- failedCases: 0,
passRate: 0,
- passedCases: 0,
+ ...runProgressOf(kept),
totalCases: allTestCaseIds.length,
},
startedAt: new Date(),
status: 'running',
- }),
- );
+ });
+ });
// Trigger paginate-test-cases workflow
log('Triggering paginate-test-cases for run %s', runId);
diff --git a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runThreadTrajectory.ts b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runThreadTrajectory.ts
index 5ec4517f7d8..46d99da4943 100644
--- a/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runThreadTrajectory.ts
+++ b/apps/server/src/router-hono/workflows/agent-eval-run/workflows/runThreadTrajectory.ts
@@ -19,7 +19,8 @@ const log = debug('lobe-server:workflows:run-thread-trajectory');
export const runThreadTrajectoryHandler = async (
context: WorkflowContext<RunThreadTrajectoryPayload>,
) => {
- const { runId, testCaseId, threadId, topicId, userId } = context.requestPayload ?? {};
+ const { executionId, runId, testCaseId, threadId, topicId, userId } =
+ context.requestPayload ?? {};
log('Starting: runId=%s testCaseId=%s threadId=%s', runId, testCaseId, threadId);
@@ -40,6 +41,7 @@ export const runThreadTrajectoryHandler = async (
// Record thread as errored so aggregation can proceed
await runStep(context, 'thread-trajectory:handle-load-error', async () => {
await service.recordThreadCompletion({
+ executionId,
runId,
status: 'error',
telemetry: { completionReason: 'error', errorMessage: data.error },
@@ -61,6 +63,7 @@ export const runThreadTrajectoryHandler = async (
// Step 2: Execute agent for this thread
const result = await runStep(context, 'thread-trajectory:exec-agent', () =>
service.executeThreadTrajectory({
+ executionId,
envPrompt,
run,
runId,
@@ -77,6 +80,7 @@ export const runThreadTrajectoryHandler = async (
// Check if all threads are done and handle finalization.
await runStep(context, 'thread-trajectory:handle-exec-error', async () => {
const { allRunDone } = await service.recordThreadCompletion({
+ executionId: result.executionId,
runId,
status: 'error',
telemetry: { completionReason: 'error', errorMessage: result.error },
diff --git a/apps/server/src/routers/lambda/__tests__/evalRunConfig.schema.test.ts b/apps/server/src/routers/lambda/__tests__/evalRunConfig.schema.test.ts
index e1a9647e100..e249be26d93 100644
--- a/apps/server/src/routers/lambda/__tests__/evalRunConfig.schema.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/evalRunConfig.schema.test.ts
@@ -1,6 +1,20 @@
import { describe, expect, it } from 'vitest';
-import { evalCaseSelectionSchema } from '../evalRunConfig.schema';
+import {
+ evalCaseSelectionSchema,
+ evalRunChatConfigSchema,
+ evalRunInputConfigSchema,
+} from '../evalRunConfig.schema';
+
+it('does not accept client-authored mock connection snapshots', () => {
+ expect(
+ evalRunInputConfigSchema.parse({
+ connectorSnapshots: { case: { mock: { connectorId: 'foreign', fingerprint: 'forged' } } },
+ model: 'test-model',
+ provider: 'test-provider',
+ }),
+ ).toEqual({ model: 'test-model', provider: 'test-provider' });
+});
describe('evalCaseSelectionSchema', () => {
describe('canonical "all" β€” normalizes to omission', () => {
@@ -79,3 +93,23 @@ describe('evalCaseSelectionSchema', () => {
});
});
});
+
+describe('evalRunChatConfigSchema', () => {
+ it('accepts the model settings the chat model-params panel offers', () => {
+ const input = {
+ enableReasoning: true,
+ gpt5_6ReasoningEffort: 'max',
+ glm5_3ReasoningEffort: 'low',
+ textVerbosity: 'low',
+ thinkingLevel3: 'medium',
+ };
+ expect(evalRunChatConfigSchema.parse(input)).toEqual(input);
+ });
+
+ it('rejects values a model setting does not have, and fields that are not model settings', () => {
+ expect(evalRunChatConfigSchema.safeParse({ glm5_3ReasoningEffort: 'medium' }).success).toBe(
+ false,
+ );
+ expect(evalRunChatConfigSchema.safeParse({ systemRole: 'x' }).success).toBe(false);
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/integration/agentEval.createRun.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/agentEval.createRun.integration.test.ts
new file mode 100644
index 00000000000..8a7157cd8c0
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/agentEval.createRun.integration.test.ts
@@ -0,0 +1,210 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import {
+ agentEvalBenchmarks,
+ agentEvalDatasets,
+ agentEvalRuns,
+ agentEvalRunTopics,
+ agentEvalTestCases,
+ agents,
+ topics,
+ workspaceMembers,
+ workspaces,
+} from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentEvalRouter } from '../../agentEval';
+import { cleanupTestUser, createTestContext, createTestUser } from './setup';
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {};
+ }),
+}));
+
+let serverDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => serverDB),
+}));
+
+describe('Agent Eval run creation validation', () => {
+ let userId: string;
+ let otherUserId: string;
+ let benchmarkId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ await serverDB.delete(agentEvalRunTopics);
+ await serverDB.delete(topics);
+ await serverDB.delete(agentEvalRuns);
+ await serverDB.delete(agentEvalTestCases);
+ await serverDB.delete(agentEvalDatasets);
+ await serverDB.delete(agentEvalBenchmarks);
+ userId = await createTestUser(serverDB);
+ otherUserId = await createTestUser(serverDB);
+ const [benchmark] = await serverDB
+ .insert(agentEvalBenchmarks)
+ .values({ identifier: 'create-run-validation', isSystem: false, name: 'Cases', rubrics: [] })
+ .returning();
+ benchmarkId = benchmark.id;
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, otherUserId);
+ await cleanupTestUser(serverDB, userId);
+ });
+
+ const createDataset = async (ownerId: string | null, withCase = false, workspaceId?: string) => {
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({ benchmarkId, identifier: 'cases', name: 'Cases', userId: ownerId, workspaceId })
+ .returning();
+ if (withCase) {
+ await serverDB.insert(agentEvalTestCases).values({
+ content: { input: 'A plain case' },
+ datasetId: dataset.id,
+ metadata: { caseId: 'case-1' },
+ userId: ownerId,
+ workspaceId,
+ });
+ }
+ return dataset;
+ };
+
+ const expectNoRunArtifacts = async () => {
+ expect(await serverDB.select().from(agentEvalRuns)).toHaveLength(0);
+ expect(await serverDB.select().from(agentEvalRunTopics)).toHaveLength(0);
+ expect(await serverDB.select().from(topics)).toHaveLength(0);
+ expect(await serverDB.select().from(agents).where(eq(agents.virtual, true))).toHaveLength(0);
+ };
+
+ it.each(['internal', 'external'] as const)(
+ 'rejects a missing dataset with BAD_REQUEST before creating an %s run',
+ async (mode) => {
+ const caller = agentEvalRouter.createCaller(createTestContext(userId));
+
+ await expect(caller.createRun({ datasetId: 'missing-dataset', mode })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: 'Dataset not found',
+ });
+ await expectNoRunArtifacts();
+ },
+ );
+
+ it.each(['internal', 'external'] as const)(
+ 'returns the same not-found error for an inaccessible dataset in %s mode',
+ async (mode) => {
+ const dataset = await createDataset(otherUserId, true);
+ const caller = agentEvalRouter.createCaller(createTestContext(userId));
+
+ await expect(caller.createRun({ datasetId: dataset.id, mode })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: 'Dataset not found',
+ });
+ await expectNoRunArtifacts();
+ },
+ );
+
+ it('rejects an empty internal dataset without creating run artifacts', async () => {
+ const dataset = await createDataset(userId);
+ const caller = agentEvalRouter.createCaller(createTestContext(userId));
+
+ await expect(caller.createRun({ datasetId: dataset.id })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: 'Select at least one test case',
+ });
+ await expectNoRunArtifacts();
+ });
+
+ it('rejects an excluded-all internal selection without creating run artifacts', async () => {
+ const dataset = await createDataset(userId, true);
+ const caller = agentEvalRouter.createCaller(createTestContext(userId));
+
+ await expect(
+ caller.createRun({
+ config: { caseSelection: { caseIds: ['case-1'], mode: 'exclude' } },
+ datasetId: dataset.id,
+ }),
+ ).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: 'Select at least one test case',
+ });
+ await expectNoRunArtifacts();
+ });
+
+ it('pre-creates pending topics for a nonempty internal dataset', async () => {
+ const dataset = await createDataset(userId, true);
+ const caller = agentEvalRouter.createCaller(createTestContext(userId));
+
+ const run = await caller.createRun({ datasetId: dataset.id });
+
+ expect(run.status).toBe('idle');
+ expect(await serverDB.select().from(agentEvalRuns)).toHaveLength(1);
+ expect(await serverDB.select().from(agentEvalRunTopics)).toMatchObject([
+ { runId: run.id, status: 'pending' },
+ ]);
+ expect(await serverDB.select().from(topics)).toMatchObject([{ trigger: 'eval', userId }]);
+ });
+
+ it('allows an empty external dataset and leaves the run pending without topics', async () => {
+ const dataset = await createDataset(userId);
+ const caller = agentEvalRouter.createCaller(createTestContext(userId));
+
+ const run = await caller.createRun({ datasetId: dataset.id, mode: 'external' });
+
+ expect(run.status).toBe('pending');
+ expect(run.config).toMatchObject({ executionMode: 'external' });
+ expect(await serverDB.select().from(agentEvalRuns)).toHaveLength(1);
+ expect(await serverDB.select().from(agentEvalRunTopics)).toHaveLength(0);
+ expect(await serverDB.select().from(topics)).toHaveLength(0);
+ expect(await serverDB.select().from(agents).where(eq(agents.virtual, true))).toHaveLength(0);
+ });
+
+ it('allows a readable system dataset without claiming its ownership', async () => {
+ const dataset = await createDataset(null, true);
+ const caller = agentEvalRouter.createCaller(createTestContext(userId));
+
+ const run = await caller.createRun({ datasetId: dataset.id });
+
+ expect(run).toMatchObject({ datasetId: dataset.id, status: 'idle', userId });
+ expect(await serverDB.select().from(agentEvalRunTopics)).toMatchObject([
+ { runId: run.id, status: 'pending', userId },
+ ]);
+ expect(await serverDB.select().from(agentEvalDatasets)).toMatchObject([
+ { id: dataset.id, userId: null },
+ ]);
+ });
+
+ it("allows a workspace collaborator to run another member's dataset", async () => {
+ const [workspace] = await serverDB
+ .insert(workspaces)
+ .values({ name: 'Shared cases', primaryOwnerId: otherUserId, slug: `cases-${otherUserId}` })
+ .returning();
+ await serverDB.insert(workspaceMembers).values([
+ { role: 'owner', userId: otherUserId, workspaceId: workspace.id },
+ { role: 'member', userId, workspaceId: workspace.id },
+ ]);
+ const dataset = await createDataset(otherUserId, true, workspace.id);
+ const caller = agentEvalRouter.createCaller({
+ ...createTestContext(userId),
+ workspaceId: workspace.id,
+ });
+
+ const run = await caller.createRun({ datasetId: dataset.id });
+
+ expect(run).toMatchObject({
+ datasetId: dataset.id,
+ status: 'idle',
+ userId,
+ workspaceId: workspace.id,
+ });
+ expect(await serverDB.select().from(agentEvalRunTopics)).toMatchObject([
+ { runId: run.id, status: 'pending', userId, workspaceId: workspace.id },
+ ]);
+ expect(await serverDB.select().from(agentEvalDatasets)).toMatchObject([
+ { id: dataset.id, userId: otherUserId, workspaceId: workspace.id },
+ ]);
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/integration/agentEval.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/agentEval.integration.test.ts
index e4f48c105fb..200375bee49 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/agentEval.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/agentEval.integration.test.ts
@@ -65,6 +65,7 @@ describe('Agent Eval Router Integration Tests', () => {
afterEach(async () => {
await cleanupTestUser(serverDB, userId);
+ await cleanupTestUser(serverDB, 'user-2');
});
describe('Benchmark Operations', () => {
@@ -834,6 +835,7 @@ describe('Agent Eval Router Integration Tests', () => {
describe('Run Operations', () => {
let datasetId: string;
+ let testCaseId: string;
beforeEach(async () => {
const [benchmark] = await serverDB
@@ -857,6 +859,11 @@ describe('Agent Eval Router Integration Tests', () => {
})
.returning();
datasetId = dataset.id;
+ const [testCase] = await serverDB
+ .insert(agentEvalTestCases)
+ .values({ content: { input: 'Test question' }, datasetId, sortOrder: 1, userId })
+ .returning();
+ testCaseId = testCase.id;
});
describe('createRun', () => {
@@ -995,36 +1002,6 @@ describe('Agent Eval Router Integration Tests', () => {
name: 'Details Test Run',
});
- // Create test case
- const [testCase] = await serverDB
- .insert(agentEvalTestCases)
- .values({
- datasetId,
- content: { input: 'Test question' },
- sortOrder: 1,
- userId,
- })
- .returning();
-
- // Create topic
- const [topic] = await serverDB
- .insert(topics)
- .values({
- userId,
- title: 'Test Topic',
- trigger: 'eval',
- mode: 'test',
- })
- .returning();
-
- // Link run, topic, and test case
- await serverDB.insert(agentEvalRunTopics).values({
- userId,
- runId: run.id,
- topicId: topic.id,
- testCaseId: testCase.id,
- });
-
// Get details
const result = await caller.getRunDetails({ id: run.id });
@@ -1034,8 +1011,11 @@ describe('Agent Eval Router Integration Tests', () => {
expect(result.dataset).toBeDefined();
expect(result.dataset?.id).toBe(datasetId);
expect(result.topics).toHaveLength(1);
- expect((result.topics[0].topic as any).id).toBe(topic.id);
- expect((result.topics[0].testCase as any).id).toBe(testCase.id);
+ expect(result.topics[0]).toMatchObject({
+ status: 'pending',
+ testCase: { id: testCaseId },
+ topic: { id: expect.any(String), trigger: 'eval' },
+ });
});
it('should throw NOT_FOUND when run does not exist', async () => {
diff --git a/apps/server/src/routers/lambda/__tests__/integration/agentEval.payload.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/agentEval.payload.integration.test.ts
new file mode 100644
index 00000000000..7ed71f8b420
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/agentEval.payload.integration.test.ts
@@ -0,0 +1,227 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import {
+ agentEvalBenchmarks,
+ agentEvalDatasets,
+ agentEvalRuns,
+ agentEvalRunTopics,
+ agentEvalTestCases,
+ topics,
+} from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import type { EvalRunConfig } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentEvalExperimentModel, AgentEvalRunModel } from '@/database/models/agentEval';
+
+import { agentEvalRouter } from '../../agentEval';
+import { cleanupTestUser, createTestContext, createTestUser } from './setup';
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {};
+ }),
+}));
+
+vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return {};
+ }),
+}));
+
+let serverDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => serverDB),
+}));
+
+describe('Agent Eval UI payloads', () => {
+ let userId: string;
+ let otherUserId: string;
+ let datasetId: string;
+ let experimentId: string;
+ let runId: string;
+ let frozenConfig: EvalRunConfig;
+ const manifestMarker = 'frozen-contract-not-for-ui';
+ const settings: EvalRunConfig = {
+ agentSnapshot: { model: 'test-model', plugins: ['notion'], provider: 'test-provider' },
+ caseSelection: { mode: 'all' },
+ caseVersion: 'frozen-case-version',
+ chatConfig: { enableReasoning: true },
+ executionMode: 'internal',
+ k: 3,
+ maxSteps: 20,
+ model: 'test-model',
+ params: { temperature: 0.3 },
+ provider: 'test-provider',
+ timeout: 300_000,
+ };
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ userId = await createTestUser(serverDB);
+ otherUserId = await createTestUser(serverDB);
+ const [benchmark] = await serverDB
+ .insert(agentEvalBenchmarks)
+ .values({
+ identifier: 'payload-benchmark',
+ isSystem: false,
+ name: 'Payload',
+ rubrics: [],
+ userId,
+ })
+ .returning();
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({ benchmarkId: benchmark.id, identifier: 'payload-cases', name: 'Cases', userId })
+ .returning();
+ datasetId = dataset.id;
+ const experiment = await new AgentEvalExperimentModel(serverDB, userId).create({
+ benchmarkIds: [benchmark.id],
+ name: 'Payload experiment',
+ });
+ experimentId = experiment.id;
+
+ const cases = await serverDB
+ .insert(agentEvalTestCases)
+ .values(
+ Array.from({ length: 50 }, (_, index) => ({
+ content: { input: `Question ${index + 1}` },
+ datasetId,
+ userId,
+ })),
+ )
+ .returning();
+ frozenConfig = {
+ ...settings,
+ connectorSnapshots: Object.fromEntries(
+ cases.map((testCase) => [
+ testCase.id,
+ {
+ notion: {
+ connectorId: 'frozen-connection',
+ datasetId,
+ fingerprint: `frozen-${testCase.id}`,
+ manifest: {
+ api: [
+ {
+ description: `${manifestMarker}:${'x'.repeat(32_768)}`,
+ name: 'search',
+ parameters: { properties: { query: { type: 'string' } }, type: 'object' },
+ },
+ ],
+ identifier: 'notion',
+ meta: { title: 'Notion' },
+ type: 'mcp',
+ },
+ transport: 'mcp',
+ },
+ },
+ ]),
+ ),
+ };
+ const [run] = await serverDB
+ .insert(agentEvalRuns)
+ .values({ config: frozenConfig, datasetId, experimentId, name: 'Read payload', userId })
+ .returning();
+ runId = run.id;
+ const runTopics = await serverDB
+ .insert(topics)
+ .values(cases.map((_, index) => ({ title: `Case ${index + 1}`, userId })))
+ .returning();
+ await serverDB.insert(agentEvalRunTopics).values(
+ cases.map((testCase, index) => ({
+ runId,
+ status: 'pending',
+ testCaseId: testCase.id,
+ topicId: runTopics[index].id,
+ userId,
+ })),
+ );
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, otherUserId);
+ await cleanupTestUser(serverDB, userId);
+ });
+
+ it('keeps fifty frozen contracts in storage while omitting them from run and experiment reads', async () => {
+ const caller = agentEvalRouter.createCaller(createTestContext(userId));
+ const [list, detail, results, progress, experiments, experiment] = await Promise.all([
+ caller.listRuns({ datasetId }),
+ caller.getRunDetails({ id: runId }),
+ caller.getRunResults({ id: runId }),
+ caller.getRunProgress({ id: runId }),
+ caller.listExperiments(),
+ caller.getExperiment({ id: experimentId }),
+ ]);
+
+ expect(list.data).toHaveLength(1);
+ expect(results.results).toHaveLength(50);
+ expect(detail.topics).toHaveLength(50);
+ expect(list.data[0].config).toEqual(settings);
+ expect(detail.config).toEqual(settings);
+ expect(experiments.data[0].recentRuns?.[0].config).toEqual(settings);
+ expect(experiment.data.runs[0].config).toEqual(settings);
+
+ for (const response of [list, detail, results, progress, experiments, experiment]) {
+ const serialized = JSON.stringify(response);
+ expect(serialized).not.toContain('connectorSnapshots');
+ expect(serialized).not.toContain(manifestMarker);
+ // Detail includes all fifty case results; the frozen run alone exceeds 1.5 MB.
+ expect(Buffer.byteLength(serialized)).toBeLessThan(100_000);
+ }
+
+ const stored = await new AgentEvalRunModel(serverDB, userId).findById(runId);
+ expect(stored?.config).toEqual(frozenConfig);
+ expect(Object.keys(stored!.config!.connectorSnapshots!)).toHaveLength(50);
+ expect(Buffer.byteLength(JSON.stringify(stored))).toBeGreaterThan(1_500_000);
+ });
+
+ it('omits frozen contracts from benchmark recent-run previews', async () => {
+ const caller = agentEvalRouter.createCaller(createTestContext(userId));
+ const benchmarks = await caller.listBenchmarks({ includeSystem: false });
+
+ expect(benchmarks).toHaveLength(1);
+ expect(benchmarks[0].recentRuns).toHaveLength(1);
+ const run = benchmarks[0].recentRuns[0];
+ expect(!!run.config?.connectorSnapshots).toBe(false);
+ expect(run.config).toEqual(settings);
+ expect(run.id).toBe(runId);
+ expect(benchmarks[0]).toMatchObject({ datasetCount: 1, runCount: 1, testCaseCount: 50 });
+ expect(JSON.stringify(benchmarks)).not.toContain(manifestMarker);
+ expect(Buffer.byteLength(JSON.stringify(benchmarks))).toBeLessThan(10_000);
+
+ const stored = await new AgentEvalRunModel(serverDB, userId).findById(runId);
+ expect(stored?.config).toEqual(frozenConfig);
+ });
+
+ it('preserves server-owned frozen settings when a client edits the returned summary config', async () => {
+ const caller = agentEvalRouter.createCaller(createTestContext(userId));
+ const detail = await caller.getRunDetails({ id: runId });
+ await caller.updateRun({
+ config: { k: detail.config!.k!, maxSteps: 25, timeout: detail.config!.timeout! },
+ id: runId,
+ });
+
+ const [stored] = await serverDB.select().from(agentEvalRuns).where(eq(agentEvalRuns.id, runId));
+ expect(stored.config).toEqual({ ...frozenConfig, maxSteps: 25 });
+ });
+
+ it('keeps run and experiment summaries scoped to their owner', async () => {
+ const otherCaller = agentEvalRouter.createCaller(createTestContext(otherUserId));
+ expect((await otherCaller.listRuns({ datasetId })).data).toEqual([]);
+ expect((await otherCaller.listExperiments()).data).toEqual([]);
+ expect(await otherCaller.listBenchmarks({ includeSystem: false })).toEqual([]);
+ await Promise.all([
+ expect(otherCaller.getRunDetails({ id: runId })).rejects.toMatchObject({ code: 'NOT_FOUND' }),
+ expect(otherCaller.getRunResults({ id: runId })).rejects.toMatchObject({ code: 'NOT_FOUND' }),
+ expect(otherCaller.getRunProgress({ id: runId })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ }),
+ expect(otherCaller.getExperiment({ id: experimentId })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ }),
+ ]);
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentEval/benchmarkStandard.test.ts b/apps/server/src/routers/lambda/agentEval/benchmarkStandard.test.ts
new file mode 100644
index 00000000000..6864dcf8f1a
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/benchmarkStandard.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ assertNewBenchmarkStandard,
+ assertRunFollowsBenchmark,
+ benchmarkProtocolOf,
+ keepBenchmarkStandard,
+} from './benchmarkStandard';
+
+const judge = { model: 'gemini-3.8-flash', provider: 'google' };
+const protocol = { k: 3, maxSteps: 30, timeoutMinutes: 20 };
+const lobeBench = { judge, kind: 'lobe-bench', protocol };
+
+describe('Lobe Bench benchmark standard', () => {
+ it('requires a judge and run rules when a Lobe Bench benchmark is made, not an Evaluation Lab one', () => {
+ expect(() => assertNewBenchmarkStandard({ kind: 'lobe-bench', protocol })).toThrow(
+ 'judge model',
+ );
+ expect(() => assertNewBenchmarkStandard({ judge, kind: 'lobe-bench' })).toThrow('run rules');
+ expect(() =>
+ assertNewBenchmarkStandard({ ...lobeBench, protocol: { ...protocol, k: 9 } }),
+ ).toThrow();
+ expect(() => assertNewBenchmarkStandard(lobeBench)).not.toThrow();
+ expect(() => assertNewBenchmarkStandard({})).not.toThrow();
+ expect(() => assertNewBenchmarkStandard(undefined)).not.toThrow();
+ });
+
+ it('keeps the judge and run rules through any update', () => {
+ expect(
+ keepBenchmarkStandard(
+ {
+ judge: { model: 'other', provider: 'openrouter' },
+ kind: 'lobe-bench',
+ protocol: { k: 1, maxSteps: 80, timeoutMinutes: 60 },
+ },
+ lobeBench,
+ ),
+ ).toEqual(lobeBench);
+ expect(keepBenchmarkStandard({ kind: 'lobe-bench', name: 'x' }, lobeBench)).toEqual({
+ ...lobeBench,
+ name: 'x',
+ });
+ });
+
+ it('lets a benchmark made before the rules were fixed set them once', () => {
+ expect(keepBenchmarkStandard(lobeBench, { kind: 'lobe-bench' })).toEqual(lobeBench);
+ expect(() =>
+ keepBenchmarkStandard({ kind: 'lobe-bench', protocol: { k: 0 } }, { kind: 'lobe-bench' }),
+ ).toThrow('run rules');
+ expect(keepBenchmarkStandard({ name: 'x' }, { name: 'lab' })).toEqual({ name: 'x' });
+ });
+
+ it('reads older benchmarks’ complete defaults as their rules', () => {
+ expect(benchmarkProtocolOf({ defaults: protocol, kind: 'lobe-bench' })).toEqual(protocol);
+ expect(benchmarkProtocolOf({ defaults: { k: 3 }, kind: 'lobe-bench' })).toBeUndefined();
+ });
+
+ it('refuses a run that does not follow the benchmark’s judge and rules', () => {
+ const follows = {
+ judgeModel: judge.model,
+ judgeProvider: judge.provider,
+ k: 3,
+ maxSteps: 30,
+ timeout: 20 * 60_000,
+ };
+ expect(() => assertRunFollowsBenchmark(follows, lobeBench)).not.toThrow();
+ for (const change of [
+ { k: 1 },
+ { maxSteps: 80 },
+ { timeout: 60 * 60_000 },
+ { judgeModel: 'other' },
+ { judgeModel: undefined, judgeProvider: undefined },
+ ])
+ expect(() => assertRunFollowsBenchmark({ ...follows, ...change }, lobeBench)).toThrow(
+ "benchmark's judge",
+ );
+ expect(() => assertRunFollowsBenchmark({ k: 1 }, { name: 'lab' })).not.toThrow();
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentEval/benchmarkStandard.ts b/apps/server/src/routers/lambda/agentEval/benchmarkStandard.ts
new file mode 100644
index 00000000000..67dab3336d0
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/benchmarkStandard.ts
@@ -0,0 +1,106 @@
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+/** `metadata.kind` of a Lobe Bench benchmark (the Evaluation Lab's have none). */
+const LOBE_BENCH_KIND = 'lobe-bench';
+
+export const benchmarkJudgeSchema = z
+ .object({ model: z.string().trim().min(1), provider: z.string().trim().min(1) })
+ .strict();
+
+/** How every case of the benchmark is run: attempts per case, step limit, per-case timeout. */
+export const benchmarkProtocolSchema = z
+ .object({
+ k: z.number().int().min(1).max(5),
+ maxSteps: z.number().int().min(1).max(500),
+ timeoutMinutes: z.number().int().min(1).max(240),
+ })
+ .strict();
+
+export type BenchmarkProtocol = z.infer<typeof benchmarkProtocolSchema>;
+
+type Metadata = Record<string, unknown> | null | undefined;
+
+const isLobeBench = (metadata: Metadata) => metadata?.kind === LOBE_BENCH_KIND;
+
+const missing = () =>
+ new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ "Choose the judge model and the run rules (attempts per case, max steps, timeout) this benchmark's runs follow.",
+ });
+
+/**
+ * The run rules a benchmark fixes: `metadata.protocol`, or for one made before
+ * they were fixed, its complete `defaults`.
+ */
+export const benchmarkProtocolOf = (metadata: Metadata): BenchmarkProtocol | undefined => {
+ const parsed = benchmarkProtocolSchema.safeParse(metadata?.protocol ?? metadata?.defaults);
+ return parsed.success ? parsed.data : undefined;
+};
+
+/**
+ * Every run on a Lobe Bench benchmark is graded by one judge and run under one
+ * set of rules, both chosen when the benchmark is made, so its scores stay
+ * comparable.
+ */
+export const assertNewBenchmarkStandard = (metadata: Metadata) => {
+ if (!isLobeBench(metadata)) return;
+ if (
+ !benchmarkJudgeSchema.safeParse(metadata?.judge).success ||
+ !benchmarkProtocolSchema.safeParse(metadata?.protocol).success
+ )
+ throw missing();
+};
+
+/**
+ * An update never changes a Lobe Bench benchmark's judge or run rules. One
+ * made before they were required may get them once; after that they are fixed.
+ */
+export const keepBenchmarkStandard = (next: Metadata, current: Metadata): Metadata => {
+ if (!next || !isLobeBench(current)) return next;
+ const kept = { ...next };
+ for (const [field, schema] of [
+ ['judge', benchmarkJudgeSchema],
+ ['protocol', benchmarkProtocolSchema],
+ ] as const) {
+ if (current?.[field]) kept[field] = current[field];
+ else if (kept[field] !== undefined && !schema.safeParse(kept[field]).success) throw missing();
+ }
+ return kept;
+};
+
+/**
+ * A run on a Lobe Bench benchmark follows the benchmark's judge and rules: a
+ * run configured otherwise is refused, so no client can rank a different setup
+ * next to it.
+ */
+export const assertRunFollowsBenchmark = (
+ config:
+ | {
+ judgeModel?: string;
+ judgeProvider?: string;
+ k?: number;
+ maxSteps?: number;
+ timeout?: number;
+ }
+ | undefined,
+ metadata: Metadata,
+) => {
+ if (!isLobeBench(metadata)) return;
+ const judge = benchmarkJudgeSchema.safeParse(metadata?.judge);
+ const protocol = benchmarkProtocolOf(metadata);
+ const differs =
+ (judge.success &&
+ (config?.judgeModel !== judge.data.model || config?.judgeProvider !== judge.data.provider)) ||
+ (protocol &&
+ ((config?.k ?? 1) !== protocol.k ||
+ config?.maxSteps !== protocol.maxSteps ||
+ config?.timeout !== protocol.timeoutMinutes * 60_000));
+ if (differs)
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ "A run on this benchmark must use the benchmark's judge, attempts per case, max steps and timeout.",
+ });
+};
diff --git a/apps/server/src/routers/lambda/agentEval/benchmarks.ts b/apps/server/src/routers/lambda/agentEval/benchmarks.ts
index 98468a1fd44..8a70243b39f 100644
--- a/apps/server/src/routers/lambda/agentEval/benchmarks.ts
+++ b/apps/server/src/routers/lambda/agentEval/benchmarks.ts
@@ -3,6 +3,8 @@ import { z } from 'zod';
import { router } from '@/libs/trpc/lambda';
+import { assertNewBenchmarkStandard, keepBenchmarkStandard } from './benchmarkStandard';
+import { prepareBenchmarkDeletion } from './lobeBenchMembership';
import { agentEvalProcedure, agentEvalProcedureWrite } from './procedures';
export const benchmarkRouter = router({
@@ -22,6 +24,7 @@ export const benchmarkRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ assertNewBenchmarkStandard(input.metadata);
try {
const result = await ctx.benchmarkModel.create(input);
if (!result) {
@@ -72,6 +75,10 @@ export const benchmarkRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { id, ...data } = input;
+ if (data.metadata) {
+ const current = await ctx.benchmarkModel.findById(id);
+ data.metadata = keepBenchmarkStandard(data.metadata, current?.metadata) ?? undefined;
+ }
const result = await ctx.benchmarkModel.update(id, data);
if (!result) {
throw new TRPCError({
@@ -84,6 +91,7 @@ export const benchmarkRouter = router({
deleteBenchmark: agentEvalProcedureWrite
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
+ await prepareBenchmarkDeletion(ctx, input.id);
try {
const result = await ctx.benchmarkModel.delete(input.id);
// Check if any rows were affected
diff --git a/apps/server/src/routers/lambda/agentEval/connectorBindings.ts b/apps/server/src/routers/lambda/agentEval/connectorBindings.ts
new file mode 100644
index 00000000000..f36d381b224
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/connectorBindings.ts
@@ -0,0 +1,28 @@
+import type { EvalConnectorBindings } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+
+import {
+ type AgentEvalConnectorService,
+ EvalConnectorBindingError,
+} from '@/server/services/agentEvalConnector';
+
+export const validateEvalConnectorBindings = async (
+ serviceForDataset: (datasetId: string) => Pick<AgentEvalConnectorService, 'validateBindings'>,
+ bindings?: EvalConnectorBindings,
+ datasetId?: string,
+) => {
+ if (!bindings || !Object.keys(bindings).length) return;
+ if (!datasetId)
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Manage evaluation connections within their Dataset.',
+ });
+ try {
+ await serviceForDataset(datasetId).validateBindings(bindings);
+ } catch (error) {
+ if (error instanceof EvalConnectorBindingError) {
+ throw new TRPCError({ code: error.code, message: error.message });
+ }
+ throw error;
+ }
+};
diff --git a/apps/server/src/routers/lambda/agentEval/connectors.test.ts b/apps/server/src/routers/lambda/agentEval/connectors.test.ts
new file mode 100644
index 00000000000..2b36e4c221a
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/connectors.test.ts
@@ -0,0 +1,204 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createCallerFactory } from '@/libs/trpc/lambda';
+import { syncConnectorToolsById } from '@/server/services/connector/sync';
+
+import { evalConnectorRouter } from './connectors';
+
+const mocks = vi.hoisted(() => ({
+ create: vi.fn(),
+ findStored: vi.fn(),
+ listStored: vi.fn(),
+ findPublicById: vi.fn(),
+ modelsForDataset: vi.fn(),
+ queryPublic: vi.fn(),
+ update: vi.fn(),
+}));
+vi.mock('@/server/services/connector/sync', () => ({ syncConnectorToolsById: vi.fn() }));
+vi.mock('./procedures', async () => {
+ const { publicProcedure } = await import('@/libs/trpc/lambda');
+ const procedure = publicProcedure.use((opts) =>
+ opts.next({
+ ctx: {
+ environmentConnections: { find: mocks.findStored, listForDataset: mocks.listStored },
+ evalConnectorModelsForDataset: mocks.modelsForDataset,
+ },
+ }),
+ );
+ return { agentEvalProcedure: procedure, agentEvalProcedureWrite: procedure };
+});
+
+const id = '5d9f523a-7180-4d3e-9242-906abc41a612';
+const input = { datasetId: 'dataset-a', id };
+const models = {
+ connectorModel: {
+ create: mocks.create,
+ findPublicById: mocks.findPublicById,
+ queryPublic: mocks.queryPublic,
+ update: mocks.update,
+ },
+ connectorToolModel: {},
+};
+const caller = createCallerFactory(evalConnectorRouter)({} as never);
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.modelsForDataset.mockResolvedValue(models);
+ mocks.findPublicById.mockResolvedValue({
+ hasCredentials: true,
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ id,
+ mcpServerUrl: 'https://mock.example/mcp',
+ name: 'Management name',
+ status: 'connected',
+ credentials: 'private-token',
+ metadata: { customHeaders: { Authorization: 'private-header' } },
+ });
+ mocks.create.mockResolvedValue({ id, credentials: 'encrypted-secret' });
+ mocks.listStored.mockResolvedValue([]);
+});
+
+describe('Dataset connector management', () => {
+ it('requires the Dataset in every list query and retains disabled rows within that exact scope', async () => {
+ await expect(caller.listEvalConnectors({} as never)).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ mocks.queryPublic.mockResolvedValue([{ id, isEnabled: false, credentials: 'private-token' }]);
+ const rows = await caller.listEvalConnectors({ datasetId: 'dataset-b' });
+ expect(rows).toEqual([expect.objectContaining({ id, isEnabled: false })]);
+ expect(JSON.stringify(rows)).not.toContain('private-token');
+ expect(mocks.modelsForDataset).toHaveBeenCalledWith('dataset-b');
+ });
+
+ it('returns only management fields and never credentials or metadata', async () => {
+ expect(await caller.getEvalConnector(input)).toEqual({
+ hasCredentials: true,
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ id,
+ mcpServerUrl: 'https://mock.example/mcp',
+ name: 'Management name',
+ status: 'connected',
+ });
+ expect(mocks.modelsForDataset).toHaveBeenCalledWith('dataset-a');
+ });
+
+ it('rejects an inaccessible connection before update or connectivity tests', async () => {
+ mocks.findPublicById.mockResolvedValue(null);
+ await expect(
+ caller.updateEvalConnector({
+ ...input,
+ name: 'New',
+ mcpServerUrl: 'https://mock.example/mcp',
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(caller.testEvalConnector(input)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mocks.update).not.toHaveBeenCalled();
+ expect(syncConnectorToolsById).not.toHaveBeenCalled();
+ });
+
+ it('keeps omitted auth unchanged and explicitly encodes replacements or clearing', async () => {
+ const patch = { ...input, name: 'New', mcpServerUrl: 'https://mock.example/mcp' };
+ await caller.updateEvalConnector(patch);
+ expect(mocks.update).toHaveBeenLastCalledWith(
+ id,
+ expect.objectContaining({ credentials: undefined }),
+ );
+ await caller.updateEvalConnector({ ...patch, credentials: null });
+ expect(mocks.update).toHaveBeenLastCalledWith(
+ id,
+ expect.objectContaining({ credentials: null }),
+ );
+ await caller.updateEvalConnector({
+ ...patch,
+ credentials: { type: 'bearer', token: 'new-token' },
+ });
+ expect(mocks.update).toHaveBeenLastCalledWith(
+ id,
+ expect.objectContaining({
+ credentials: JSON.stringify({ token: 'new-token', type: 'bearer' }),
+ }),
+ );
+ });
+
+ it('creates a distinct evaluation record with server-owned Dataset marker', async () => {
+ expect(
+ await caller.createEvalConnector({
+ datasetId: input.datasetId,
+ name: 'Shared name',
+ mcpServerUrl: 'https://mock.example/mcp',
+ credentials: { type: 'header', headers: { Authorization: 'synthetic' } },
+ }),
+ ).toEqual({ id });
+ expect(mocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ identifier: expect.stringMatching(/^eval-mock-/),
+ metadata: { agentEval: { datasetId: input.datasetId } },
+ name: 'Shared name',
+ credentials: JSON.stringify({ headers: { Authorization: 'synthetic' }, type: 'header' }),
+ }),
+ );
+ });
+
+ it('rejects credentials embedded in addresses before persistence', async () => {
+ await expect(
+ caller.createEvalConnector({
+ datasetId: input.datasetId,
+ name: 'Mock',
+ mcpServerUrl: 'https://user:[email protected]/mcp',
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(mocks.create).not.toHaveBeenCalled();
+ });
+
+ it('tests through scoped models and redacts upstream failures', async () => {
+ vi.mocked(syncConnectorToolsById).mockRejectedValue(
+ new Error('Authorization: Bearer private-token'),
+ );
+ await expect(caller.testEvalConnector(input)).rejects.toMatchObject({
+ message: 'Connection test failed. Check the address and authentication, then retry.',
+ });
+ expect(syncConnectorToolsById).toHaveBeenCalledWith(id, models, {
+ pruneMissingAutoTools: true,
+ });
+ });
+});
+
+describe('connections stored in an Environment', () => {
+ const stored = {
+ connection: {
+ credentials: 'encrypted-stored-secret',
+ name: 'Gmail mock',
+ url: 'https://mock.example/mcp/ds/gmail',
+ },
+ connectorId: 'env:shared-world:gmail',
+ environmentId: 'shared-world',
+ mutable: true,
+ service: 'gmail',
+ };
+
+ it('lists and reads them by their env id without credentials', async () => {
+ mocks.queryPublic.mockResolvedValue([]);
+ mocks.listStored.mockResolvedValue([stored]);
+ mocks.findStored.mockResolvedValue(stored);
+ const listed = await caller.listEvalConnectors({ datasetId: 'dataset-a' });
+ const read = await caller.getEvalConnector({
+ datasetId: 'dataset-a',
+ id: 'env:shared-world:gmail',
+ });
+ expect(listed).toEqual([read]);
+ expect(read).toEqual({
+ hasCredentials: true,
+ id: 'env:shared-world:gmail',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mock.example/mcp/ds/gmail',
+ name: 'Gmail mock',
+ status: 'connected',
+ });
+ expect(JSON.stringify(listed)).not.toContain('encrypted-stored-secret');
+ expect(mocks.findStored).toHaveBeenCalledWith('dataset-a', 'env:shared-world:gmail');
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentEval/connectors.ts b/apps/server/src/routers/lambda/agentEval/connectors.ts
new file mode 100644
index 00000000000..29dbf478194
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/connectors.ts
@@ -0,0 +1,204 @@
+import { randomUUID } from 'node:crypto';
+
+import { parseEnvironmentConnectionId } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import type { PublicConnectorRecord } from '@/database/models/connector';
+import {
+ EvalConnectorUpdateError,
+ normalizeEvalConnectorPatch,
+} from '@/database/models/connectorEval';
+import {
+ AgentEvalEnvironmentConnectionError,
+ type StoredEnvironmentConnection,
+} from '@/database/repositories/agentEvalEnvironmentConnection';
+import { router } from '@/libs/trpc/lambda';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import {
+ EvalConnectorBindingError,
+ getLobeBenchForwardingEndpoint,
+} from '@/server/services/agentEvalConnector';
+import { syncConnectorToolsById } from '@/server/services/connector/sync';
+
+import { agentEvalProcedure, agentEvalProcedureWrite } from './procedures';
+
+const datasetInput = z.object({ datasetId: z.string().min(1) });
+// A connector row (uuid) or a connection stored in an Environment (`env:<environmentId>:<service>`).
+const connectorInput = datasetInput.extend({
+ id: z.union([
+ z.string().uuid(),
+ z.string().refine((id) => !!parseEnvironmentConnectionId(id), 'Invalid connection id'),
+ ]),
+});
+const credentialsInput = z.discriminatedUnion('type', [
+ z.object({ token: z.string().min(1), type: z.literal('bearer') }),
+ z.object({ headers: z.record(z.string(), z.string()), type: z.literal('header') }),
+]);
+const editableInput = z.object({
+ credentials: credentialsInput.nullish(),
+ isEnabled: z.boolean().optional(),
+ mcpServerUrl: z.string().url(),
+ name: z.string().trim().min(1).max(255),
+});
+
+/** Only explicit management fields leave this API; credentials and metadata never do. */
+const toManagementRecord = (record: PublicConnectorRecord) => ({
+ hasCredentials: record.hasCredentials,
+ id: record.id,
+ isEnabled: record.isEnabled,
+ mcpConnectionType: record.mcpConnectionType,
+ mcpServerUrl: record.mcpServerUrl,
+ name: record.name,
+ status: record.status,
+});
+
+/** A stored connection in the same management shape; it is always enabled. */
+const toStoredManagementRecord = ({
+ connection,
+ connectorId,
+ service,
+}: StoredEnvironmentConnection) => ({
+ hasCredentials: !!connection.credentials,
+ id: connectorId,
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: connection.url,
+ name: connection.name ?? service,
+ status: 'connected',
+});
+
+const mapEditError = (error: unknown): never => {
+ if (error instanceof EvalConnectorUpdateError)
+ throw new TRPCError({ code: 'BAD_REQUEST', message: error.message });
+ throw error;
+};
+
+export const evalConnectorRouter = router({
+ createEvalConnector: agentEvalProcedureWrite
+ .input(datasetInput.merge(editableInput))
+ .mutation(async ({ ctx, input }) => {
+ const { connectorModel } = await ctx.evalConnectorModelsForDataset(input.datasetId);
+ const metadata = { agentEval: { datasetId: input.datasetId } };
+ try {
+ const patch = await normalizeEvalConnectorPatch(
+ { credentials: null, metadata, mcpServerUrl: null },
+ {
+ credentials: input.credentials ? JSON.stringify(input.credentials) : null,
+ mcpServerUrl: input.mcpServerUrl,
+ },
+ );
+ const row = await connectorModel.create({
+ ...patch,
+ identifier: `eval-mock-${randomUUID()}`,
+ isEnabled: input.isEnabled ?? true,
+ mcpConnectionType: 'http',
+ metadata,
+ name: input.name,
+ sourceType: 'custom',
+ status: 'disconnected',
+ });
+ return { id: row.id };
+ } catch (error) {
+ return mapEditError(error);
+ }
+ }),
+ getEvalConnector: agentEvalProcedure.input(connectorInput).query(async ({ ctx, input }) => {
+ const { connectorModel } = await ctx.evalConnectorModelsForDataset(input.datasetId);
+ if (parseEnvironmentConnectionId(input.id)) {
+ const stored = await ctx.environmentConnections.find(input.datasetId, input.id);
+ if (!stored)
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Dataset connection not found' });
+ return toStoredManagementRecord(stored);
+ }
+ const record = await connectorModel.findPublicById(input.id);
+ if (!record)
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Dataset connection not found' });
+ return toManagementRecord(record);
+ }),
+ listEvalConnectors: agentEvalProcedure.input(datasetInput).query(async ({ ctx, input }) => {
+ const { connectorModel } = await ctx.evalConnectorModelsForDataset(input.datasetId);
+ const stored = await ctx.environmentConnections.listForDataset(input.datasetId);
+ return [
+ ...(await connectorModel.queryPublic()).map(toManagementRecord),
+ ...stored.map(toStoredManagementRecord),
+ ];
+ }),
+ testEvalConnector: agentEvalProcedureWrite
+ .input(connectorInput)
+ .mutation(async ({ ctx, input }) => {
+ const models = await ctx.evalConnectorModelsForDataset(input.datasetId);
+ if (parseEnvironmentConnectionId(input.id)) {
+ try {
+ return await ctx
+ .evalConnectorServiceForDataset(input.datasetId)
+ .testStoredConnection(input.id);
+ } catch {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Connection test failed. Check the address and authentication, then retry.',
+ });
+ }
+ }
+ if (!(await models.connectorModel.findPublicById(input.id)))
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Dataset connection not found' });
+ try {
+ return await syncConnectorToolsById(input.id, models, { pruneMissingAutoTools: true });
+ } catch {
+ // Upstream MCP errors may echo credentials, request headers or private addresses.
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Connection test failed. Check the address and authentication, then retry.',
+ });
+ }
+ }),
+ updateEvalConnector: agentEvalProcedureWrite
+ .input(connectorInput.merge(editableInput))
+ .mutation(async ({ ctx, input }) => {
+ const { connectorModel } = await ctx.evalConnectorModelsForDataset(input.datasetId);
+ if (parseEnvironmentConnectionId(input.id)) {
+ try {
+ // A stored connection is always a LobeBench mock route.
+ getLobeBenchForwardingEndpoint(input.mcpServerUrl);
+ const credentials =
+ input.credentials === undefined
+ ? undefined
+ : input.credentials === null
+ ? null
+ : await (
+ await KeyVaultsGateKeeper.initWithEnvKey()
+ ).encrypt(JSON.stringify(input.credentials));
+ return await ctx.environmentConnections.update(input.datasetId, input.id, {
+ credentials,
+ name: input.name,
+ url: input.mcpServerUrl,
+ });
+ } catch (error) {
+ if (
+ error instanceof AgentEvalEnvironmentConnectionError ||
+ error instanceof EvalConnectorBindingError
+ )
+ throw new TRPCError({ code: 'BAD_REQUEST', message: error.message });
+ throw error;
+ }
+ }
+ if (!(await connectorModel.findPublicById(input.id)))
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Dataset connection not found' });
+ try {
+ await connectorModel.update(input.id, {
+ isEnabled: input.isEnabled,
+ credentials:
+ input.credentials === undefined
+ ? undefined
+ : input.credentials === null
+ ? null
+ : JSON.stringify(input.credentials),
+ mcpServerUrl: input.mcpServerUrl,
+ name: input.name,
+ });
+ return { id: input.id };
+ } catch (error) {
+ return mapEditError(error);
+ }
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agentEval/datasetConnections.ts b/apps/server/src/routers/lambda/agentEval/datasetConnections.ts
new file mode 100644
index 00000000000..adb4232116e
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/datasetConnections.ts
@@ -0,0 +1,57 @@
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { AgentEvalDatasetWriteError } from '@/database/models/agentEval/datasetAccess';
+import { AgentEvalDatasetPackageImportError } from '@/database/repositories/agentEvalDatasetPackage';
+import { router } from '@/libs/trpc/lambda';
+
+import { validateEvalConnectorBindings } from './connectorBindings';
+import { agentEvalProcedure, agentEvalProcedureWrite } from './procedures';
+import { evalConnectorBindingsSchema } from './schemas';
+
+const mapBindingError = (error: unknown): never => {
+ if (error instanceof AgentEvalDatasetWriteError)
+ throw new TRPCError({ code: 'FORBIDDEN', message: error.message });
+ if (error instanceof AgentEvalDatasetPackageImportError)
+ throw new TRPCError({ code: 'BAD_REQUEST', message: error.message });
+ throw error;
+};
+
+export const datasetConnectionRouter = router({
+ getDatasetConnectorBindings: agentEvalProcedure
+ .input(z.object({ datasetId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ try {
+ return await ctx.datasetConnectorRepo.getBindings(input.datasetId);
+ } catch (error) {
+ return mapBindingError(error);
+ }
+ }),
+ updateDatasetConnectorBindings: agentEvalProcedureWrite
+ .input(
+ z.object({
+ caseBindings: z.record(z.string(), evalConnectorBindingsSchema).optional(),
+ datasetId: z.string(),
+ environmentBindings: z.record(z.string(), evalConnectorBindingsSchema).optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ if (Object.keys(input.caseBindings ?? {}).length > 0)
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ 'Mock connections belong to an Environment. Choose them for the Environment, not for a case.',
+ });
+ for (const bindings of Object.values(input.environmentBindings ?? {}))
+ await validateEvalConnectorBindings(
+ ctx.evalConnectorServiceForDataset,
+ bindings,
+ input.datasetId,
+ );
+ try {
+ return await ctx.datasetConnectorRepo.updateBindings(input.datasetId, input);
+ } catch (error) {
+ return mapBindingError(error);
+ }
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agentEval/datasetPackageSchema.test.ts b/apps/server/src/routers/lambda/agentEval/datasetPackageSchema.test.ts
new file mode 100644
index 00000000000..75f1a570bec
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/datasetPackageSchema.test.ts
@@ -0,0 +1,200 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { validateDatasetPackage } from './datasetPackageSchema';
+
+const example = () => ({
+ cases: [{ content: { expected: 'hello', input: 'Reply with hello.' }, key: 'greeting' }],
+ dataset: { evalMode: 'equals', name: 'Synthetic examples' },
+ format: 'lobehub-eval-dataset',
+ version: 1,
+});
+
+describe('dataset package schema', () => {
+ it('rejects ungradable cases instead of depending on an absent system benchmark', () => {
+ expect(() =>
+ validateDatasetPackage({ ...example(), dataset: { name: 'Missing grading' } }),
+ ).toThrow('grading mode');
+ });
+ it('preserves structured history, grading and shared environment references', () => {
+ const pack = validateDatasetPackage({
+ ...example(),
+ cases: [
+ {
+ content: {
+ input: 'Remember the greeting.',
+ messages: [{ content: 'hello', role: 'user' }],
+ },
+ environmentKey: 'isolated',
+ evalConfig: { judgePrompt: 'The answer must contain the greeting.' },
+ evalMode: 'rule-checklist',
+ key: 'memory',
+ sortOrder: 4,
+ },
+ ],
+ environments: [
+ {
+ config: { memory: {}, sessionDate: '2026-01-01T00:00:00Z' },
+ key: 'isolated',
+ name: 'Empty memory',
+ },
+ ],
+ });
+ expect(pack.cases[0]).toMatchObject({
+ content: { messages: [{ content: 'hello', role: 'user' }] },
+ environmentKey: 'isolated',
+ evalConfig: { judgePrompt: 'The answer must contain the greeting.' },
+ evalMode: 'rule-checklist',
+ sortOrder: 4,
+ });
+ expect(pack.environments[0].config.memory).toEqual({});
+ });
+
+ it('rejects unknown versions, ownership, system flags and nonportable row IDs', () => {
+ for (const pack of [
+ { ...example(), version: 2 },
+ { ...example(), userId: 'somebody-else' },
+ { ...example(), dataset: { name: 'System', metadata: { kind: 'lobe-bench' } } },
+ { ...example(), cases: [{ ...example().cases[0], environmentId: 'database-row' }] },
+ ])
+ expect(() => validateDatasetPackage(pack)).toThrow('Invalid dataset package');
+ });
+
+ it('rejects missing references and duplicate portable keys', () => {
+ expect(() =>
+ validateDatasetPackage({
+ ...example(),
+ cases: [{ ...example().cases[0], environmentKey: 'missing' }],
+ }),
+ ).toThrow('referenced environment');
+ expect(() =>
+ validateDatasetPackage({ ...example(), cases: [...example().cases, ...example().cases] }),
+ ).toThrow('Case keys must be unique');
+ expect(() =>
+ validateDatasetPackage({
+ ...example(),
+ environments: [
+ { config: {}, key: 'same', name: 'One' },
+ { config: {}, key: 'same', name: 'Two' },
+ ],
+ }),
+ ).toThrow('Environment keys must be unique');
+ });
+
+ it('accepts mock routing segments while rejecting package-supplied endpoints and credentials', () => {
+ const mockPack = {
+ ...example(),
+ dataset: { ...example().dataset, metadata: { mock: { dataset: 'synthetic-v1' } } },
+ environments: [
+ { config: { mock: { services: ['example'] } }, key: 'mock', name: 'Synthetic mock' },
+ ],
+ };
+ expect(validateDatasetPackage(mockPack).dataset.metadata?.mock?.dataset).toBe('synthetic-v1');
+ expect(validateDatasetPackage({ ...mockPack, dataset: example().dataset })).toMatchObject({
+ environments: mockPack.environments,
+ });
+ expect(() =>
+ validateDatasetPackage({
+ ...mockPack,
+ dataset: {
+ ...mockPack.dataset,
+ metadata: { mock: { baseUrl: 'https://untrusted.example', dataset: 'synthetic-v1' } },
+ },
+ }),
+ ).toThrow('Invalid dataset package');
+ expect(() =>
+ validateDatasetPackage({
+ ...mockPack,
+ environments: [
+ {
+ config: {
+ toolForwarding: {
+ example: { endpoint: 'https://untrusted.example', token: 'not-a-real-token' },
+ },
+ },
+ key: 'mock',
+ name: 'Mock',
+ },
+ ],
+ }),
+ ).toThrow('Invalid dataset package');
+ });
+
+ it('rejects installation-specific connections in shared and inline package environments', () => {
+ const connectorBindings = {
+ example: { connectorId: 'b34a8f4d-349a-41a9-b307-3a8754e8e5a8' },
+ };
+ for (const value of [
+ {
+ ...example(),
+ environments: [{ config: { connectorBindings }, key: 'local', name: 'Local connection' }],
+ },
+ {
+ ...example(),
+ cases: [
+ { key: 'inline', content: { input: 'Do work', environment: { connectorBindings } } },
+ ],
+ },
+ ])
+ expect(() => validateDatasetPackage(value)).toThrow('Invalid dataset package');
+ });
+ it('accepts private portable connection definitions and rejects invalid references safely', () => {
+ const privatePack = {
+ ...example(),
+ connections: {
+ privateMock: {
+ credentials: { token: 'synthetic-private-token', type: 'bearer' },
+ name: 'Private mock',
+ url: 'https://mock.example/mcp',
+ },
+ },
+ environments: [
+ {
+ connectionBindings: { notion: { connectionKey: 'privateMock' } },
+ config: {},
+ key: 'private',
+ name: 'Private',
+ },
+ ],
+ };
+ expect(validateDatasetPackage(privatePack).connections?.privateMock.credentials).toMatchObject({
+ type: 'bearer',
+ });
+ expect(() => validateDatasetPackage({ ...privatePack, connections: {} })).toThrow(
+ 'connection configuration',
+ );
+ for (const url of [
+ 'invalid-url-synthetic-private-token',
+ 'file:///private',
+ 'https://[email protected]',
+ 'https://mock.example?token=synthetic-private-token',
+ ]) {
+ let message = '';
+ try {
+ validateDatasetPackage({
+ ...privatePack,
+ connections: { privateMock: { ...privatePack.connections.privateMock, url } },
+ });
+ } catch (error) {
+ message = (error as Error).message;
+ }
+ expect(message).toContain('connection configuration');
+ expect(message).not.toContain('synthetic-private-token');
+ expect(message).not.toContain(url);
+ }
+ });
+
+ it('refuses a case that binds its own mock connection', () => {
+ const pack = example();
+ const withCaseBinding = {
+ ...pack,
+ cases: pack.cases.map((testCase, index) =>
+ index === 0
+ ? { ...testCase, connectionBindings: { notion: { connectionKey: 'privateMock' } } }
+ : testCase,
+ ),
+ connections: { privateMock: { name: 'Private mock', url: 'https://mock.example/mcp' } },
+ };
+ expect(() => validateDatasetPackage(withCaseBinding)).toThrow('belong to an Environment');
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentEval/datasetPackageSchema.ts b/apps/server/src/routers/lambda/agentEval/datasetPackageSchema.ts
new file mode 100644
index 00000000000..8b2dbd4be08
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/datasetPackageSchema.ts
@@ -0,0 +1,211 @@
+import type { AgentEvalDatasetPackage } from '@lobechat/types';
+import { z } from 'zod';
+
+import {
+ evalCaseEnvironmentSchema,
+ evalConfigSchema,
+ evalTestCaseContentSchema,
+ rubricTypeSchema,
+} from './schemas';
+
+const key = z.string().trim().min(1).max(200);
+const portableEnvironmentSchema = evalCaseEnvironmentSchema.omit({ connectorBindings: true });
+const connectionReferenceSchema = z.record(
+ key,
+ z.object({ connectionKey: key, transport: z.enum(['mcp', 'lobe-bench']).optional() }).strict(),
+);
+const credentialValue = z
+ .string()
+ .min(1)
+ .max(16384)
+ .refine((value) => !/[\r\n]/.test(value));
+const connectionSchema = z
+ .object({
+ credentials: z
+ .discriminatedUnion('type', [
+ z.object({ token: credentialValue, type: z.literal('bearer') }).strict(),
+ z
+ .object({
+ headers: z.record(z.string().regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/), credentialValue),
+ type: z.literal('header'),
+ })
+ .strict(),
+ ])
+ .optional(),
+ name: z.string().trim().min(1).max(200),
+ url: z
+ .url()
+ .max(8192)
+ .refine((value) => {
+ try {
+ const url = new URL(value);
+ return (
+ ['http:', 'https:'].includes(url.protocol) &&
+ !url.username &&
+ !url.password &&
+ !url.search &&
+ !url.hash
+ );
+ } catch {
+ return false;
+ }
+ }, 'Use an HTTP MCP address without embedded credentials, query or fragment'),
+ })
+ .strict();
+const packageMetadataSchema = z
+ .object({
+ mock: z
+ .object({
+ connectors: z
+ .record(
+ key,
+ z
+ .object({
+ avatar: z.string().max(2000).optional(),
+ description: z.string().max(4000).optional(),
+ title: z.string().max(200).optional(),
+ })
+ .strict(),
+ )
+ .optional(),
+ dataset: key,
+ })
+ .strict()
+ .optional(),
+ presentation: key.optional(),
+ release: key.optional(),
+ })
+ .strict();
+
+/** A versioned ZIP envelope preserves structured cases instead of flattening them into columns. */
+export const datasetPackageSchema = z
+ .object({
+ cases: z
+ .array(
+ z
+ .object({
+ connectionBindings: connectionReferenceSchema.optional(),
+ content: evalTestCaseContentSchema.strict().extend({
+ environment: portableEnvironmentSchema.optional(),
+ input: z.string().min(1),
+ }),
+ environmentKey: key.optional(),
+ evalConfig: evalConfigSchema.optional(),
+ evalMode: rubricTypeSchema.optional(),
+ key,
+ metadata: z
+ .object({
+ category: z.string().optional(),
+ difficulty: z.enum(['easy', 'hard', 'medium']).optional(),
+ index: z.number().int().nonnegative().optional(),
+ tags: z.array(z.string()).max(100).optional(),
+ })
+ .strict()
+ .optional(),
+ sortOrder: z.number().int().nonnegative().optional(),
+ })
+ .strict(),
+ )
+ .min(1)
+ .max(5000),
+ connections: z.record(key, connectionSchema).optional(),
+ dataset: z
+ .object({
+ description: z.string().max(10000).optional(),
+ evalConfig: evalConfigSchema.optional(),
+ evalMode: rubricTypeSchema.optional(),
+ metadata: packageMetadataSchema.optional(),
+ name: z.string().trim().min(1).max(200),
+ })
+ .strict(),
+ environments: z
+ .array(
+ z
+ .object({
+ connectionBindings: connectionReferenceSchema.optional(),
+ config: portableEnvironmentSchema,
+ description: z.string().max(10000).optional(),
+ key,
+ name: z.string().trim().min(1).max(200),
+ })
+ .strict(),
+ )
+ .max(500)
+ .default([]),
+ format: z.literal('lobehub-eval-dataset'),
+ version: z.literal(1),
+ })
+ .strict()
+ .superRefine((value, ctx) => {
+ const environmentKeys = new Set<string>();
+ value.environments.forEach((environment, index) => {
+ if (environmentKeys.has(environment.key)) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'Environment keys must be unique',
+ path: ['environments', index, 'key'],
+ });
+ }
+ environmentKeys.add(environment.key);
+ });
+ const caseKeys = new Set<string>();
+ value.cases.forEach((testCase, index) => {
+ if (!testCase.evalMode && !value.dataset.evalMode) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'Specify a grading mode on the case or dataset',
+ path: ['cases', index, 'evalMode'],
+ });
+ }
+ if (caseKeys.has(testCase.key)) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'Case keys must be unique',
+ path: ['cases', index, 'key'],
+ });
+ }
+ caseKeys.add(testCase.key);
+ if (testCase.environmentKey && !environmentKeys.has(testCase.environmentKey)) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'The referenced environment is missing from this package',
+ path: ['cases', index, 'environmentKey'],
+ });
+ }
+ // Kept in the schema only to explain the refusal: connections belong to Environments.
+ if (Object.keys(testCase.connectionBindings ?? {}).length > 0) {
+ ctx.addIssue({
+ code: 'custom',
+ message:
+ 'Mock connections belong to an Environment. A case cannot bind its own; list the services it uses in its Environment instead.',
+ path: ['cases', index, 'connectionBindings'],
+ });
+ }
+ });
+ for (const item of [...value.environments, ...value.cases]) {
+ if (
+ Object.values(item.connectionBindings ?? {}).some(
+ (binding) => !Object.hasOwn(value.connections ?? {}, binding.connectionKey),
+ )
+ )
+ ctx.addIssue({
+ code: 'custom',
+ message: 'A mock binding references a connection missing from this package',
+ path: ['connections'],
+ });
+ }
+ });
+
+export const validateDatasetPackage = (manifest: unknown): AgentEvalDatasetPackage => {
+ const result = datasetPackageSchema.safeParse(manifest);
+ if (!result.success) {
+ const issue = result.error.issues[0];
+ if (issue.path.includes('connections') || issue.path.includes('credentials')) {
+ throw new Error('Invalid dataset package connection configuration');
+ }
+ throw new Error(
+ `Invalid dataset package at ${issue.path.join('.') || 'root'}: ${issue.message}`,
+ );
+ }
+ return result.data;
+};
diff --git a/apps/server/src/routers/lambda/agentEval/datasetPackages.test.ts b/apps/server/src/routers/lambda/agentEval/datasetPackages.test.ts
new file mode 100644
index 00000000000..59e0f64fa90
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/datasetPackages.test.ts
@@ -0,0 +1,223 @@
+// @vitest-environment node
+import { strToU8, zipSync } from 'fflate';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentEvalDatasetWriteError } from '@/database/models/agentEval/datasetAccess';
+import type * as DatasetPackageRepository from '@/database/repositories/agentEvalDatasetPackage';
+import { AgentEvalDatasetPackageImportError } from '@/database/repositories/agentEvalDatasetPackage';
+import { createCallerFactory } from '@/libs/trpc/lambda';
+import { EvalConnectorBindingError } from '@/server/services/agentEvalConnector';
+
+import { datasetRouter } from './datasets';
+
+const mocks = vi.hoisted(() => ({
+ importPackage: vi.fn(),
+ assertActiveOrLegacy: vi.fn(),
+ getFileByteArray: vi.fn(),
+ getFileMetadata: vi.fn(),
+ deleteFile: vi.fn(),
+ releaseBestEffort: vi.fn(),
+ validateBindings: vi.fn(),
+}));
+vi.mock('@/database/repositories/agentEvalDatasetPackage', async (importOriginal) => {
+ const actual = await importOriginal<typeof DatasetPackageRepository>();
+ return {
+ ...actual,
+ AgentEvalDatasetPackageRepo: class {
+ importPackage = mocks.importPackage;
+ },
+ };
+});
+vi.mock('./procedures', async () => {
+ const { publicProcedure } = await import('@/libs/trpc/lambda');
+ const procedure = publicProcedure.use((opts) =>
+ opts.next({
+ ctx: {
+ evalConnectorServiceForDataset: () => ({ validateBindings: mocks.validateBindings }),
+ fileUploadService: {
+ assertActiveOrLegacy: mocks.assertActiveOrLegacy,
+ releaseBestEffort: mocks.releaseBestEffort,
+ },
+ fileService: {
+ getFileByteArray: mocks.getFileByteArray,
+ getFileMetadata: mocks.getFileMetadata,
+ deleteFile: mocks.deleteFile,
+ },
+ userId: 'synthetic-owner',
+ serverDB: {},
+ } as any,
+ }),
+ );
+ return { agentEvalProcedure: procedure, agentEvalProcedureWrite: procedure };
+});
+const caller = createCallerFactory(datasetRouter)({} as any);
+const manifest = {
+ format: 'lobehub-eval-dataset',
+ version: 1,
+ dataset: {
+ name: 'Synthetic only',
+ evalMode: 'equals',
+ metadata: { mock: { dataset: 'example-v1' } },
+ },
+ cases: [{ key: 'one', content: { input: 'hello', expected: 'world' }, environmentKey: 'world' }],
+ environments: [{ key: 'world', name: 'World', config: { mock: { services: ['example'] } } }],
+};
+const archive = (value: unknown) => zipSync({ 'dataset.json': strToU8(JSON.stringify(value)) });
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.assertActiveOrLegacy.mockResolvedValue({ id: 'upload' });
+ mocks.getFileByteArray.mockResolvedValue(archive(manifest));
+ mocks.getFileMetadata.mockResolvedValue({ contentLength: 1024 });
+ mocks.importPackage.mockResolvedValue({
+ datasetId: 'new-dataset',
+ benchmarkId: 'new-benchmark',
+ count: 1,
+ environmentCount: 1,
+ });
+ mocks.releaseBestEffort.mockResolvedValue(undefined);
+ mocks.deleteFile.mockResolvedValue(undefined);
+ mocks.validateBindings.mockResolvedValue(undefined);
+});
+
+describe('dataset ZIP API', () => {
+ it('rejects oversized stored objects before downloading their bytes', async () => {
+ mocks.getFileMetadata.mockResolvedValue({ contentLength: 11 * 1024 * 1024 });
+ await expect(
+ caller.parseDatasetFile({ pathname: 'large', filename: 'large.zip' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ await expect(caller.importDatasetPackage({ pathname: 'large' })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ expect(mocks.getFileByteArray).not.toHaveBeenCalled();
+ expect(mocks.importPackage).not.toHaveBeenCalled();
+ });
+ it('does not misclassify storage outages as user validation errors', async () => {
+ mocks.getFileMetadata.mockRejectedValue(new Error('internal storage detail'));
+ await expect(
+ caller.parseDatasetFile({ pathname: 'file', filename: 'file.zip' }),
+ ).rejects.toMatchObject({ code: 'INTERNAL_SERVER_ERROR' });
+ await expect(caller.importDatasetPackage({ pathname: 'file' })).rejects.toMatchObject({
+ code: 'INTERNAL_SERVER_ERROR',
+ });
+ expect(mocks.importPackage).not.toHaveBeenCalled();
+ });
+ it('previews structured ZIP data without importing or consuming the upload', async () => {
+ await expect(
+ caller.parseDatasetFile({ pathname: 'upload-path', filename: 'examples.zip' }),
+ ).resolves.toMatchObject({
+ format: 'zip',
+ totalCount: 1,
+ datasetPackage: {
+ name: 'Synthetic only',
+ caseCount: 1,
+ environmentCount: 1,
+ mockServices: ['example'],
+ },
+ preview: [{ input: 'hello', expected: 'world' }],
+ });
+ expect(mocks.importPackage).not.toHaveBeenCalled();
+ expect(mocks.releaseBestEffort).not.toHaveBeenCalled();
+ });
+ it('imports validated data and only then releases the successful upload', async () => {
+ await expect(
+ caller.importDatasetPackage({ pathname: 'upload-path', name: 'My dataset' }),
+ ).resolves.toMatchObject({ datasetId: 'new-dataset' });
+ expect(mocks.importPackage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: 'My dataset',
+ package: manifest,
+ sha256: expect.stringMatching(/^[a-f0-9]{64}$/),
+ }),
+ );
+ expect(mocks.releaseBestEffort).toHaveBeenCalledWith('upload-path');
+ expect(mocks.importPackage.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.releaseBestEffort.mock.invocationCallOrder[0],
+ );
+ });
+ it('rejects malformed or unsupported packages before DB writes and retains the file', async () => {
+ for (const bytes of [
+ new Uint8Array([1, 2]),
+ archive({ ...manifest, version: 99 }),
+ archive({ ...manifest, cases: [{ ...manifest.cases[0], environmentKey: 'missing' }] }),
+ ]) {
+ mocks.getFileByteArray.mockResolvedValue(bytes);
+ await expect(caller.importDatasetPackage({ pathname: 'upload-path' })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ }
+ expect(mocks.importPackage).not.toHaveBeenCalled();
+ expect(mocks.releaseBestEffort).not.toHaveBeenCalled();
+ });
+ it('retains failed imports for retry and maps scope and immutable-dataset errors', async () => {
+ for (const [error, code] of [
+ [new AgentEvalDatasetWriteError('Not yours'), 'FORBIDDEN'],
+ [new AgentEvalDatasetPackageImportError('Use a new dataset'), 'BAD_REQUEST'],
+ ] as const) {
+ mocks.importPackage.mockRejectedValue(error);
+ await expect(
+ caller.importDatasetPackage({ pathname: 'upload-path', datasetId: 'existing' }),
+ ).rejects.toMatchObject({ code, message: error.message });
+ }
+ expect(mocks.releaseBestEffort).not.toHaveBeenCalled();
+ expect(mocks.deleteFile).not.toHaveBeenCalled();
+ });
+ it('rejects unowned uploads before reading data or constructing an import', async () => {
+ mocks.assertActiveOrLegacy.mockRejectedValue(new Error('Upload not owned'));
+ await expect(caller.importDatasetPackage({ pathname: 'foreign' })).rejects.toThrow(
+ 'Upload not owned',
+ );
+ expect(mocks.getFileByteArray).not.toHaveBeenCalled();
+ expect(mocks.importPackage).not.toHaveBeenCalled();
+ });
+ it('does not turn committed legacy imports into failures when temporary cleanup fails', async () => {
+ mocks.assertActiveOrLegacy.mockResolvedValue(null);
+ mocks.deleteFile.mockRejectedValue(new Error('storage unavailable'));
+ await expect(caller.importDatasetPackage({ pathname: 'legacy-upload' })).resolves.toMatchObject(
+ { count: 1 },
+ );
+ });
+ it('redacts private connection URLs and credentials from the ZIP preview', async () => {
+ mocks.getFileByteArray.mockResolvedValue(
+ archive({
+ ...manifest,
+ connections: {
+ privateMock: {
+ credentials: { token: 'synthetic-private-token', type: 'bearer' },
+ name: 'Private mock',
+ url: 'https://private-mock.example/mcp',
+ },
+ },
+ environments: [
+ {
+ ...manifest.environments[0],
+ connectionBindings: { example: { connectionKey: 'privateMock' } },
+ },
+ ],
+ }),
+ );
+ const preview = await caller.parseDatasetFile({ filename: 'private.zip', pathname: 'upload' });
+ expect(preview).toMatchObject({
+ datasetPackage: {
+ connectionRequirements: [{ providedServices: ['example'], services: ['example'] }],
+ embeddedConnections: [{ authConfigured: true, key: 'privateMock', name: 'Private mock' }],
+ },
+ });
+ expect(JSON.stringify(preview)).not.toContain('synthetic-private-token');
+ expect(JSON.stringify(preview)).not.toContain('private-mock.example');
+ });
+ it('refuses inaccessible existing connections before creating an import and retains the upload', async () => {
+ mocks.validateBindings.mockRejectedValue(
+ new EvalConnectorBindingError('The selected mock connection is unavailable'),
+ );
+ await expect(
+ caller.importDatasetPackage({
+ environmentBindings: {
+ world: { example: { connectorId: 'b34a8f4d-349a-41a9-b307-3a8754e8e5a8' } },
+ },
+ pathname: 'upload',
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(mocks.importPackage).not.toHaveBeenCalled();
+ expect(mocks.releaseBestEffort).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentEval/datasetPackages.ts b/apps/server/src/routers/lambda/agentEval/datasetPackages.ts
new file mode 100644
index 00000000000..3b26925f31e
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/datasetPackages.ts
@@ -0,0 +1,167 @@
+import type { AgentEvalDatasetPackagePreview } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import debug from 'debug';
+import { z } from 'zod';
+
+import { AgentEvalDatasetWriteError } from '@/database/models/agentEval/datasetAccess';
+import {
+ AgentEvalDatasetPackageImportError,
+ AgentEvalDatasetPackageRepo,
+} from '@/database/repositories/agentEvalDatasetPackage';
+import {
+ getPackageConnectionRequirements,
+ getReferencedPackageConnections,
+ validatePackageConnectionSelections,
+} from '@/database/repositories/agentEvalDatasetPackage/bindings';
+import {
+ DATASET_PACKAGE_MAX_COMPRESSED_BYTES,
+ readDatasetPackageArchive,
+} from '@/server/services/agentEvalDatasetPackage/archive';
+import type { FileService } from '@/server/services/file';
+
+import { validateEvalConnectorBindings } from './connectorBindings';
+import { validateDatasetPackage } from './datasetPackageSchema';
+import { agentEvalProcedureWrite } from './procedures';
+import { evalConnectorBindingsSchema } from './schemas';
+
+const log = debug('lobe-server:agentEvalDatasetPackage');
+
+export const readDatasetPackageUpload = async (
+ fileService: Pick<FileService, 'getFileMetadata' | 'getFileByteArray'>,
+ pathname: string,
+) => {
+ const { contentLength } = await fileService.getFileMetadata(pathname);
+ if (
+ !Number.isFinite(contentLength) ||
+ contentLength < 0 ||
+ contentLength > DATASET_PACKAGE_MAX_COMPRESSED_BYTES
+ ) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Dataset ZIP exceeds the 10 MiB limit' });
+ }
+ return fileService.getFileByteArray(pathname);
+};
+
+export const parseDatasetPackage = (content: Uint8Array) => {
+ const archive = readDatasetPackageArchive(content);
+ return { package: validateDatasetPackage(archive.manifest), sha256: archive.sha256 };
+};
+
+export const previewDatasetPackage = (content: Uint8Array) => {
+ const { package: pack } = parseDatasetPackage(content);
+ const connectionRequirements = getPackageConnectionRequirements(pack);
+ const datasetPackage: AgentEvalDatasetPackagePreview = {
+ caseCount: pack.cases.length,
+ connectionRequirements,
+ description: pack.dataset.description,
+ environmentCount: pack.environments.length,
+ embeddedConnections: getReferencedPackageConnections(pack).map((key) => ({
+ authConfigured: !!pack.connections?.[key]?.credentials,
+ key,
+ name: pack.connections![key].name,
+ })),
+ mockServices: [
+ ...new Set(connectionRequirements.flatMap((requirement) => requirement.services)),
+ ].sort(),
+ name: pack.dataset.name,
+ release: pack.dataset.metadata?.release,
+ version: pack.version,
+ };
+ return {
+ datasetPackage,
+ format: 'zip' as const,
+ headers: [] as string[],
+ preview: pack.cases.slice(0, 50).map(({ content }) => ({
+ category: content.category,
+ expected: content.expected,
+ input: content.input,
+ })),
+ totalCount: pack.cases.length,
+ };
+};
+
+export const importDatasetPackageProcedure = agentEvalProcedureWrite
+ .input(
+ z
+ .object({
+ benchmarkId: z.string().min(1).optional(),
+ caseBindings: z.record(z.string().min(1), evalConnectorBindingsSchema).optional(),
+ datasetId: z.string().min(1).optional(),
+ environmentBindings: z.record(z.string().min(1), evalConnectorBindingsSchema).optional(),
+ filename: z.string().optional(),
+ name: z.string().trim().min(1).max(200).optional(),
+ pathname: z.string().min(1),
+ })
+ .refine((value) => !value.datasetId || !value.benchmarkId, {
+ message: 'Choose an existing dataset or a destination benchmark, not both',
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const upload = await ctx.fileUploadService.assertActiveOrLegacy(input.pathname);
+ const content = await readDatasetPackageUpload(ctx.fileService, input.pathname);
+ let parsed: ReturnType<typeof parseDatasetPackage>;
+ try {
+ parsed = parseDatasetPackage(content);
+ } catch (error) {
+ log('Package validation rejected: %s', error instanceof Error ? error.name : 'unknown');
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: error instanceof Error ? error.message : 'Invalid dataset package',
+ });
+ }
+ try {
+ const bindings = {
+ caseBindings: input.caseBindings,
+ environmentBindings: input.environmentBindings,
+ };
+ validatePackageConnectionSelections(parsed.package, bindings);
+ for (const selection of [
+ ...Object.values(bindings.environmentBindings ?? {}),
+ ...Object.values(bindings.caseBindings ?? {}),
+ ])
+ await validateEvalConnectorBindings(
+ ctx.evalConnectorServiceForDataset,
+ selection,
+ input.datasetId,
+ );
+ const repo = new AgentEvalDatasetPackageRepo(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ctx.evalConnectorGateKeeper,
+ );
+ const result = await repo.importPackage({
+ benchmarkId: input.benchmarkId,
+ bindings,
+ datasetId: input.datasetId,
+ name: input.name,
+ ...parsed,
+ });
+ log(
+ 'Imported package %s: dataset=%s cases=%d environments=%d',
+ parsed.sha256,
+ result.datasetId,
+ result.count,
+ result.environmentCount,
+ );
+ // Keep a failed import retryable. Cleanup must never turn a committed import into an error.
+ if (upload) await ctx.fileUploadService.releaseBestEffort(input.pathname);
+ else
+ await ctx.fileService.deleteFile(input.pathname).catch(() => {
+ log('Legacy upload cleanup failed after import: dataset=%s', result.datasetId);
+ });
+ return result;
+ } catch (error) {
+ log(
+ 'Package import failed: sha256=%s type=%s',
+ parsed.sha256,
+ error instanceof Error ? error.name : 'unknown',
+ );
+ if (error instanceof AgentEvalDatasetWriteError) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: error.message });
+ }
+ if (error instanceof AgentEvalDatasetPackageImportError) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: error.message });
+ }
+ throw error;
+ }
+ });
diff --git a/apps/server/src/routers/lambda/agentEval/datasetWrites.test.ts b/apps/server/src/routers/lambda/agentEval/datasetWrites.test.ts
new file mode 100644
index 00000000000..283fa532d03
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/datasetWrites.test.ts
@@ -0,0 +1,160 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentEvalDatasetWriteError } from '@/database/models/agentEval/datasetAccess';
+import { AgentEvalEnvironmentBindingError } from '@/database/models/agentEval/environment';
+import { createCallerFactory } from '@/libs/trpc/lambda';
+import { EvalConnectorBindingError } from '@/server/services/agentEvalConnector';
+
+import { datasetRouter } from './datasets';
+import { environmentRouter } from './environments';
+import { testCaseRouter } from './testCases';
+
+const mocks = vi.hoisted(() => ({
+ create: vi.fn(),
+ batchCreate: vi.fn(),
+ update: vi.fn(),
+ delete: vi.fn(),
+ createDataset: vi.fn(),
+ updateDataset: vi.fn(),
+ validateBindings: vi.fn(),
+ createEnvironment: vi.fn(),
+ updateEnvironment: vi.fn(),
+ findEnvironment: vi.fn(),
+}));
+
+vi.mock('./procedures', async () => {
+ const { publicProcedure } = await import('@/libs/trpc/lambda');
+ const procedure = publicProcedure.use((opts) =>
+ opts.next({
+ ctx: {
+ evalConnectorServiceForDataset: () => ({ validateBindings: mocks.validateBindings }),
+ environmentModel: {
+ create: mocks.createEnvironment,
+ findById: mocks.findEnvironment,
+ update: mocks.updateEnvironment,
+ },
+ datasetModel: { create: mocks.createDataset, update: mocks.updateDataset },
+ testCaseModel: {
+ findById: vi.fn().mockResolvedValue({ datasetId: 'dataset' }),
+ create: mocks.create,
+ batchCreate: mocks.batchCreate,
+ update: mocks.update,
+ delete: mocks.delete,
+ },
+ } as any,
+ }),
+ );
+ return { agentEvalProcedure: procedure, agentEvalProcedureWrite: procedure };
+});
+
+const datasets = createCallerFactory(datasetRouter)({} as any);
+const cases = createCallerFactory(testCaseRouter)({} as any);
+const environments = createCallerFactory(environmentRouter)({} as any);
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ for (const mock of Object.values(mocks)) {
+ mock.mockRejectedValue(new AgentEvalDatasetWriteError());
+ }
+ mocks.validateBindings.mockResolvedValue(undefined);
+ mocks.findEnvironment.mockResolvedValue({ config: {} });
+});
+
+describe('mock connection write access', () => {
+ it('leaves omitted bindings for the atomic model merge and accepts explicit unchanged bindings', async () => {
+ const connectorBindings = { mock: { connectorId: '5d9f523a-7180-4d3e-9242-906abc41a612' } };
+ mocks.findEnvironment.mockResolvedValue({ config: { connectorBindings } });
+ mocks.updateEnvironment.mockResolvedValue({ id: 'env' });
+ await environments.updateEnvironment({ config: { timezone: 'UTC' }, id: 'env' });
+ expect(mocks.updateEnvironment).toHaveBeenCalledWith('env', {
+ config: { timezone: 'UTC' },
+ });
+ expect(mocks.findEnvironment).not.toHaveBeenCalled();
+ await environments.updateEnvironment({ config: { connectorBindings }, id: 'env' });
+ expect(mocks.updateEnvironment).toHaveBeenCalledTimes(2);
+ // JSONB ordering and an explicit default transport do not change the binding.
+ await environments.updateEnvironment({
+ config: { connectorBindings: { mock: { transport: 'mcp', ...connectorBindings.mock } } },
+ id: 'env',
+ });
+ expect(mocks.updateEnvironment).toHaveBeenCalledTimes(3);
+ await expect(
+ environments.updateEnvironment({ config: { connectorBindings: {} }, id: 'env' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(mocks.updateEnvironment).toHaveBeenCalledTimes(3);
+ });
+
+ it('reports a concurrent Dataset binding repair as a conflict', async () => {
+ const connectorBindings = { mock: { connectorId: '5d9f523a-7180-4d3e-9242-906abc41a612' } };
+ mocks.findEnvironment.mockResolvedValue({ config: { connectorBindings } });
+ mocks.updateEnvironment.mockRejectedValue(new AgentEvalEnvironmentBindingError());
+ await expect(
+ environments.updateEnvironment({ config: { connectorBindings }, id: 'env' }),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+ });
+
+ it('rejects inaccessible bindings on every direct environment or case write path', async () => {
+ const environment = {
+ connectorBindings: { mock: { connectorId: '5d9f523a-7180-4d3e-9242-906abc41a612' } },
+ mock: { services: ['mock'] },
+ };
+ const content = { environment, input: 'Test' };
+ mocks.validateBindings.mockRejectedValue(
+ new EvalConnectorBindingError('The selected mock connection is unavailable'),
+ );
+ for (const request of [
+ () => environments.createEnvironment({ config: environment, name: 'Mock environment' }),
+ () => environments.updateEnvironment({ config: environment, id: 'env' }),
+ () => cases.createTestCase({ content, datasetId: 'dataset' }),
+ () => cases.batchCreateTestCases({ cases: [{ content }], datasetId: 'dataset' }),
+ () => cases.updateTestCase({ content, id: 'case' }),
+ () => datasets.createDataset({ cases: [{ content }], identifier: 'copy', name: 'Copy' }),
+ ]) {
+ await expect(request()).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ }
+ for (const write of [
+ mocks.createEnvironment,
+ mocks.updateEnvironment,
+ mocks.create,
+ mocks.batchCreate,
+ mocks.update,
+ mocks.createDataset,
+ ]) {
+ expect(write).not.toHaveBeenCalled();
+ }
+ });
+});
+
+describe('dataset write failures', () => {
+ it('returns permission errors for rejected case writes, not internal errors', async () => {
+ await expect(
+ cases.createTestCase({ content: { input: 'Case' }, datasetId: 'blocked' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ await expect(
+ cases.batchCreateTestCases({ cases: [{ content: { input: 'Case' } }], datasetId: 'blocked' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ await expect(
+ cases.updateTestCase({ content: { input: 'Changed' }, id: 'fixed-case' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('reports a frozen case deletion as unsuccessful using the existing response shape', async () => {
+ await expect(cases.deleteTestCase({ id: 'fixed-case' })).resolves.toMatchObject({
+ success: false,
+ });
+ });
+
+ it('returns permission errors for frozen dataset updates and unreadable copied environments', async () => {
+ await expect(datasets.updateDataset({ id: 'fixed', metadata: {} })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ await expect(
+ datasets.createDataset({
+ cases: [{ content: { input: 'Copy' }, environmentId: 'foreign' }],
+ identifier: 'copy',
+ name: 'Copy',
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentEval/datasets.ts b/apps/server/src/routers/lambda/agentEval/datasets.ts
index b845c2e2c76..9daf3bbf451 100644
--- a/apps/server/src/routers/lambda/agentEval/datasets.ts
+++ b/apps/server/src/routers/lambda/agentEval/datasets.ts
@@ -2,12 +2,20 @@ import { parseDataset } from '@lobechat/eval-dataset-parser';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
+import { AgentEvalDatasetWriteError } from '@/database/models/agentEval/datasetAccess';
import { router } from '@/libs/trpc/lambda';
+import {
+ importDatasetPackageProcedure,
+ previewDatasetPackage,
+ readDatasetPackageUpload,
+} from './datasetPackages';
+import { assertDatasetDeletable, assertDatasetMove } from './lobeBenchMembership';
import { agentEvalProcedure, agentEvalProcedureWrite } from './procedures';
-import { evalConfigSchema, rubricTypeSchema } from './schemas';
+import { evalConfigSchema, evalTestCaseContentSchema, rubricTypeSchema } from './schemas';
export const datasetRouter = router({
+ importDatasetPackage: importDatasetPackageProcedure,
// ============================================
// Dataset Operations
// ============================================
@@ -24,11 +32,24 @@ export const datasetRouter = router({
evalConfig: evalConfigSchema.optional(),
metadata: z.record(z.string(), z.unknown()).optional(),
sourceExperimentId: z.string().optional(),
+ cases: z
+ .array(
+ z.object({
+ content: evalTestCaseContentSchema,
+ environmentId: z.string().nullish(),
+ evalMode: rubricTypeSchema.optional(),
+ evalConfig: evalConfigSchema.optional(),
+ metadata: z.record(z.string(), z.unknown()).optional(),
+ sortOrder: z.number().optional(),
+ }),
+ )
+ .optional(),
}),
)
.mutation(async ({ input, ctx }) => {
try {
- const result = await ctx.datasetModel.create(input);
+ const { cases, ...dataset } = input;
+ const result = await ctx.datasetModel.create(dataset, cases);
if (!result) {
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
@@ -37,6 +58,9 @@ export const datasetRouter = router({
}
return result;
} catch (error: any) {
+ if (error instanceof AgentEvalDatasetWriteError) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: error.message });
+ }
// PostgreSQL errors might be in error.cause
const pgError = error?.cause || error;
@@ -75,6 +99,9 @@ export const datasetRouter = router({
.input(
z.object({
id: z.string(),
+ // Moves the dataset into another benchmark the caller can see (its own, or a
+ // built-in one), e.g. an account dataset into a benchmark the account made.
+ benchmarkId: z.string().optional(),
name: z.string().optional(),
description: z.string().optional(),
evalMode: rubricTypeSchema.nullish(),
@@ -84,7 +111,22 @@ export const datasetRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { id, ...data } = input;
- const result = await ctx.datasetModel.update(id, data);
+ await assertDatasetMove(ctx, id, data.benchmarkId);
+ if (data.benchmarkId && !(await ctx.benchmarkModel.findById(data.benchmarkId))) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Benchmark with id "${data.benchmarkId}" not found`,
+ });
+ }
+ let result;
+ try {
+ result = await ctx.datasetModel.update(id, data);
+ } catch (error) {
+ if (error instanceof AgentEvalDatasetWriteError) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: error.message });
+ }
+ throw error;
+ }
if (!result) {
throw new TRPCError({
code: 'NOT_FOUND',
@@ -96,8 +138,9 @@ export const datasetRouter = router({
deleteDataset: agentEvalProcedureWrite
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
+ await assertDatasetDeletable(ctx, input.id);
try {
- const result = await ctx.datasetModel.delete(input.id);
+ const result = await ctx.datasetDeletionRepo.deleteDataset(input.id);
// Check if any rows were affected
if (result.rowCount === 0) {
return {
@@ -117,7 +160,7 @@ export const datasetRouter = router({
.input(
z.object({
pathname: z.string(),
- format: z.enum(['json', 'jsonl', 'csv', 'xlsx']).optional(),
+ format: z.enum(['json', 'jsonl', 'csv', 'xlsx', 'zip']).optional(),
filename: z.string().optional(),
}),
)
@@ -126,14 +169,24 @@ export const datasetRouter = router({
const format = input.format || 'auto';
const resolvedFilename = input.filename || input.pathname;
const isXlsx = format === 'xlsx' || resolvedFilename?.match(/\.xlsx?$/i);
+ const isZip = format === 'zip' || /\.zip$/i.test(resolvedFilename);
+ // Storage failures are not user validation errors; only parse failures below are BAD_REQUEST.
+ const archive = isZip
+ ? await readDatasetPackageUpload(ctx.fileService, input.pathname)
+ : undefined;
+ const content =
+ archive ??
+ (isXlsx
+ ? await ctx.fileService.getFileByteArray(input.pathname)
+ : await ctx.fileService.getFileContent(input.pathname));
try {
- const content = isXlsx
- ? await ctx.fileService.getFileByteArray(input.pathname)
- : await ctx.fileService.getFileContent(input.pathname);
+ if (archive) {
+ return previewDatasetPackage(archive);
+ }
const result = parseDataset(content, {
filename: resolvedFilename,
- format: format === 'auto' ? undefined : format,
+ format: format === 'auto' || format === 'zip' ? undefined : format,
preview: 50,
});
@@ -142,6 +195,7 @@ export const datasetRouter = router({
preview: result.rows,
totalCount: result.totalCount,
format: result.format,
+ datasetPackage: undefined,
};
} catch (error: any) {
if (upload) await ctx.fileUploadService.releaseBestEffort(input.pathname);
@@ -267,6 +321,11 @@ export const datasetRouter = router({
imported = true;
return { count: result.length, data: result };
+ } catch (error) {
+ if (error instanceof AgentEvalDatasetWriteError) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: error.message });
+ }
+ throw error;
} finally {
if (upload) await ctx.fileUploadService.releaseBestEffort(input.pathname);
else if (imported) await ctx.fileService.deleteFile(input.pathname);
diff --git a/apps/server/src/routers/lambda/agentEval/environments.ts b/apps/server/src/routers/lambda/agentEval/environments.ts
new file mode 100644
index 00000000000..5892ff06009
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/environments.ts
@@ -0,0 +1,118 @@
+import type { EvalCaseEnvironment } from '@lobechat/types';
+import { redactEnvironmentConnections } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import {
+ AgentEvalEnvironmentBindingError,
+ hasSameEvalConnectorBindings,
+} from '@/database/models/agentEval/environment';
+import { router } from '@/libs/trpc/lambda';
+
+import { validateEvalConnectorBindings } from './connectorBindings';
+import { agentEvalProcedure, agentEvalProcedureWrite } from './procedures';
+import { evalCaseEnvironmentSchema } from './schemas';
+
+/**
+ * Stored connections are written only by import and the Dataset connection API.
+ * Clients get redacted copies and may send them back unchanged: drop them here.
+ */
+const environmentConfigInput = z.preprocess((value) => {
+ if (!value || typeof value !== 'object' || !('connections' in value)) return value;
+ const { connections: _redacted, ...config } = value as Record<string, unknown>;
+ return config;
+}, evalCaseEnvironmentSchema);
+
+/** An Environment row as it leaves the server: connection credentials removed. */
+const redacted = <T extends { config: EvalCaseEnvironment } | null | undefined>(row: T): T =>
+ row ? { ...row, config: redactEnvironmentConnections(row.config) } : row;
+
+/**
+ * Reusable case environments: the Agent setup, Memory fixture, clock and mock
+ * connectors that many cases share. Cases point at one through
+ * `environmentId`; deleting an environment leaves its cases without one.
+ */
+export const environmentRouter = router({
+ createEnvironment: agentEvalProcedureWrite
+ .input(
+ z.object({
+ config: environmentConfigInput,
+ description: z.string().optional(),
+ identifier: z.string().trim().min(1).max(200).optional(),
+ metadata: z.record(z.string(), z.unknown()).optional(),
+ name: z.string().trim().min(1).max(200),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ await validateEvalConnectorBindings(
+ ctx.evalConnectorServiceForDataset,
+ input.config.connectorBindings,
+ );
+ return redacted(await ctx.environmentModel.create(input));
+ } catch (error: any) {
+ const pgError = error?.cause || error;
+ if (pgError?.code === '23505') {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: `Environment with identifier "${input.identifier}" already exists`,
+ });
+ }
+ throw error;
+ }
+ }),
+ listEnvironments: agentEvalProcedure.query(async ({ ctx }) =>
+ (await ctx.environmentModel.query()).map(redacted),
+ ),
+ getEnvironment: agentEvalProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ ctx, input }) => {
+ const environment = await ctx.environmentModel.findById(input.id);
+ if (!environment)
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
+ return redacted(environment);
+ }),
+ updateEnvironment: agentEvalProcedureWrite
+ .input(
+ z.object({
+ config: environmentConfigInput.optional(),
+ description: z.string().nullish(),
+ id: z.string(),
+ identifier: z.string().trim().min(1).max(200).nullish(),
+ metadata: z.record(z.string(), z.unknown()).nullish(),
+ name: z.string().trim().min(1).max(200).optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { id, ...data } = input;
+ if (data.config?.connectorBindings !== undefined) {
+ const current = await ctx.environmentModel.findById(id);
+ if (
+ !hasSameEvalConnectorBindings(
+ data.config.connectorBindings,
+ current?.config.connectorBindings,
+ )
+ )
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Manage evaluation connections within their Dataset.',
+ });
+ }
+ let result;
+ try {
+ result = await ctx.environmentModel.update(id, data);
+ } catch (error) {
+ if (error instanceof AgentEvalEnvironmentBindingError)
+ throw new TRPCError({ code: 'CONFLICT', message: error.message });
+ throw error;
+ }
+ if (!result) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });
+ return redacted(result);
+ }),
+ deleteEnvironment: agentEvalProcedureWrite
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ const result = await ctx.environmentModel.delete(input.id);
+ return { success: (result.rowCount ?? 0) > 0 };
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agentEval/experiments.delete.test.ts b/apps/server/src/routers/lambda/agentEval/experiments.delete.test.ts
new file mode 100644
index 00000000000..ff8efd9b394
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/experiments.delete.test.ts
@@ -0,0 +1,83 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createCallerFactory } from '@/libs/trpc/lambda';
+
+import { experimentRouter } from './experiments';
+import type * as Procedures from './procedures';
+
+const mocks = vi.hoisted(() => ({
+ deleteRun: vi.fn(),
+ experimentDelete: vi.fn(),
+ runQuery: vi.fn(),
+}));
+
+// Bare procedure with mocked models so only the mutation body runs.
+vi.mock('./procedures', async (importOriginal) => {
+ const actual = await importOriginal<typeof Procedures>();
+ const { publicProcedure } = await import('@/libs/trpc/lambda');
+ const procedure = publicProcedure.use((opts) =>
+ opts.next({
+ ctx: {
+ experimentModel: { delete: mocks.experimentDelete },
+ runModel: { query: mocks.runQuery },
+ runService: { deleteRun: mocks.deleteRun },
+ } as any,
+ }),
+ );
+ return { ...actual, agentEvalProcedure: procedure, agentEvalProcedureWrite: procedure };
+});
+
+const experiments = createCallerFactory(experimentRouter)({} as any);
+
+describe('deleteExperiment', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.experimentDelete.mockResolvedValue({ rowCount: 1 });
+ mocks.deleteRun.mockResolvedValue({ rowCount: 1 });
+ });
+
+ it('only detaches runs by default (Evaluation Lab semantics)', async () => {
+ await expect(experiments.deleteExperiment({ id: 'exp_1' })).resolves.toEqual({ success: true });
+ expect(mocks.runQuery).not.toHaveBeenCalled();
+ expect(mocks.deleteRun).not.toHaveBeenCalled();
+ expect(mocks.experimentDelete).toHaveBeenCalledWith('exp_1');
+ });
+
+ it('deletes every run of the experiment before the experiment when asked to', async () => {
+ mocks.runQuery.mockResolvedValue([
+ { id: 'run_a', status: 'completed' },
+ { id: 'run_b', status: 'failed' },
+ ]);
+ await expect(experiments.deleteExperiment({ id: 'exp_1', withRuns: true })).resolves.toEqual({
+ success: true,
+ });
+ expect(mocks.runQuery).toHaveBeenCalledWith({ experimentId: 'exp_1' });
+ expect(mocks.deleteRun.mock.calls.map(([id]) => id).sort()).toEqual(['run_a', 'run_b']);
+ expect(mocks.deleteRun.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.experimentDelete.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('refuses while a run is still in flight and deletes nothing', async () => {
+ mocks.runQuery.mockResolvedValue([
+ { id: 'run_a', status: 'completed' },
+ { id: 'run_b', status: 'running' },
+ ]);
+ await expect(experiments.deleteExperiment({ id: 'exp_1', withRuns: true })).resolves.toEqual({
+ error: 'Stop the experiment before deleting it',
+ success: false,
+ });
+ expect(mocks.deleteRun).not.toHaveBeenCalled();
+ expect(mocks.experimentDelete).not.toHaveBeenCalled();
+ });
+
+ it('reports an unknown experiment', async () => {
+ mocks.runQuery.mockResolvedValue([]);
+ mocks.experimentDelete.mockResolvedValue({ rowCount: 0 });
+ await expect(experiments.deleteExperiment({ id: 'exp_x', withRuns: true })).resolves.toEqual({
+ error: 'Experiment not found',
+ success: false,
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentEval/experiments.ts b/apps/server/src/routers/lambda/agentEval/experiments.ts
index 7812d6667a8..4514bdf6ede 100644
--- a/apps/server/src/routers/lambda/agentEval/experiments.ts
+++ b/apps/server/src/routers/lambda/agentEval/experiments.ts
@@ -7,6 +7,9 @@ import { router } from '@/libs/trpc/lambda';
import { RUN_ENRICHMENT_CONCURRENCY } from './constants';
import { agentEvalProcedure, agentEvalProcedureWrite } from './procedures';
+/** Run statuses that still have work in flight; such an experiment is stopped before it is deleted. */
+const ACTIVE_RUN_STATUSES = new Set(['pending', 'running']);
+
export const experimentRouter = router({
// ============================================
// Experiment Operations
@@ -76,9 +79,23 @@ export const experimentRouter = router({
return { data: result, success: true };
}),
deleteExperiment: agentEvalProcedureWrite
- .input(z.object({ id: z.string() }))
+ .input(
+ z.object({
+ id: z.string(),
+ // Lobe Bench: an experiment owns its runs, so deleting it deletes them too (results,
+ // topics and case Agents go with each run) instead of detaching them like the Lab does.
+ withRuns: z.boolean().optional(),
+ }),
+ )
.mutation(async ({ input, ctx }) => {
try {
+ if (input.withRuns) {
+ const runs = await ctx.runModel.query({ experimentId: input.id });
+ if (runs.some((run) => ACTIVE_RUN_STATUSES.has(run.status))) {
+ return { success: false, error: 'Stop the experiment before deleting it' };
+ }
+ await pMap(runs, (run) => ctx.runService.deleteRun(run.id), { concurrency: 4 });
+ }
const result = await ctx.experimentModel.delete(input.id);
if (result.rowCount === 0) {
return { success: false, error: 'Experiment not found' };
diff --git a/apps/server/src/routers/lambda/agentEval/index.procedures.test.ts b/apps/server/src/routers/lambda/agentEval/index.procedures.test.ts
index 570fb437201..08b68064db9 100644
--- a/apps/server/src/routers/lambda/agentEval/index.procedures.test.ts
+++ b/apps/server/src/routers/lambda/agentEval/index.procedures.test.ts
@@ -28,18 +28,26 @@ function expected(): Array<
['abortRun', 'mutation', 13],
['batchCreateTestCases', 'mutation', 13],
['batchResumeRunCases', 'mutation', 13],
+ ['checkProviders', 'query', 12],
['createBenchmark', 'mutation', 13],
['createDataset', 'mutation', 13],
+ ['createEvalConnector', 'mutation', 13],
+ ['createEnvironment', 'mutation', 13],
['createExperiment', 'mutation', 13],
['createRun', 'mutation', 13],
['createTestCase', 'mutation', 13],
['deleteBenchmark', 'mutation', 13],
['deleteDataset', 'mutation', 13],
+ ['deleteEnvironment', 'mutation', 13],
['deleteExperiment', 'mutation', 13],
['deleteRun', 'mutation', 13],
['deleteTestCase', 'mutation', 13],
+ ['draftTestCaseFromTopic', 'mutation', 13],
['getBenchmark', 'query', 12],
['getDataset', 'query', 12],
+ ['getDatasetConnectorBindings', 'query', 12],
+ ['getEvalConnector', 'query', 12],
+ ['getEnvironment', 'query', 12],
['getExperiment', 'query', 12],
['getResumableCases', 'query', 12],
['getRunDetails', 'query', 12],
@@ -47,22 +55,33 @@ function expected(): Array<
['getRunResults', 'query', 12],
['getTestCase', 'query', 12],
['importDataset', 'mutation', 13],
+ ['importDatasetPackage', 'mutation', 13],
['listBenchmarks', 'query', 12],
['listDatasets', 'query', 12],
+ ['listEnvironments', 'query', 11],
+ ['listEvalConnectors', 'query', 12],
['listExperiments', 'query', 11],
['listRuns', 'query', 12],
['listTestCases', 'query', 12],
['parseDatasetFile', 'mutation', 13],
+ ['rejudgeRun', 'mutation', 13],
+ ['rerunRunUnverified', 'mutation', 13],
['resumeRunCase', 'mutation', 13],
['retryRunCase', 'mutation', 13],
['retryRunErrors', 'mutation', 13],
['startRun', 'mutation', 13],
+ ['testEvalConnector', 'mutation', 13],
['updateBenchmark', 'mutation', 13],
['updateDataset', 'mutation', 13],
+ ['updateDatasetConnectorBindings', 'mutation', 13],
+ ['updateEvalConnector', 'mutation', 13],
+ ['updateEnvironment', 'mutation', 13],
['updateExperiment', 'mutation', 13],
['updateRun', 'mutation', 13],
['updateRunMetrics', 'mutation', 13],
['updateRunStatus', 'mutation', 13],
['updateTestCase', 'mutation', 13],
- ];
+ ].sort(([a], [b]) => String(a).localeCompare(String(b))) as Array<
+ [string, 'mutation' | 'query' | 'subscription', number]
+ >;
}
diff --git a/apps/server/src/routers/lambda/agentEval/index.ts b/apps/server/src/routers/lambda/agentEval/index.ts
index 13578378dbc..ce59cc95fca 100644
--- a/apps/server/src/routers/lambda/agentEval/index.ts
+++ b/apps/server/src/routers/lambda/agentEval/index.ts
@@ -1,7 +1,10 @@
import { mergeRouters } from '@/libs/trpc/lambda';
import { benchmarkRouter } from './benchmarks';
+import { evalConnectorRouter } from './connectors';
+import { datasetConnectionRouter } from './datasetConnections';
import { datasetRouter } from './datasets';
+import { environmentRouter } from './environments';
import { experimentRouter } from './experiments';
import { runRouter } from './runs';
import { testCaseRouter } from './testCases';
@@ -10,6 +13,9 @@ export const agentEvalRouter = mergeRouters(
benchmarkRouter,
experimentRouter,
datasetRouter,
+ datasetConnectionRouter,
+ evalConnectorRouter,
+ environmentRouter,
testCaseRouter,
runRouter,
);
diff --git a/apps/server/src/routers/lambda/agentEval/lobeBenchMembership.test.ts b/apps/server/src/routers/lambda/agentEval/lobeBenchMembership.test.ts
new file mode 100644
index 00000000000..550e49a2e15
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/lobeBenchMembership.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ assertDatasetDeletable,
+ assertDatasetMove,
+ prepareBenchmarkDeletion,
+} from './lobeBenchMembership';
+
+const lobeBench = { kind: 'lobe-bench' };
+
+const context = (rows: {
+ benchmarks?: Record<string, { metadata?: Record<string, unknown> }>;
+ datasets?: Record<string, { benchmarkId?: string | null; metadata?: Record<string, unknown> }>;
+ /** Experiments linked to the benchmark, as they stand once its runs are gone. */
+ experiments?: Record<string, { benchmarks: Array<{ id: string }>; runs: unknown[] }>;
+ runs?: Array<{ id: string; status?: string }>;
+}) => {
+ const deleteRun = vi.fn(async () => undefined);
+ const releaseDatasets = vi.fn(async () => 1);
+ const deleteExperiment = vi.fn(async () => undefined);
+ return {
+ ctx: {
+ benchmarkModel: {
+ findById: async (id: string) => rows.benchmarks?.[id],
+ releaseDatasets,
+ },
+ datasetModel: { findById: async (id: string) => rows.datasets?.[id] },
+ experimentModel: {
+ delete: deleteExperiment,
+ findByBenchmarkIds: async () =>
+ Object.keys(rows.experiments ?? {}).map((experimentId) => ({ experimentId })),
+ findById: async (id: string) => rows.experiments?.[id],
+ },
+ runModel: { query: async () => rows.runs ?? [] },
+ runService: { deleteRun },
+ },
+ deleteExperiment,
+ deleteRun,
+ releaseDatasets,
+ };
+};
+
+describe('Lobe Bench datasets and the benchmark they are in', () => {
+ it('lets a free dataset join a benchmark that has not run yet', async () => {
+ const { ctx } = context({
+ benchmarks: { fresh: { metadata: lobeBench } },
+ datasets: { ds: { benchmarkId: null, metadata: lobeBench } },
+ });
+ await expect(assertDatasetMove(ctx, 'ds', 'fresh')).resolves.toBeUndefined();
+ });
+
+ it('keeps a dataset in its benchmark and a benchmark that has run closed', async () => {
+ const inBenchmark = context({
+ benchmarks: { other: { metadata: lobeBench } },
+ datasets: { ds: { benchmarkId: 'mine', metadata: lobeBench } },
+ });
+ await expect(assertDatasetMove(inBenchmark.ctx, 'ds', 'other')).rejects.toThrow(
+ 'stays in the benchmark',
+ );
+ const ran = context({
+ benchmarks: { ran: { metadata: lobeBench } },
+ datasets: { ds: { benchmarkId: null, metadata: lobeBench } },
+ runs: [{ id: 'run', status: 'completed' }],
+ });
+ await expect(assertDatasetMove(ran.ctx, 'ds', 'ran')).rejects.toThrow('has runs');
+ });
+
+ it('leaves Evaluation Lab datasets alone', async () => {
+ const { ctx } = context({ datasets: { ds: { benchmarkId: 'a', metadata: {} } } });
+ await expect(assertDatasetMove(ctx, 'ds', 'b')).resolves.toBeUndefined();
+ await expect(assertDatasetDeletable(ctx, 'ds')).resolves.toBeUndefined();
+ });
+
+ it('deletes a dataset in a benchmark only with the benchmark', async () => {
+ const { ctx } = context({
+ datasets: {
+ free: { benchmarkId: null, metadata: lobeBench },
+ taken: { benchmarkId: 'bench', metadata: lobeBench },
+ },
+ });
+ await expect(assertDatasetDeletable(ctx, 'taken')).rejects.toThrow('Delete the benchmark');
+ await expect(assertDatasetDeletable(ctx, 'free')).resolves.toBeUndefined();
+ });
+
+ it('deletes a benchmark’s runs and frees its datasets before the benchmark goes', async () => {
+ const { ctx, deleteRun, releaseDatasets } = context({
+ benchmarks: { bench: { metadata: lobeBench } },
+ runs: [
+ { id: 'run-1', status: 'completed' },
+ { id: 'run-2', status: 'failed' },
+ ],
+ });
+ await prepareBenchmarkDeletion(ctx, 'bench');
+ expect(deleteRun.mock.calls).toEqual([['run-1'], ['run-2']]);
+ expect(releaseDatasets).toHaveBeenCalledWith('bench');
+ });
+
+ it('deletes an experiment left empty by the benchmark, keeping ones that span others or still run', async () => {
+ const { ctx, deleteExperiment } = context({
+ benchmarks: { bench: { metadata: lobeBench } },
+ experiments: {
+ emptied: { benchmarks: [{ id: 'bench' }], runs: [] },
+ sharedWithAnother: { benchmarks: [{ id: 'bench' }, { id: 'other' }], runs: [] },
+ stillHasRuns: { benchmarks: [{ id: 'bench' }], runs: [{ id: 'kept' }] },
+ },
+ runs: [{ id: 'run-1', status: 'completed' }],
+ });
+ await prepareBenchmarkDeletion(ctx, 'bench');
+ expect(deleteExperiment.mock.calls).toEqual([['emptied']]);
+ });
+
+ it('refuses to delete a benchmark while one of its runs is going', async () => {
+ const { ctx, deleteRun, releaseDatasets } = context({
+ benchmarks: { bench: { metadata: lobeBench } },
+ runs: [{ id: 'run-1', status: 'running' }],
+ });
+ await expect(prepareBenchmarkDeletion(ctx, 'bench')).rejects.toThrow('Stop the experiments');
+ expect(deleteRun).not.toHaveBeenCalled();
+ expect(releaseDatasets).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentEval/lobeBenchMembership.ts b/apps/server/src/routers/lambda/agentEval/lobeBenchMembership.ts
new file mode 100644
index 00000000000..a0cf3c9512d
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/lobeBenchMembership.ts
@@ -0,0 +1,94 @@
+import { TRPCError } from '@trpc/server';
+
+/** `metadata.kind` of Lobe Bench rows (the Evaluation Lab's have none). */
+const LOBE_BENCH_KIND = 'lobe-bench';
+
+type Metadata = Record<string, unknown> | null | undefined;
+
+const isLobeBench = (metadata: Metadata) => metadata?.kind === LOBE_BENCH_KIND;
+
+interface MembershipContext {
+ benchmarkModel: {
+ findById: (id: string) => Promise<{ metadata?: Metadata } | undefined | null>;
+ releaseDatasets: (id: string) => Promise<number>;
+ };
+ datasetModel: {
+ findById: (
+ id: string,
+ ) => Promise<{ benchmarkId?: string | null; metadata?: Metadata } | undefined | null>;
+ };
+ experimentModel: {
+ delete: (id: string) => Promise<unknown>;
+ findByBenchmarkIds: (benchmarkIds: string[]) => Promise<Array<{ experimentId: string }>>;
+ findById: (
+ id: string,
+ ) => Promise<{ benchmarks: Array<{ id: string }>; runs: unknown[] } | undefined>;
+ };
+ runModel: {
+ query: (filter: {
+ benchmarkId: string;
+ limit?: number;
+ }) => Promise<Array<{ id: string; status?: string | null }>>;
+ };
+ runService: { deleteRun: (id: string) => Promise<unknown> };
+}
+
+const refuse = (message: string) => new TRPCError({ code: 'BAD_REQUEST', message });
+
+/**
+ * A Lobe Bench benchmark is made of its datasets once: a dataset in one stays
+ * in it until the benchmark is deleted, and a benchmark that has run takes no
+ * more. (Making one adds its datasets right after creating it, before any run.)
+ */
+export const assertDatasetMove = async (
+ ctx: MembershipContext,
+ datasetId: string,
+ benchmarkId: string | undefined,
+) => {
+ if (benchmarkId === undefined) return;
+ const dataset = await ctx.datasetModel.findById(datasetId);
+ if (!dataset || !isLobeBench(dataset.metadata)) return;
+ if ((dataset.benchmarkId ?? null) === benchmarkId) return;
+ if (dataset.benchmarkId)
+ throw refuse(
+ 'A dataset stays in the benchmark it is part of. Delete the benchmark to use its datasets elsewhere.',
+ );
+ const target = await ctx.benchmarkModel.findById(benchmarkId);
+ if (!isLobeBench(target?.metadata)) return;
+ if ((await ctx.runModel.query({ benchmarkId, limit: 1 })).length > 0)
+ throw refuse('A benchmark that has runs keeps the datasets it was made of.');
+};
+
+/** A dataset in a Lobe Bench benchmark is deleted only by deleting the benchmark. */
+export const assertDatasetDeletable = async (ctx: MembershipContext, datasetId: string) => {
+ const dataset = await ctx.datasetModel.findById(datasetId);
+ if (dataset && isLobeBench(dataset.metadata) && dataset.benchmarkId)
+ throw refuse(
+ 'This dataset is part of a benchmark. Delete the benchmark first; its datasets are kept.',
+ );
+};
+
+/**
+ * Before a Lobe Bench benchmark is deleted: its runs go with it (with their
+ * conversations and case Agents), and its datasets are freed rather than
+ * deleted. An experiment made on this benchmark alone is left with nothing
+ * once its runs go, so it goes too; one that spans other benchmarks or still
+ * has runs stays. Refused while one of its runs is still going.
+ */
+export const prepareBenchmarkDeletion = async (ctx: MembershipContext, benchmarkId: string) => {
+ const benchmark = await ctx.benchmarkModel.findById(benchmarkId);
+ if (!isLobeBench(benchmark?.metadata)) return;
+ const runs = await ctx.runModel.query({ benchmarkId });
+ if (runs.some((run) => run.status === 'pending' || run.status === 'running'))
+ throw refuse('Stop the experiments still running on this benchmark before deleting it.');
+ const experiments = await ctx.experimentModel.findByBenchmarkIds([benchmarkId]);
+ for (const run of runs) await ctx.runService.deleteRun(run.id);
+ await ctx.benchmarkModel.releaseDatasets(benchmarkId);
+ for (const { experimentId } of experiments) {
+ const experiment = await ctx.experimentModel.findById(experimentId);
+ if (!experiment) continue;
+ const onlyThisBenchmark = experiment.benchmarks.every(({ id }) => id === benchmarkId);
+ if (onlyThisBenchmark && experiment.runs.length === 0)
+ await ctx.experimentModel.delete(experimentId);
+ }
+};
diff --git a/apps/server/src/routers/lambda/agentEval/procedures.ts b/apps/server/src/routers/lambda/agentEval/procedures.ts
index 222c5fd6d91..2b14da51205 100644
--- a/apps/server/src/routers/lambda/agentEval/procedures.ts
+++ b/apps/server/src/routers/lambda/agentEval/procedures.ts
@@ -3,12 +3,20 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceA
import {
AgentEvalBenchmarkModel,
AgentEvalDatasetModel,
+ AgentEvalEnvironmentModel,
AgentEvalExperimentModel,
AgentEvalRunModel,
AgentEvalRunTopicModel,
AgentEvalTestCaseModel,
} from '@/database/models/agentEval';
+import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import { AgentEvalDatasetDeletionRepo } from '@/database/repositories/agentEvalDatasetDeletion';
+import { AgentEvalDatasetConnectorRepo } from '@/database/repositories/agentEvalDatasetPackage/datasetConnectorBindings';
+import { AgentEvalEnvironmentConnectionRepo } from '@/database/repositories/agentEvalEnvironmentConnection';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { AgentEvalConnectorService } from '@/server/services/agentEvalConnector';
import { AgentEvalRunService } from '@/server/services/agentEvalRun';
import { FileService } from '@/server/services/file';
import { FileUploadService } from '@/server/services/fileUpload';
@@ -20,7 +28,40 @@ export const agentEvalProcedure = wsCompatProcedure.use(serverDatabase).use(asyn
return opts.next({
ctx: {
benchmarkModel: new AgentEvalBenchmarkModel(ctx.serverDB, ctx.userId, wsId),
+ evalConnectorServiceForDataset: (datasetId: string) =>
+ new AgentEvalConnectorService(ctx.serverDB, ctx.userId, datasetId, wsId),
+ evalConnectorModelsForDataset: async (datasetId: string) => {
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+ return {
+ connectorModel: ConnectorModel.forEvaluation(
+ ctx.serverDB,
+ ctx.userId,
+ datasetId,
+ wsId,
+ gateKeeper,
+ ),
+ connectorToolModel: ConnectorToolModel.forEvaluation(
+ ctx.serverDB,
+ ctx.userId,
+ datasetId,
+ wsId,
+ ),
+ };
+ },
+ evalConnectorGateKeeper: {
+ encrypt: async (plaintext: string) =>
+ (await KeyVaultsGateKeeper.initWithEnvKey()).encrypt(plaintext),
+ },
datasetModel: new AgentEvalDatasetModel(ctx.serverDB, ctx.userId, wsId),
+ datasetConnectorRepo: new AgentEvalDatasetConnectorRepo(ctx.serverDB, ctx.userId, wsId),
+ datasetDeletionRepo: new AgentEvalDatasetDeletionRepo(ctx.serverDB, ctx.userId, wsId),
+ environmentModel: new AgentEvalEnvironmentModel(ctx.serverDB, ctx.userId, wsId),
+ /** Mock connections stored in Environments (`env:` ids). */
+ environmentConnections: new AgentEvalEnvironmentConnectionRepo(
+ ctx.serverDB,
+ ctx.userId,
+ wsId,
+ ),
experimentModel: new AgentEvalExperimentModel(ctx.serverDB, ctx.userId, wsId),
runModel: new AgentEvalRunModel(ctx.serverDB, ctx.userId, wsId),
runService: new AgentEvalRunService(ctx.serverDB, ctx.userId, wsId),
diff --git a/apps/server/src/routers/lambda/agentEval/runCompatibility.test.ts b/apps/server/src/routers/lambda/agentEval/runCompatibility.test.ts
new file mode 100644
index 00000000000..ac64c76ee6c
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/runCompatibility.test.ts
@@ -0,0 +1,109 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createCallerFactory } from '@/libs/trpc/lambda';
+import { EvalConnectorBindingError } from '@/server/services/agentEvalConnector';
+import { EvalCaseCompatibilityError } from '@/server/services/agentEvalRun/caseCompatibility';
+import { EvalResumeConflictError } from '@/server/services/agentEvalRun/resumeTarget';
+
+import { runRouter } from './runs';
+
+const mocks = vi.hoisted(() => ({
+ assertConnectorBindings: vi.fn(),
+ dataset: vi.fn(),
+ rejudge: vi.fn(),
+ rerun: vi.fn(),
+ resume: vi.fn(),
+ retryErrors: vi.fn(),
+ retrySingle: vi.fn(),
+ trigger: vi.fn(),
+ update: vi.fn(),
+}));
+
+vi.mock('./procedures', async () => {
+ const { publicProcedure } = await import('@/libs/trpc/lambda');
+ const procedure = publicProcedure.use((opts) =>
+ opts.next({
+ ctx: {
+ datasetModel: { findById: mocks.dataset },
+ runModel: {
+ findById: async () => ({
+ config: { caseVersion: 'v1' },
+ datasetId: 'dataset',
+ id: 'run',
+ status: 'completed',
+ }),
+ update: mocks.update,
+ },
+ runService: {
+ assertConnectorBindings: mocks.assertConnectorBindings,
+ rejudgeRun: mocks.rejudge,
+ resumeTrajectory: mocks.resume,
+ rerunUnverifiedCases: mocks.rerun,
+ retryErrorCases: mocks.retryErrors,
+ retrySingleCase: mocks.retrySingle,
+ },
+ } as any,
+ }),
+ );
+ return { agentEvalProcedure: procedure, agentEvalProcedureWrite: procedure };
+});
+
+vi.mock('@/server/workflows/agentEvalRun', () => ({
+ AgentEvalRunWorkflow: {
+ triggerExecuteTestCase: mocks.trigger,
+ triggerRunBenchmark: mocks.trigger,
+ },
+}));
+
+const runs = createCallerFactory(runRouter)({} as any);
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.dataset.mockResolvedValue({ metadata: { release: 'v2' } });
+ for (const call of [mocks.rejudge, mocks.rerun, mocks.retryErrors, mocks.retrySingle]) {
+ call.mockRejectedValue(new EvalCaseCompatibilityError('The dataset case version changed'));
+ }
+});
+
+describe('run compatibility conflicts', () => {
+ it('rejects an unavailable mock binding before changing status or dispatching', async () => {
+ mocks.dataset.mockResolvedValue({ metadata: { release: 'v1' } });
+ mocks.assertConnectorBindings.mockRejectedValue(
+ new EvalConnectorBindingError('The selected mock connection is unavailable'),
+ );
+ await expect(runs.startRun({ id: 'run' })).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(mocks.update).not.toHaveBeenCalled();
+ expect(mocks.trigger).not.toHaveBeenCalled();
+ });
+
+ it('rejects starting an old-version run before changing its status or dispatching', async () => {
+ await expect(runs.startRun({ id: 'run' })).rejects.toMatchObject({ code: 'CONFLICT' });
+ expect(mocks.update).not.toHaveBeenCalled();
+ expect(mocks.trigger).not.toHaveBeenCalled();
+ });
+
+ it('maps all rejected rejudge and retry paths to conflicts without dispatching', async () => {
+ await expect(runs.rejudgeRun({ id: 'run' })).rejects.toMatchObject({ code: 'CONFLICT' });
+ await expect(runs.rerunRunUnverified({ id: 'run' })).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ await expect(runs.retryRunErrors({ id: 'run' })).rejects.toMatchObject({ code: 'CONFLICT' });
+ await expect(runs.retryRunCase({ runId: 'run', testCaseId: 'case' })).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(mocks.trigger).not.toHaveBeenCalled();
+ });
+});
+
+it.each([EvalResumeConflictError, EvalCaseCompatibilityError])(
+ 'maps rejected Resume to CONFLICT (%s)',
+ async (ConflictError) => {
+ mocks.resume.mockRejectedValue(new ConflictError('Resume target changed'));
+ await expect(runs.resumeRunCase({ runId: 'run', testCaseId: 'case' })).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(mocks.update).not.toHaveBeenCalled();
+ expect(mocks.trigger).not.toHaveBeenCalled();
+ },
+);
diff --git a/apps/server/src/routers/lambda/agentEval/runs.ts b/apps/server/src/routers/lambda/agentEval/runs.ts
index 2994fe0f523..98222e02d9e 100644
--- a/apps/server/src/routers/lambda/agentEval/runs.ts
+++ b/apps/server/src/routers/lambda/agentEval/runs.ts
@@ -4,10 +4,23 @@ import pMap from 'p-map';
import { z } from 'zod';
import { router } from '@/libs/trpc/lambda';
-import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
+import { EvalConnectorBindingError } from '@/server/services/agentEvalConnector';
+import { AgentEvalRunService, RUN_CREATE_ID_CONFLICT } from '@/server/services/agentEvalRun';
+import { CASE_AGENT_MODEL_REQUIRED } from '@/server/services/agentEvalRun/caseAgent';
+import {
+ assertRunCaseCompatibility,
+ EvalCaseCompatibilityError,
+} from '@/server/services/agentEvalRun/caseCompatibility';
+import {
+ RUN_DATASET_NOT_FOUND,
+ RUN_EMPTY_SELECTION,
+} from '@/server/services/agentEvalRun/createRun';
+import { EvalResumeConflictError } from '@/server/services/agentEvalRun/resumeTarget';
import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';
import { evalRunInputConfigSchema } from '../evalRunConfig.schema';
+import { assertRunFollowsBenchmark } from './benchmarkStandard';
import { RUN_ENRICHMENT_CONCURRENCY } from './constants';
import { agentEvalProcedure, agentEvalProcedureWrite } from './procedures';
@@ -17,12 +30,48 @@ const log = debug('lobe-lambda-router:agent-eval');
const BATCH_RESUME_CONCURRENCY = 5;
export const runRouter = router({
+ /**
+ * Whether this server can call each provider for the current user: the same
+ * runtime construction an eval run performs before its first model call, so
+ * a missing key (account or server) is caught before an experiment spends
+ * attempts on `InvalidProviderAPIKey` errors.
+ */
+ checkProviders: agentEvalProcedure
+ .input(z.object({ providers: z.array(z.string().trim().min(1)).max(20) }))
+ .query(async ({ input, ctx }) => {
+ const providers = [...new Set(input.providers)];
+ return pMap(
+ providers,
+ async (provider) => {
+ try {
+ await initModelRuntimeFromDB(
+ ctx.serverDB,
+ ctx.userId,
+ provider,
+ ctx.workspaceId ?? undefined,
+ );
+ return { ok: true as const, provider };
+ } catch (error) {
+ const detail = error as { errorType?: string; message?: string } | undefined;
+ return {
+ error: detail?.errorType ?? detail?.message ?? 'Provider unavailable',
+ ok: false as const,
+ provider,
+ };
+ }
+ },
+ { concurrency: 4 },
+ );
+ }),
// ============================================
// Run Operations
// ============================================
createRun: agentEvalProcedureWrite
.input(
z.object({
+ // Optional caller-supplied id: a client that checkpoints its launch can
+ // retry the same create after a lost response without making a second run.
+ id: z.string().trim().min(1).max(64).optional(),
datasetId: z.string(),
targetAgentId: z.string().optional(),
name: z.string().optional(),
@@ -34,6 +83,11 @@ export const runRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
+ const dataset = await ctx.datasetModel.findById(input.datasetId);
+ const benchmark = dataset?.benchmarkId
+ ? await ctx.benchmarkModel.findById(dataset.benchmarkId)
+ : undefined;
+ assertRunFollowsBenchmark(input.config, benchmark?.metadata);
try {
const result = await ctx.runService.createRun(input);
if (!result) {
@@ -52,6 +106,20 @@ export const runRouter = router({
if (pgError?.message === 'Parent run not found') {
throw new TRPCError({ code: 'BAD_REQUEST', message: 'Parent run not found' });
}
+ if (pgError?.message === CASE_AGENT_MODEL_REQUIRED) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: CASE_AGENT_MODEL_REQUIRED });
+ }
+ if (pgError?.message === RUN_EMPTY_SELECTION) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: RUN_EMPTY_SELECTION });
+ }
+ if (pgError?.message === RUN_DATASET_NOT_FOUND) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: RUN_DATASET_NOT_FOUND });
+ }
+ // The id is taken by a run this caller cannot see, or by one created with
+ // other parameters: say so without describing the other run.
+ if (pgError?.message === RUN_CREATE_ID_CONFLICT) {
+ throw new TRPCError({ code: 'CONFLICT', message: RUN_CREATE_ID_CONFLICT });
+ }
// Check for foreign key violation (dataset not found)
if (pgError?.code === '23503' && pgError?.constraint?.includes('dataset')) {
@@ -173,6 +241,19 @@ export const runRouter = router({
});
}
+ try {
+ await assertRunCaseCompatibility(ctx, run);
+ await ctx.runService.assertConnectorBindings(run);
+ } catch (error) {
+ if (error instanceof EvalConnectorBindingError) {
+ throw new TRPCError({ code: error.code, message: error.message });
+ }
+ if (error instanceof EvalCaseCompatibilityError) {
+ throw new TRPCError({ code: 'CONFLICT', message: error.message });
+ }
+ throw error;
+ }
+
// Set status to pending immediately so frontend gets feedback
await ctx.runModel.update(runId, { status: 'pending' });
@@ -208,6 +289,42 @@ export const runRouter = router({
return { success: true };
}),
+ /**
+ * Run again every case of a finished run that has an attempt without a
+ * verdict (error, timeout, judge failure), with the run's own settings.
+ */
+ rerunRunUnverified: agentEvalProcedureWrite
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ const run = await ctx.runModel.findById(input.id);
+ if (!run) throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
+
+ if (!['completed', 'failed', 'aborted'].includes(run.status)) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Cannot rerun: status=${run.status}`,
+ });
+ }
+
+ let rerunCount: number;
+ try {
+ ({ rerunCount } = await ctx.runService.rerunUnverifiedCases(input.id));
+ } catch (error) {
+ if (error instanceof EvalCaseCompatibilityError) {
+ throw new TRPCError({ code: 'CONFLICT', message: error.message });
+ }
+ throw error;
+ }
+ if (rerunCount > 0) {
+ await AgentEvalRunWorkflow.triggerRunBenchmark({
+ force: true,
+ runId: input.id,
+ userId: ctx.userId,
+ });
+ }
+
+ return { rerunCount, runId: input.id, success: true };
+ }),
retryRunErrors: agentEvalProcedureWrite
.input(z.object({ id: z.string() }))
.mutation(async ({ input, ctx }) => {
@@ -221,7 +338,15 @@ export const runRouter = router({
});
}
- const { retryCount } = await ctx.runService.retryErrorCases(input.id);
+ let retryCount: number;
+ try {
+ ({ retryCount } = await ctx.runService.retryErrorCases(input.id));
+ } catch (error) {
+ if (error instanceof EvalCaseCompatibilityError) {
+ throw new TRPCError({ code: 'CONFLICT', message: error.message });
+ }
+ throw error;
+ }
await AgentEvalRunWorkflow.triggerRunBenchmark({
force: true,
@@ -231,6 +356,32 @@ export const runRouter = router({
return { retryCount, runId: input.id, success: true };
}),
+ /**
+ * Grade a finished run again with the dataset's current judge setup, from
+ * the trajectories it recorded. Only the judge runs; no case is executed.
+ */
+ rejudgeRun: agentEvalProcedureWrite
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ const run = await ctx.runModel.findById(input.id);
+ if (!run) throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
+
+ if (!['completed', 'failed', 'aborted'].includes(run.status)) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Cannot re-judge: status=${run.status}`,
+ });
+ }
+
+ try {
+ return await ctx.runService.rejudgeRun(input.id);
+ } catch (error) {
+ if (error instanceof EvalCaseCompatibilityError) {
+ throw new TRPCError({ code: 'CONFLICT', message: error.message });
+ }
+ throw error;
+ }
+ }),
retryRunCase: agentEvalProcedureWrite
.input(z.object({ runId: z.string(), testCaseId: z.string() }))
.mutation(async ({ input, ctx }) => {
@@ -247,6 +398,9 @@ export const runRouter = router({
try {
await ctx.runService.retrySingleCase(input.runId, input.testCaseId);
} catch (error) {
+ if (error instanceof EvalCaseCompatibilityError) {
+ throw new TRPCError({ code: 'CONFLICT', message: error.message });
+ }
const message = error instanceof Error ? error.message : 'Cannot retry case';
if (message.startsWith('Cannot retry: case is')) {
throw new TRPCError({ code: 'CONFLICT', message });
@@ -274,11 +428,20 @@ export const runRouter = router({
input.testCaseId,
input.threadId,
);
- const result = await ctx.runService.resumeTrajectory({
- runId: input.runId,
- testCaseId: input.testCaseId,
- threadId: input.threadId,
- });
+ const result = await ctx.runService
+ .resumeTrajectory({
+ runId: input.runId,
+ testCaseId: input.testCaseId,
+ threadId: input.threadId,
+ })
+ .catch((error) => {
+ if (
+ error instanceof EvalResumeConflictError ||
+ error instanceof EvalCaseCompatibilityError
+ )
+ throw new TRPCError({ code: 'CONFLICT', message: error.message });
+ throw error;
+ });
log('resumeRunCase: result %O', result);
return result;
}),
@@ -326,7 +489,7 @@ export const runRouter = router({
getRunProgress: agentEvalProcedure
.input(z.object({ id: z.string() }))
.query(async ({ input, ctx }) => {
- let run = await ctx.runModel.findById(input.id);
+ let run = await ctx.runModel.findSummaryById(input.id);
if (!run) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
}
@@ -335,7 +498,7 @@ export const runRouter = router({
if (run.status === 'running') {
const timedOut = await ctx.runService.checkAndHandleRunTimeout(run);
if (timedOut) {
- run = (await ctx.runModel.findById(input.id))!;
+ run = (await ctx.runModel.findSummaryById(input.id))!;
}
}
@@ -356,7 +519,7 @@ export const runRouter = router({
}),
)
.query(async ({ input, ctx }) => {
- const run = await ctx.runModel.findById(input.id);
+ const run = await ctx.runModel.findSummaryById(input.id);
if (!run) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Run not found' });
}
diff --git a/apps/server/src/routers/lambda/agentEval/schemas.test.ts b/apps/server/src/routers/lambda/agentEval/schemas.test.ts
new file mode 100644
index 00000000000..5c8f758b087
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentEval/schemas.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import { evalCaseEnvironmentSchema } from './schemas';
+
+describe('evalCaseEnvironmentSchema.timezone', () => {
+ it.each(['UTC', 'America/Chicago', 'Asia/Shanghai'])(
+ 'accepts supported timezone %s',
+ (timezone) => {
+ expect(evalCaseEnvironmentSchema.parse({ timezone })).toEqual({ timezone });
+ },
+ );
+
+ it('rejects an invalid timezone before a case or shared environment can be saved', () => {
+ const result = evalCaseEnvironmentSchema.safeParse({
+ sessionDate: '2026-11-01T12:00:00Z',
+ timezone: 'Not/AZone',
+ });
+ expect(result.success).toBe(false);
+ if (!result.success) expect(result.error.issues[0].path).toEqual(['timezone']);
+ });
+});
+
+describe('evalCaseEnvironmentSchema.toolForwarding', () => {
+ it('accepts connector names with a timeout', () => {
+ expect(
+ evalCaseEnvironmentSchema.parse({
+ mock: { services: ['gmail'] },
+ toolForwarding: { twitter: { timeoutMs: 5000 }, linear: {} },
+ }),
+ ).toEqual({
+ mock: { services: ['gmail'] },
+ toolForwarding: { linear: {}, twitter: { timeoutMs: 5000 } },
+ });
+ });
+
+ it('rejects an endpoint: where calls go is the server mock, not case data', () => {
+ const result = evalCaseEnvironmentSchema.safeParse({
+ toolForwarding: { twitter: { endpoint: 'https://evil.example.com/exec' } },
+ });
+ expect(result.success).toBe(false);
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentEval/schemas.ts b/apps/server/src/routers/lambda/agentEval/schemas.ts
index 2e6008731c4..8ce36749338 100644
--- a/apps/server/src/routers/lambda/agentEval/schemas.ts
+++ b/apps/server/src/routers/lambda/agentEval/schemas.ts
@@ -1,5 +1,8 @@
+import { evalToolManifestsSchema } from '@lobechat/types';
import { z } from 'zod';
+import { evalMemoryFixtureSchema } from '@/server/services/agentEvalRun/evalMemory.schema';
+
export const rubricTypeSchema = z.enum([
'equals',
'contains',
@@ -13,6 +16,7 @@ export const rubricTypeSchema = z.enum([
'javascript',
'python',
'llm-rubric',
+ 'rule-checklist',
'factuality',
'answer-relevance',
'similar',
@@ -23,18 +27,69 @@ export const rubricTypeSchema = z.enum([
export const evalConfigSchema = z.object({ judgePrompt: z.string().optional() }).passthrough();
+export const evalCaseAgentConfigSchema = z
+ .object({
+ memory: z
+ .object({
+ effort: z.enum(['low', 'medium', 'high']).optional(),
+ enabled: z.boolean().optional(),
+ toolPermission: z.enum(['read-only', 'read-write']).optional(),
+ })
+ .strict()
+ .optional(),
+ name: z.string().trim().min(1).max(200).optional(),
+ plugins: z.array(z.string().trim().min(1)).optional(),
+ systemRole: z.string().optional(),
+ title: z.string().trim().min(1).max(200).optional(),
+ })
+ .strict();
+
+export const evalConnectorBindingSchema = z
+ .object({
+ connectorId: z.uuid(),
+ transport: z.enum(['mcp', 'lobe-bench']).optional(),
+ })
+ .strict();
+
+export const evalConnectorBindingsSchema = z.record(
+ z.string().trim().min(1).max(255),
+ evalConnectorBindingSchema,
+);
+
export const evalCaseEnvironmentSchema = z
.object({
+ agent: evalCaseAgentConfigSchema.optional(),
+ connectorBindings: evalConnectorBindingsSchema.optional(),
+ toolManifests: evalToolManifestsSchema.optional(),
envPrompt: z.string().optional(),
+ memory: evalMemoryFixtureSchema.optional(),
+ mock: z
+ .object({ services: z.array(z.string().trim().min(1)).min(1) })
+ .strict()
+ .optional(),
+ sessionDate: z
+ .string()
+ .refine((value) => !Number.isNaN(Date.parse(value)), 'sessionDate must be an ISO date')
+ .optional(),
+ timezone: z
+ .string()
+ .trim()
+ .min(1)
+ .refine((value) => {
+ try {
+ new Intl.DateTimeFormat('en-US', { timeZone: value });
+ return true;
+ } catch {
+ return false;
+ }
+ }, 'timezone must be a supported time zone')
+ .optional(),
+ // Legacy logical service requirements and timeouts. The selected connection,
+ // never case content, supplies the endpoint and credentials.
toolForwarding: z
.record(
z.string().trim().min(1),
- z
- .object({
- endpoint: z.string().url(),
- timeoutMs: z.number().int().positive().optional(),
- })
- .strict(),
+ z.object({ timeoutMs: z.number().int().positive().optional() }).strict(),
)
.optional(),
})
@@ -99,10 +154,19 @@ export const evalTestCaseMessagesSchema = z
}
});
+/**
+ * A case's own settings over its Environment. Mock connections belong to the
+ * Environment alone, so a case cannot bind its own; it only narrows the
+ * services it uses (`mock.services`).
+ */
+export const evalCaseOwnEnvironmentSchema = evalCaseEnvironmentSchema.omit({
+ connectorBindings: true,
+});
+
export const evalTestCaseContentSchema = z.object({
category: z.string().optional(),
choices: z.array(z.string()).optional(),
- environment: evalCaseEnvironmentSchema.optional(),
+ environment: evalCaseOwnEnvironmentSchema.optional(),
expected: z.string().optional(),
input: z.string(),
messages: evalTestCaseMessagesSchema.optional(),
diff --git a/apps/server/src/routers/lambda/agentEval/testCases.ts b/apps/server/src/routers/lambda/agentEval/testCases.ts
index 8c2c06743e0..3a6689004ab 100644
--- a/apps/server/src/routers/lambda/agentEval/testCases.ts
+++ b/apps/server/src/routers/lambda/agentEval/testCases.ts
@@ -1,8 +1,20 @@
+import type { EvalCaseEnvironment } from '@lobechat/types';
+import { redactEnvironmentConnections } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
+import type { AgentEvalEnvironmentModel } from '@/database/models/agentEval';
+import { AgentEvalDatasetWriteError } from '@/database/models/agentEval/datasetAccess';
import { router } from '@/libs/trpc/lambda';
+import { mergeCaseEnvironment } from '@/server/services/agentEvalRun/caseEnvironment';
+import {
+ draftCaseFromTopic,
+ TOPIC_HAS_NO_REQUEST,
+ TOPIC_NOT_FOUND,
+} from '@/server/services/agentEvalRun/caseFromTopic';
+import { createEvalRunDeps } from '@/server/services/agentEvalRun/deps';
+import { validateEvalConnectorBindings } from './connectorBindings';
import { agentEvalProcedure, agentEvalProcedureWrite } from './procedures';
import {
evalCaseEnvironmentSchema,
@@ -12,6 +24,47 @@ import {
rubricTypeSchema,
} from './schemas';
+/**
+ * Readers get each case with its shared environment merged into
+ * `content.environment` and the environment's name alongside, so the UI
+ * shows the persona, tools and clock a case actually runs with. The case's
+ * own overrides stay available as `environmentOverrides`, so an editor can
+ * change them without writing the merged result back as overrides.
+ */
+async function attachEnvironments<
+ T extends { content: { environment?: EvalCaseEnvironment }; environmentId?: string | null },
+>(
+ environmentModel: AgentEvalEnvironmentModel,
+ testCases: T[],
+): Promise<
+ Array<
+ T & {
+ environment?: { id: string; name: string } | null;
+ environmentOverrides?: EvalCaseEnvironment;
+ }
+ >
+> {
+ const ids = testCases.map((item) => item.environmentId).filter(Boolean) as string[];
+ if (ids.length === 0) return testCases;
+ const rows = await environmentModel.findByIds(ids);
+ const byId = new Map(rows.map((row) => [row.id, row]));
+ return testCases.map((item) => {
+ const shared = item.environmentId ? byId.get(item.environmentId) : undefined;
+ if (!shared) return item;
+ return {
+ ...item,
+ content: {
+ ...item.content,
+ environment: redactEnvironmentConnections(
+ mergeCaseEnvironment(shared.config, item.content.environment),
+ ),
+ },
+ environment: { id: shared.id, name: shared.name },
+ environmentOverrides: item.content.environment ?? {},
+ };
+ });
+}
+
export const testCaseRouter = router({
// ============================================
// TestCase Operations
@@ -21,6 +74,7 @@ export const testCaseRouter = router({
z.object({
datasetId: z.string(),
content: evalTestCaseContentSchema,
+ environmentId: z.string().nullish(),
evalMode: rubricTypeSchema.optional(),
evalConfig: evalConfigSchema.optional(),
metadata: z.record(z.string(), z.unknown()).optional(),
@@ -38,6 +92,9 @@ export const testCaseRouter = router({
}
return result;
} catch (error: any) {
+ if (error instanceof AgentEvalDatasetWriteError) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: error.message });
+ }
// PostgreSQL errors might be in error.cause
const pgError = error?.cause || error;
@@ -51,6 +108,33 @@ export const testCaseRouter = router({
throw error;
}
}),
+ /**
+ * Draft a case from one of the account's conversations: its last request,
+ * the earlier turns as context, the answering Agent's setup, and rules the
+ * judge model proposes. Nothing is saved; the author edits and saves it.
+ */
+ draftTestCaseFromTopic: agentEvalProcedureWrite
+ .input(
+ z.object({
+ benchmarkId: z.string().optional(),
+ draftRules: z.boolean().optional(),
+ topicId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ try {
+ return await draftCaseFromTopic(
+ createEvalRunDeps(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),
+ input.topicId,
+ { benchmarkId: input.benchmarkId, draftRules: input.draftRules },
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ if (message === TOPIC_NOT_FOUND) throw new TRPCError({ code: 'NOT_FOUND', message });
+ if (message === TOPIC_HAS_NO_REQUEST) throw new TRPCError({ code: 'BAD_REQUEST', message });
+ throw error;
+ }
+ }),
batchCreateTestCases: agentEvalProcedureWrite
.input(
z.object({
@@ -58,6 +142,10 @@ export const testCaseRouter = router({
cases: z.array(
z.object({
content: evalTestCaseContentSchema,
+ environmentId: z.string().nullish(),
+ // A copied case keeps its own rules and judge (a case copied into a dataset).
+ evalConfig: evalConfigSchema.optional(),
+ evalMode: rubricTypeSchema.optional(),
metadata: z.record(z.string(), z.unknown()).optional(),
sortOrder: z.number().optional(),
}),
@@ -73,6 +161,9 @@ export const testCaseRouter = router({
const result = await ctx.testCaseModel.batchCreate(testCases);
return { count: result.length, data: result };
} catch (error: any) {
+ if (error instanceof AgentEvalDatasetWriteError) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: error.message });
+ }
// PostgreSQL errors might be in error.cause
const pgError = error?.cause || error;
@@ -90,6 +181,7 @@ export const testCaseRouter = router({
.input(
z.object({
id: z.string(),
+ environmentId: z.string().nullish(),
content: z
.object({
input: z.string().optional(),
@@ -108,7 +200,22 @@ export const testCaseRouter = router({
)
.mutation(async ({ input, ctx }) => {
const { id, ...data } = input;
- const result = await ctx.testCaseModel.update(id, data as any);
+ let result;
+ try {
+ await validateEvalConnectorBindings(
+ ctx.evalConnectorServiceForDataset,
+ data.content?.environment?.connectorBindings,
+ data.content?.environment?.connectorBindings
+ ? (await ctx.testCaseModel.findById(id))?.datasetId
+ : undefined,
+ );
+ result = await ctx.testCaseModel.update(id, data);
+ } catch (error) {
+ if (error instanceof AgentEvalDatasetWriteError) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: error.message });
+ }
+ throw error;
+ }
if (!result) {
throw new TRPCError({
code: 'NOT_FOUND',
@@ -144,7 +251,8 @@ export const testCaseRouter = router({
if (!testCase) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Test case not found' });
}
- return testCase;
+ const [resolved] = await attachEnvironments(ctx.environmentModel, [testCase]);
+ return resolved;
}),
listTestCases: agentEvalProcedure
.input(
@@ -159,6 +267,6 @@ export const testCaseRouter = router({
ctx.testCaseModel.findByDatasetId(input.datasetId, input.limit, input.offset),
ctx.testCaseModel.countByDatasetId(input.datasetId),
]);
- return { data, total };
+ return { data: await attachEnvironments(ctx.environmentModel, data), total };
}),
});
diff --git a/apps/server/src/routers/lambda/agentEvalExternal.ts b/apps/server/src/routers/lambda/agentEvalExternal.ts
index 8300d497e20..7223eda36ba 100644
--- a/apps/server/src/routers/lambda/agentEvalExternal.ts
+++ b/apps/server/src/routers/lambda/agentEvalExternal.ts
@@ -11,6 +11,7 @@ import {
AgentEvalTestCaseModel,
} from '@/database/models/agentEval';
import { ThreadModel } from '@/database/models/thread';
+import { AgentEvalExecutionRepo } from '@/database/repositories/agentEvalExecution';
import { messages } from '@/database/schemas';
import { buildWorkspaceWhere } from '@/database/utils/workspace';
import { router } from '@/libs/trpc/lambda';
@@ -283,7 +284,11 @@ export const agentEvalExternalRouter = router({
});
}
- await ctx.runTopicModel.batchMarkAborted(input.runId);
+ await new AgentEvalExecutionRepo(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).batchMarkAborted(input.runId);
if (input.status === 'failed') {
const runTopics = await ctx.runTopicModel.findByRunId(input.runId);
diff --git a/apps/server/src/routers/lambda/composio.configuration.test.ts b/apps/server/src/routers/lambda/composio.configuration.test.ts
new file mode 100644
index 00000000000..6925c410c55
--- /dev/null
+++ b/apps/server/src/routers/lambda/composio.configuration.test.ts
@@ -0,0 +1,76 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { PluginModel } from '@/database/models/plugin';
+
+import { composioRouter } from './composio';
+
+const mocks = vi.hoisted(() => ({
+ pluginCreate: vi.fn(),
+ pluginQuery: vi.fn(),
+}));
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => ({})) }));
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn().mockImplementation(function () {
+ return { create: mocks.pluginCreate, query: mocks.pluginQuery };
+ }),
+}));
+
+// Keep the real Composio client factory and its missing-key guard. No SDK client
+// or remote request can be created without a configured key.
+vi.mock('@/config/composio', () => ({
+ getServerComposioApiKey: () => undefined,
+ getServerComposioAuthConfigId: () => undefined,
+}));
+
+const callerFor = (userId?: string, workspaceId?: string) =>
+ composioRouter.createCaller({ userId, workspaceId } as any);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('composioRouter without a configured API key', () => {
+ it.each([
+ ['personal-user', undefined],
+ ['workspace-user', 'workspace-1'],
+ ])('lists stored Composio plugins for %s in the existing scope', async (userId, workspaceId) => {
+ const composioPlugin = {
+ customParams: { composio: { connectedAccountId: 'account-1' } },
+ identifier: 'gmail',
+ };
+ mocks.pluginQuery.mockResolvedValue([
+ composioPlugin,
+ { customParams: {}, identifier: 'ordinary-plugin' },
+ { identifier: 'another-plugin' },
+ ]);
+
+ await expect(callerFor(userId, workspaceId).getComposioPlugins()).resolves.toEqual([
+ composioPlugin,
+ ]);
+ expect(PluginModel).toHaveBeenCalledWith(expect.anything(), userId, workspaceId);
+ });
+
+ it('still rejects unauthenticated plugin listing before reading the database', async () => {
+ await expect(callerFor().getComposioPlugins()).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+ expect(mocks.pluginQuery).not.toHaveBeenCalled();
+ });
+
+ it('still requires a key for remote account lookup', async () => {
+ await expect(
+ callerFor('user-1').getConnection({ connectedAccountId: 'account-1' }),
+ ).rejects.toThrow('Composio API key is not configured on server');
+ });
+
+ it('still requires a key before creating a connection or writing its plugin', async () => {
+ await expect(
+ callerFor('user-1').createConnection({
+ appSlug: 'gmail',
+ identifier: 'gmail',
+ label: 'Gmail',
+ }),
+ ).rejects.toThrow('Composio API key is not configured on server');
+ expect(mocks.pluginCreate).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/composio.ts b/apps/server/src/routers/lambda/composio.ts
index 9f6214ab16b..343f9dddd31 100644
--- a/apps/server/src/routers/lambda/composio.ts
+++ b/apps/server/src/routers/lambda/composio.ts
@@ -27,9 +27,8 @@ import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { assertConnectorMaintainable } from './_helpers/connectorManagePolicy';
-const composioProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+const composioDbProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
- const client = getComposioClient();
const wsId = ctx.workspaceId ?? undefined;
// Workspace-scoped. A Composio connection bound to a workspace agent (or a
// workspace's base tools) must land as a workspace-dimension row
@@ -44,10 +43,15 @@ const composioProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)
const connectorToolModel = new ConnectorToolModel(ctx.serverDB, ctx.userId, wsId);
return opts.next({
- ctx: { ...ctx, composioClient: client, connectorModel, connectorToolModel, pluginModel },
+ ctx: { ...ctx, connectorModel, connectorToolModel, pluginModel },
});
});
+// Stored plugin listings do not require the external Composio service to be configured.
+const composioProcedure = composioDbProcedure.use(async (opts) =>
+ opts.next({ ctx: { composioClient: getComposioClient() } }),
+);
+
// Writes: in a workspace, require at least the member role (blocks viewers).
// Personal mode passes through. The workspace connector policy is layered on
// top per-mutation via `assertComposioRowManageable` (mirrors the native
@@ -399,7 +403,7 @@ export const composioRouter = router({
return { success: true };
}),
- getComposioPlugins: composioProcedure.query(async ({ ctx }) => {
+ getComposioPlugins: composioDbProcedure.query(async ({ ctx }) => {
const allPlugins = await ctx.pluginModel.query();
return allPlugins.filter((plugin) => plugin.customParams?.composio);
}),
diff --git a/apps/server/src/routers/lambda/connector.evalEdits.test.ts b/apps/server/src/routers/lambda/connector.evalEdits.test.ts
new file mode 100644
index 00000000000..d43c9681819
--- /dev/null
+++ b/apps/server/src/routers/lambda/connector.evalEdits.test.ts
@@ -0,0 +1,90 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { EvalConnectorUpdateError } from '@/database/models/connectorEval';
+
+import { connectorRouter } from './connector';
+
+const mocks = vi.hoisted(() => ({
+ create: vi.fn(),
+ findById: vi.fn(),
+ findScopedByIdentifier: vi.fn(),
+ update: vi.fn(),
+}));
+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
+vi.mock('@/database/models/connector', () => ({
+ ConnectorModel: vi.fn(function () {
+ return mocks;
+ }),
+}));
+vi.mock('@/database/models/connectorTool', () => ({ ConnectorToolModel: vi.fn() }));
+vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },
+}));
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const { trpc } = await import('@/libs/trpc/lambda/init');
+ return {
+ requireWorkspaceRoleWhenScoped: () => trpc.middleware((opts) => opts.next()),
+ wsCompatProcedure: trpc.procedure,
+ };
+});
+vi.mock('@/libs/trpc/lambda/middleware', async () => {
+ const { trpc } = await import('@/libs/trpc/lambda/init');
+ return {
+ serverDatabase: trpc.middleware((opts) =>
+ opts.next({ ctx: { ...opts.ctx, serverDB: {} as never } }),
+ ),
+ };
+});
+
+const id = '9f1f6f30-0000-4000-8000-000000000001';
+const caller = connectorRouter.createCaller({ userId: 'creator' } as never);
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.findById.mockResolvedValue({ id, userId: 'creator' });
+ mocks.findScopedByIdentifier.mockResolvedValue(null);
+ mocks.create.mockResolvedValue({ id });
+});
+
+describe('imported evaluation connector edit boundary', () => {
+ it('does not allow a normal create request to spoof evaluation import provenance', async () => {
+ await caller.create({
+ identifier: 'ordinary',
+ name: 'Ordinary',
+ sourceType: 'custom',
+ metadata: { agentEval: { datasetId: 'spoofed' }, description: 'Keep this' },
+ });
+ expect(mocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({ metadata: { description: 'Keep this' } }),
+ );
+ });
+
+ it('reports an unsafe authentication-retaining address edit as a client error', async () => {
+ mocks.update.mockRejectedValue(
+ new EvalConnectorUpdateError(
+ 'Clear or replace authentication when changing a mock connection address',
+ ),
+ );
+ await expect(
+ caller.update({ id, patch: { mcpServerUrl: 'https://new-mock.example/mcp' } }),
+ ).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: 'Clear or replace authentication when changing a mock connection address',
+ });
+ });
+
+ it('preserves the explicit-clear versus omitted credential distinction for model normalization', async () => {
+ await caller.update({ id, patch: { metadata: { description: 'Keep authentication' } } });
+ expect(mocks.update.mock.calls[0][1]).not.toHaveProperty('credentials');
+ await caller.update({
+ id,
+ patch: { credentials: null, metadata: { customHeaders: { 'X-Mock': 'header-token' } } },
+ });
+ expect(mocks.update.mock.calls[1][1]).toMatchObject({
+ credentials: null,
+ metadata: { customHeaders: { 'X-Mock': 'header-token' } },
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.ts
index c7d0c0e3005..8733287819f 100644
--- a/apps/server/src/routers/lambda/connector.ts
+++ b/apps/server/src/routers/lambda/connector.ts
@@ -11,6 +11,10 @@ import {
} from '@/business/server/trpc-middlewares/workspaceAuth';
import { AgentModel } from '@/database/models/agent';
import { ConnectorModel } from '@/database/models/connector';
+import {
+ EvalConnectorUpdateError,
+ withoutEvalConnectorMarker,
+} from '@/database/models/connectorEval';
import { ConnectorToolModel } from '@/database/models/connectorTool';
import { PluginModel } from '@/database/models/plugin';
import { WorkspaceModel } from '@/database/models/workspace';
@@ -374,7 +378,8 @@ export const connectorRouter = router({
// (written by the OAuth connect path), and trusting it here would let a
// member spoof connector attribution. No existing row on create β†’ the
// field is simply removed.
- metadata: withTrustedLinkedByUserId(input.metadata, undefined) ?? null,
+ metadata:
+ withoutEvalConnectorMarker(withTrustedLinkedByUserId(input.metadata, undefined)) ?? null,
name: input.name,
oidcConfig: input.oidcConfig ?? null,
};
@@ -715,19 +720,25 @@ export const connectorRouter = router({
// silently clear) the connector's authorizer. Untouched when the patch
// omits metadata.
const metadata = withTrustedLinkedByUserId(patch.metadata, target.metadata);
- await ctx.connectorModel.update(input.id, {
- ...patch,
- ...(patch.metadata === undefined ? {} : { metadata }),
- // undefined β†’ leave untouched; null β†’ clear; object β†’ encrypt the JSON string.
- // When credentials are cleared, also drop the cached expiry timestamp so
- // token-refresh logic doesn't act on a stale value for the new server.
- ...(credentials === undefined
- ? {}
- : {
- credentials: credentials ? JSON.stringify(credentials) : null,
- ...(credentials === null ? { tokenExpiresAt: null } : {}),
- }),
- } as any);
+ try {
+ await ctx.connectorModel.update(input.id, {
+ ...patch,
+ ...(patch.metadata === undefined ? {} : { metadata }),
+ // undefined β†’ leave untouched; null β†’ clear; object β†’ encrypt the JSON string.
+ // When credentials are cleared, also drop the cached expiry timestamp so
+ // token-refresh logic doesn't act on a stale value for the new server.
+ ...(credentials === undefined
+ ? {}
+ : {
+ credentials: credentials ? JSON.stringify(credentials) : null,
+ ...(credentials === null ? { tokenExpiresAt: null } : {}),
+ }),
+ } as any);
+ } catch (error) {
+ if (error instanceof EvalConnectorUpdateError)
+ throw new TRPCError({ code: 'BAD_REQUEST', message: error.message });
+ throw error;
+ }
}),
delete: connectorWriteProcedure
diff --git a/apps/server/src/routers/lambda/evalRunConfig.schema.ts b/apps/server/src/routers/lambda/evalRunConfig.schema.ts
index c8bb923bd8f..a53c824b866 100644
--- a/apps/server/src/routers/lambda/evalRunConfig.schema.ts
+++ b/apps/server/src/routers/lambda/evalRunConfig.schema.ts
@@ -1,3 +1,4 @@
+import { AgentChatConfigSchema } from '@lobechat/types';
import { z } from 'zod';
/**
@@ -55,18 +56,91 @@ export const evalCaseSelectionSchema = z
return val;
});
+/**
+ * Contender settings of a model-only run; applied to every case's hidden Agent.
+ * The model settings the chat model-params panel offers (reasoning switch and
+ * effort, thinking level and budget, verbosity …), validated as the Agent
+ * chatConfig validates them.
+ */
+export const evalRunChatConfigSchema = AgentChatConfigSchema.pick({
+ codexMaxReasoningEffort: true,
+ deepseekV4GAReasoningEffort: true,
+ deepseekV4ReasoningEffort: true,
+ disableContextCaching: true,
+ effort: true,
+ enableAdaptiveThinking: true,
+ enableReasoning: true,
+ glm5_2ReasoningEffort: true,
+ glm5_3ReasoningEffort: true,
+ gpt5_1ReasoningEffort: true,
+ gpt5_2ProReasoningEffort: true,
+ gpt5_2ReasoningEffort: true,
+ gpt5_6ReasoningEffort: true,
+ gpt5ReasoningEffort: true,
+ gpt6ReasoningEffort: true,
+ grok4_20ReasoningEffort: true,
+ grok4_3ReasoningEffort: true,
+ grok4_5ReasoningEffort: true,
+ grok4_6ReasoningEffort: true,
+ grok4_7ReasoningEffort: true,
+ hy3ReasoningEffort: true,
+ kimiK3ReasoningEffort: true,
+ opus47Effort: true,
+ preserveThinking: true,
+ qwen38ReasoningEffort: true,
+ reasoningBudgetToken: true,
+ reasoningBudgetToken32k: true,
+ reasoningBudgetToken80k: true,
+ reasoningEffort: true,
+ reasoningMode: true,
+ ring2_6ReasoningEffort: true,
+ step3_5ReasoningEffort: true,
+ textVerbosity: true,
+ thinking: true,
+ thinkingBudget: true,
+ thinkingLevel: true,
+ thinkingLevel2: true,
+ thinkingLevel3: true,
+ thinkingLevel4: true,
+}).strict();
+
+export const evalRunModelParamsSchema = z
+ .object({
+ frequency_penalty: z.number().min(-2).max(2).optional(),
+ presence_penalty: z.number().min(-2).max(2).optional(),
+ temperature: z.number().min(0).max(2).optional(),
+ top_p: z.number().min(0).max(1).optional(),
+ })
+ .strict();
+
/**
* User-facing config for creating an eval run. Shared by the internal
* (agentEval) and external (agentEvalExternal) routers.
*/
-export const evalRunInputConfigSchema = z.object({
- caseSelection: evalCaseSelectionSchema.optional(),
- k: z.number().min(1).max(10).optional(),
- maxConcurrency: z.number().min(1).max(20).optional(),
- maxSteps: z.number().min(1).max(1000).optional(),
- timeout: z
- .number()
- .min(60_000)
- .max(6 * 3_600_000)
- .optional(),
-});
+export const evalRunInputConfigSchema = z
+ .object({
+ caseSelection: evalCaseSelectionSchema.optional(),
+ chatConfig: evalRunChatConfigSchema.optional(),
+ /** The judge of this run; absent, the case, case set or benchmark judge applies. */
+ judgeModel: z.string().trim().min(1).optional(),
+ judgeProvider: z.string().trim().min(1).optional(),
+ k: z.number().min(1).max(10).optional(),
+ maxConcurrency: z.number().min(1).max(20).optional(),
+ maxSteps: z.number().min(1).max(1000).optional(),
+ model: z.string().trim().min(1).optional(),
+ params: evalRunModelParamsSchema.optional(),
+ provider: z.string().trim().min(1).optional(),
+ timeout: z
+ .number()
+ .min(60_000)
+ .max(6 * 3_600_000)
+ .optional(),
+ })
+ .refine((config) => Boolean(config.model) === Boolean(config.provider), {
+ message: 'model and provider must be set together',
+ path: ['provider'],
+ })
+ .refine((config) => Boolean(config.judgeModel) === Boolean(config.judgeProvider), {
+ message: 'judgeModel and judgeProvider must be set together',
+ path: ['judgeProvider'],
+ });
diff --git a/apps/server/src/services/agentEvalConnector/index.test.ts b/apps/server/src/services/agentEvalConnector/index.test.ts
new file mode 100644
index 00000000000..2397441835f
--- /dev/null
+++ b/apps/server/src/services/agentEvalConnector/index.test.ts
@@ -0,0 +1,597 @@
+import type { EvalConnectorBindings } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '@/database/core/getTestDB';
+import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import {
+ agentEvalDatasets,
+ agentEvalEnvironments,
+ agentEvalTestCases,
+ userConnectors,
+ users,
+ workspaces,
+} from '@/database/schemas';
+import { syncConnectorToolsById } from '@/server/services/connector/sync';
+
+import {
+ AgentEvalConnectorService,
+ EvalConnectorBindingError,
+ getLobeBenchForwardingEndpoint,
+} from './index';
+
+const mocked = vi.hoisted(() => ({
+ callTool: vi.fn(),
+ fetch: vi.fn(),
+ listRawTools: vi.fn(),
+ gateKeeper: {
+ decrypt: vi.fn(async (ciphertext: string) => ({
+ plaintext: ciphertext.replace(/^sealed:/, ''),
+ })),
+ encrypt: vi.fn(async (plaintext: string) => `sealed:${plaintext}`),
+ },
+}));
+vi.mock('@/server/services/mcp', () => ({ mcpService: mocked }));
+vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mocked.fetch }));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: async () => mocked.gateKeeper },
+}));
+
+const db = await getTestDB();
+const userId = 'eval-connector-user';
+const datasetId = 'eval-connector-dataset';
+const model = () =>
+ ConnectorModel.forEvaluation(db, userId, datasetId, undefined, mocked.gateKeeper);
+const service = () => new AgentEvalConnectorService(db, userId, datasetId);
+const originals = (bindings: EvalConnectorBindings) =>
+ Object.fromEntries(
+ Object.keys(bindings).map((identifier) => [
+ identifier,
+ {
+ identifier,
+ type: 'mcp' as const,
+ meta: { title: identifier, description: 'Original service' },
+ api: [{ name: 'read', description: 'Read a fixture', parameters: { type: 'object' } }],
+ },
+ ]),
+ );
+const check = (bindings: EvalConnectorBindings) =>
+ service().checkBindings(bindings, originals(bindings));
+const rawTools = [{ description: 'Read a fixture', inputSchema: { type: 'object' }, name: 'read' }];
+const create = async (token = 'alpha-secret', url = 'https://mock.test/mcp/dataset/notion') =>
+ model().create({
+ credentials: JSON.stringify({ token, type: 'bearer' }),
+ identifier: `imported-${crypto.randomUUID()}`,
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: url,
+ metadata: { agentEval: { datasetId } },
+ name: 'Private fixture',
+ sourceType: 'custom',
+ status: 'disconnected',
+ });
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ await db.delete(users);
+ await db.insert(users).values([{ id: userId }, { id: 'other-eval-user' }]);
+ await db.insert(agentEvalDatasets).values([
+ { id: datasetId, identifier: datasetId, name: 'Dataset', userId },
+ { id: 'other-dataset', identifier: 'other-dataset', name: 'Other Dataset', userId },
+ {
+ id: 'foreign-dataset',
+ identifier: 'foreign-dataset',
+ name: 'Foreign Dataset',
+ userId: 'other-eval-user',
+ },
+ ]);
+ mocked.listRawTools.mockResolvedValue(rawTools);
+ mocked.callTool.mockResolvedValue({ content: 'fixture-result', success: true });
+ mocked.fetch.mockImplementation(async () => new Response('', { status: 404 }));
+});
+afterEach(async () => {
+ vi.unstubAllEnvs();
+ await db.delete(users);
+});
+
+describe('evaluation connector binding', () => {
+ it('lists and resolves only this Dataset connections, excluding ordinary and same-owner other Dataset rows', async () => {
+ const own = await create();
+ const ordinary = await new ConnectorModel(db, userId).create({
+ identifier: 'notion',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://real.test/mcp',
+ name: 'Notion',
+ sourceType: 'custom',
+ status: 'connected',
+ });
+ const other = await ConnectorModel.forEvaluation(db, userId, 'other-dataset').create({
+ identifier: 'other-mock',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mock.test/mcp/other/notion',
+ metadata: { agentEval: { datasetId: 'other-dataset' } },
+ name: 'Notion',
+ sourceType: 'custom',
+ status: 'connected',
+ });
+ expect((await service().listAvailableConnectors()).map(({ id }) => id)).toEqual([own.id]);
+ for (const connector of [ordinary, other]) {
+ const bindings = { notion: { connectorId: connector.id } };
+ await expect(service().validateBindings(bindings)).rejects.toThrow('unavailable');
+ await expect(service().checkBindings(bindings)).rejects.toThrow('unavailable');
+ }
+ expect(mocked.listRawTools).not.toHaveBeenCalled();
+ expect(mocked.callTool).not.toHaveBeenCalled();
+ });
+
+ it('fails closed on missing, mixed, or wrong frozen Dataset scopes before execution', async () => {
+ const own = await create();
+ const { snapshots } = await check({ notion: { connectorId: own.id } });
+ const legacy = { notion: { ...snapshots.notion, datasetId: undefined } };
+ const other = { notion: { ...snapshots.notion, datasetId: 'other-dataset' } };
+ const mixed = { ...snapshots, other: other.notion };
+ for (const snapshot of [legacy, other, mixed]) {
+ await expect(
+ service().execute('notion', snapshot, { apiName: 'read', args: '{}' }),
+ ).rejects.toBeInstanceOf(EvalConnectorBindingError);
+ }
+ expect(mocked.callTool).not.toHaveBeenCalled();
+ });
+
+ it('does not expose or execute a foreign Dataset even for a matching connector marker', async () => {
+ const foreign = await ConnectorModel.forEvaluation(
+ db,
+ 'other-eval-user',
+ 'foreign-dataset',
+ ).create({
+ identifier: 'foreign-mock',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mock.test/mcp/foreign/notion',
+ metadata: { agentEval: { datasetId: 'foreign-dataset' } },
+ name: 'Notion',
+ sourceType: 'custom',
+ status: 'connected',
+ });
+ const unavailableService = new AgentEvalConnectorService(db, userId, 'foreign-dataset');
+ expect(await unavailableService.listAvailableConnectors()).toEqual([]);
+ await expect(
+ unavailableService.validateBindings({ notion: { connectorId: foreign.id } }),
+ ).rejects.toThrow('unavailable');
+ const own = await create();
+ await db
+ .update(userConnectors)
+ .set({ metadata: { agentEval: { datasetId: 'foreign-dataset' } } })
+ .where(eq(userConnectors.id, own.id));
+ // Matching connection owner + marker cannot substitute for Dataset access.
+ await expect(
+ unavailableService.validateBindings({ notion: { connectorId: own.id } }),
+ ).rejects.toThrow('unavailable');
+ expect(await unavailableService.listAvailableConnectors()).toEqual([]);
+ expect(mocked.listRawTools).not.toHaveBeenCalled();
+ });
+
+ it('rejects legacy snapshots instead of deriving a new model contract from the mock', async () => {
+ const connector = await create();
+ const bindings = { notion: { connectorId: connector.id } };
+ const { snapshots } = await service().checkBindings(bindings);
+ await expect(service().resolveBindings(bindings, snapshots)).rejects.toThrow(
+ 'no original tool contract',
+ );
+ expect(mocked.callTool).not.toHaveBeenCalled();
+ });
+
+ it('uses the frozen original tool surface, never the connection display name', async () => {
+ const connector = await create();
+ await model().update(connector.id, { name: 'LobeBench Mock Β· private-name' });
+ const bindings = { notion: { connectorId: connector.id } };
+ const original = {
+ identifier: 'notion',
+ type: 'mcp' as const,
+ meta: { title: 'Notion', description: 'Search and edit your workspace.' },
+ api: [{ name: 'read', description: 'Read a page.', parameters: { type: 'object' } }],
+ systemRole: 'Use the original workspace tools.',
+ };
+ const { snapshots, manifests } = await service().checkBindings(bindings, { notion: original });
+ expect(manifests).toEqual([original]);
+ expect(snapshots.notion.manifest).toEqual(original);
+ expect(JSON.stringify({ manifests, snapshots })).not.toContain('LobeBench Mock');
+ });
+
+ it('bounds batch preflights to four connections and serializes transports of the same connection', async () => {
+ const connections = [];
+ for (let i = 0; i < 8; i++) {
+ connections.push(await create(`token-${i}`, `https://mock.test/mcp/dataset/service-${i}`));
+ }
+ const groups: EvalConnectorBindings[] = connections.map((connector, i) => ({
+ [`alias-${i}`]: { connectorId: connector.id },
+ }));
+ groups.push({
+ sameMcp: { connectorId: connections[0].id, transport: 'mcp' },
+ bench: { connectorId: connections[0].id, transport: 'lobe-bench' },
+ });
+ let active = 0;
+ let maximum = 0;
+ let sameConnectionMaximum = 0;
+ const activeByUrl = new Map<string, number>();
+ const release: Array<() => void> = [];
+ let released = false;
+ mocked.listRawTools.mockImplementation(async ({ url }: { url: string }) => {
+ active++;
+ maximum = Math.max(maximum, active);
+ activeByUrl.set(url, (activeByUrl.get(url) ?? 0) + 1);
+ sameConnectionMaximum = Math.max(sameConnectionMaximum, activeByUrl.get(url)!);
+ if (!released) await new Promise<void>((resolve) => release.push(resolve));
+ active--;
+ activeByUrl.set(url, activeByUrl.get(url)! - 1);
+ return rawTools;
+ });
+ const current = service();
+ const checking = current.checkBindingGroups(groups);
+ try {
+ await vi.waitFor(() => expect(mocked.listRawTools).toHaveBeenCalledTimes(4));
+ } finally {
+ released = true;
+ release.forEach((resolve) => resolve());
+ }
+ await checking;
+ expect(maximum).toBe(4);
+ expect(sameConnectionMaximum).toBe(1);
+ expect(mocked.listRawTools).toHaveBeenCalledTimes(9);
+ expect(mocked.fetch).toHaveBeenCalledOnce();
+ const { snapshots } = await current.resolveBindings(groups.at(-1)!);
+ expect(snapshots.sameMcp.transport).toBe('mcp');
+ expect(snapshots.bench.transport).toBe('lobe-bench');
+ expect(snapshots.sameMcp.fingerprint).not.toBe(snapshots.bench.fingerprint);
+
+ mocked.fetch.mockResolvedValueOnce(new Response('', { status: 401 }));
+ await expect(current.checkBindingGroups([groups.at(-1)!])).rejects.toThrow('HTTP 401');
+ expect(mocked.listRawTools).toHaveBeenCalledTimes(11);
+ });
+
+ it('validates every alias before deduplicating a batch connection', async () => {
+ const connector = await create();
+ await expect(
+ service().checkBindingGroups([
+ { notion: { connectorId: connector.id } },
+ { 'lobe-user-memory': { connectorId: connector.id } },
+ ]),
+ ).rejects.toThrow('cannot be bound');
+ expect(mocked.listRawTools).not.toHaveBeenCalled();
+ });
+
+ it('syncs an imported connection and freezes only its UUID and tool fingerprint', async () => {
+ const connector = await create();
+ const bindings = { notion: { connectorId: connector.id } };
+ const { snapshots, manifests } = await check(bindings);
+ expect(manifests[0].identifier).toBe('notion');
+ expect(manifests[0].api.map((tool) => tool.name)).toEqual(['read']);
+ expect(snapshots.notion).toEqual({
+ connectorId: connector.id,
+ datasetId,
+ fingerprint: expect.any(String),
+ transport: 'mcp',
+ manifest: originals(bindings).notion,
+ });
+ expect(JSON.stringify({ snapshots, manifests })).not.toMatch(
+ /alpha-secret|https:|mcpParams|Authorization/,
+ );
+ expect(
+ await service().execute('notion', snapshots, { apiName: 'read', args: '{}' }),
+ ).toMatchObject({ content: 'fixture-result', success: true });
+ expect(mocked.callTool.mock.calls[0][0].clientParams.auth.token).toBe('alpha-secret');
+ });
+
+ it('keeps two bindings to the same URL on their own credentials and permits token rotation', async () => {
+ const first = await create('first-secret');
+ const second = await create('second-secret');
+ const bindings = { first: { connectorId: first.id }, second: { connectorId: second.id } };
+ const { snapshots } = await check(bindings);
+ await service().execute('first', snapshots, { apiName: 'read', args: '{}' });
+ await service().execute('second', snapshots, { apiName: 'read', args: '{}' });
+ await model().update(first.id, {
+ credentials: JSON.stringify({ token: 'rotated-secret', type: 'bearer' }),
+ });
+ await service().execute('first', snapshots, { apiName: 'read', args: '{}' });
+ expect(mocked.callTool.mock.calls.map(([call]) => call.clientParams.auth.token)).toEqual([
+ 'first-secret',
+ 'second-secret',
+ 'rotated-secret',
+ ]);
+ });
+
+ it('rejects foreign, workspace, mounted, disabled, and non-HTTP connections', async () => {
+ const own = await create();
+ const other = await new ConnectorModel(db, 'other-eval-user').create({
+ identifier: 'foreign',
+ name: 'Foreign',
+ sourceType: 'custom',
+ status: 'connected',
+ });
+ await db
+ .insert(workspaces)
+ .values({ id: 'eval-workspace', name: 'WS', primaryOwnerId: userId, slug: 'eval-workspace' });
+ const workspace = await new ConnectorModel(db, userId, 'eval-workspace').create({
+ identifier: 'scoped',
+ name: 'Workspace',
+ sourceType: 'custom',
+ status: 'connected',
+ });
+ for (const id of [other.id, workspace.id, crypto.randomUUID()]) {
+ await expect(service().validateBindings({ notion: { connectorId: id } })).rejects.toThrow(
+ 'unavailable',
+ );
+ }
+ for (const patch of [
+ { metadata: { agentEval: { datasetId }, mountedByAgentId: 'another-agent' } },
+ { metadata: { agentEval: { datasetId } }, isEnabled: false },
+ { isEnabled: true, mcpConnectionType: 'stdio' as const },
+ ]) {
+ // Legacy rows can predate the model's stronger write restrictions.
+ await db.update(userConnectors).set(patch).where(eq(userConnectors.id, own.id));
+ await expect(service().validateBindings({ notion: { connectorId: own.id } })).rejects.toThrow(
+ 'unavailable',
+ );
+ }
+ expect(mocked.callTool).not.toHaveBeenCalled();
+ });
+
+ it('blocks target and tool-permission drift instead of silently following a changed connection', async () => {
+ const connector = await create();
+ const bindings = { notion: { connectorId: connector.id } };
+ const { snapshots } = await check(bindings);
+ await model().update(connector.id, {
+ credentials: null,
+ mcpServerUrl: 'https://other.test/mcp/dataset/notion',
+ });
+ await expect(
+ service().execute('notion', snapshots, { apiName: 'read', args: '{}' }),
+ ).rejects.toThrow('changed');
+ await model().update(connector.id, { mcpServerUrl: 'https://mock.test/mcp/dataset/notion' });
+ const tools = ConnectorToolModel.forEvaluation(db, userId, datasetId);
+ const [tool] = await tools.queryByConnector(connector.id);
+ await tools.updatePermission(tool.id, 'needs_approval');
+ await expect(
+ service().execute('notion', snapshots, { apiName: 'read', args: '{}' }),
+ ).rejects.toThrow('changed');
+ await expect(service().resolveBindings(bindings)).rejects.toThrow('automatically permitted');
+ expect(mocked.callTool).not.toHaveBeenCalled();
+ });
+
+ it.each(['disabled', 'needs_approval'] as const)(
+ 'preserves %s permission when an upstream tool disappears and returns',
+ async (permission) => {
+ const connector = await create();
+ const bindings = { notion: { connectorId: connector.id } };
+ await check(bindings);
+ const tools = ConnectorToolModel.forEvaluation(db, userId, datasetId);
+ const [tool] = await tools.queryByConnector(connector.id);
+ await tools.updatePermission(tool.id, permission);
+ await expect(check(bindings)).rejects.toThrow('automatically permitted');
+ expect((await tools.queryByConnector(connector.id))[0].permission).toBe(permission);
+ mocked.listRawTools.mockResolvedValue([]);
+ await expect(check(bindings)).rejects.toThrow('automatically permitted');
+ expect((await tools.queryByConnector(connector.id))[0].permission).toBe(permission);
+ mocked.listRawTools.mockResolvedValue(rawTools);
+ await expect(check(bindings)).rejects.toThrow('automatically permitted');
+ expect((await tools.queryByConnector(connector.id))[0].permission).toBe(permission);
+ },
+ );
+
+ it('prunes missing auto tools only on explicit evaluation sync', async () => {
+ const connector = await create();
+ const bindings = { notion: { connectorId: connector.id } };
+ await check(bindings);
+ const tools = ConnectorToolModel.forEvaluation(db, userId, datasetId);
+ mocked.listRawTools.mockResolvedValue([]);
+ await syncConnectorToolsById(connector.id, {
+ connectorModel: model(),
+ connectorToolModel: tools,
+ });
+ expect(await tools.queryByConnector(connector.id)).toHaveLength(1);
+ await expect(check(bindings)).rejects.toThrow('automatically permitted');
+ expect(await tools.queryByConnector(connector.id)).toEqual([]);
+ });
+
+ it('uses only the selected LobeBench connection token and same-origin derived route', async () => {
+ vi.stubEnv('EVAL_TOOL_FORWARDING_TOKEN', 'global-secret-must-not-be-used');
+ const connector = await create(
+ 'connection-secret',
+ 'https://mock.test/prefix/mcp/dataset/notion',
+ );
+ const { snapshots } = await check({
+ logicalAlias: { connectorId: connector.id, transport: 'lobe-bench' },
+ });
+ mocked.fetch.mockResolvedValueOnce(
+ Response.json({ data: { content: 'ok', success: true }, success: true }),
+ );
+ const result = await service().execute('logicalAlias', snapshots, {
+ apiName: 'read',
+ args: '{}',
+ attemptId: 'attempt',
+ caseId: 'case',
+ });
+ expect(result).toEqual({ content: 'ok', success: true });
+ const [url, options] = mocked.fetch.mock.calls.at(-1)!;
+ expect(url).toBe('https://mock.test/prefix/tool-exec/dataset/notion/exec');
+ expect(options.headers.get('Authorization')).toBe('Bearer connection-secret');
+ expect(options.redirect).toBe('manual');
+ expect(JSON.parse(options.body)).toMatchObject({
+ data: { identifier: 'notion' },
+ metadata: { attemptId: 'attempt', caseId: 'case' },
+ });
+ expect(JSON.stringify(mocked.fetch.mock.calls)).not.toContain('global-secret');
+ });
+
+ it.each([401, 302])(
+ 'fails preflight on protected endpoint HTTP %i without following redirects',
+ async (status) => {
+ const connector = await create();
+ mocked.fetch.mockResolvedValue(
+ new Response('', { headers: { Location: 'https://other.test/steal' }, status }),
+ );
+ await expect(
+ check({ notion: { connectorId: connector.id, transport: 'lobe-bench' } }),
+ ).rejects.toThrow(`HTTP ${status}`);
+ expect(mocked.fetch).toHaveBeenCalledOnce();
+ expect(mocked.fetch.mock.calls[0][1].redirect).toBe('manual');
+ expect(mocked.callTool).not.toHaveBeenCalled();
+ },
+ );
+
+ it('redacts unexpected provider errors during preflight', async () => {
+ const connector = await create();
+ mocked.listRawTools.mockRejectedValue(
+ new Error('upstream printed alpha-secret and its private URL'),
+ );
+ await expect(check({ notion: { connectorId: connector.id } })).rejects.toThrow(
+ 'Could not verify',
+ );
+ await expect(check({ notion: { connectorId: connector.id } })).rejects.not.toThrow(
+ 'alpha-secret',
+ );
+ });
+
+ it.each(['TimeoutError', 'AbortError'])(
+ 'identifies the failing binding without exposing the upstream %s message',
+ async (name) => {
+ const connector = await create();
+ mocked.listRawTools.mockRejectedValue(
+ Object.assign(new Error('alpha-secret at https://private.test/mcp'), { name }),
+ );
+ const failure = await service()
+ .checkBindings({ notion: { connectorId: connector.id } })
+ .catch((error: unknown) => error);
+ expect(failure).toBeInstanceOf(EvalConnectorBindingError);
+ expect((failure as Error).message).toContain('"notion"');
+ expect((failure as Error).message).toContain(connector.id);
+ expect((failure as Error).message).toMatch(/timed out|interrupted/);
+ expect((failure as Error).message).not.toMatch(/alpha-secret|https:|private\.test/);
+ },
+ );
+
+ it('identifies a shared connection when discovery leaves no permitted tools', async () => {
+ const connector = await create();
+ mocked.listRawTools.mockResolvedValue([]);
+ const failure = await service()
+ .checkBindingGroups([
+ { firstAlias: { connectorId: connector.id } },
+ { secondAlias: { connectorId: connector.id } },
+ ])
+ .catch((error: unknown) => error);
+ expect(failure).toBeInstanceOf(EvalConnectorBindingError);
+ expect((failure as Error).message).toContain(connector.id);
+ expect((failure as Error).message).toContain('alias "firstAlias"');
+ expect((failure as Error).message).toContain('no automatically permitted tools');
+ expect((failure as Error).message).not.toMatch(/alpha-secret|https:|mock\.test/);
+ expect(mocked.listRawTools).toHaveBeenCalledOnce();
+ });
+});
+
+describe('LobeBench route derivation', () => {
+ it.each([
+ 'https://mock.test/exec',
+ 'https://user:[email protected]/mcp/ds/service',
+ 'https://mock.test/mcp/ds/service?token=secret',
+ 'file:///mcp/ds/service',
+ ])('rejects ambiguous forwarding target %s', (url) => {
+ expect(() => getLobeBenchForwardingEndpoint(url)).toThrow();
+ });
+});
+
+describe('connections stored in an Environment', () => {
+ const environmentId = '00000000-0000-4000-8000-0000000000e1';
+ const connectorId = `env:${environmentId}:gmail`;
+ const contract = originals({ gmail: { connectorId } });
+ const binding = { gmail: { connectorId, transport: 'lobe-bench' as const } };
+
+ const environmentConfig = async () =>
+ (await db.select().from(agentEvalEnvironments))[0].config as Record<string, unknown>;
+
+ beforeEach(async () => {
+ await db.insert(agentEvalEnvironments).values({
+ config: {
+ connections: {
+ gmail: {
+ credentials: 'sealed:{"token":"stored-secret","type":"bearer"}',
+ name: 'Gmail mock',
+ url: 'https://mock.test/mcp/dataset/gmail',
+ },
+ },
+ connectorBindings: binding,
+ mock: { services: ['gmail'] },
+ toolManifests: contract,
+ },
+ id: environmentId,
+ name: 'Shared world',
+ userId,
+ } as never);
+ await db
+ .insert(agentEvalTestCases)
+ .values({ content: { input: 'Read my mail' }, datasetId, environmentId, userId });
+ });
+
+ it('resolves from the frozen contract without a connector row or tool discovery', async () => {
+ const { manifests, snapshots } = await service().resolveBindings(binding, undefined, contract);
+ expect(manifests.map((manifest) => manifest.identifier)).toEqual(['gmail']);
+ expect(snapshots.gmail).toMatchObject({ connectorId, datasetId, transport: 'lobe-bench' });
+ expect(JSON.stringify(snapshots)).not.toContain('stored-secret');
+ expect(mocked.listRawTools).not.toHaveBeenCalled();
+ expect(await db.select().from(userConnectors)).toHaveLength(0);
+ });
+
+ it('checks a stored connection without a separately supplied contract', async () => {
+ await service().checkBindingGroups([binding]);
+ const { manifests } = await service().checkBindings(binding);
+ expect(manifests.map((manifest) => manifest.identifier)).toEqual(['gmail']);
+ });
+
+ it("checks a stored connection against the case's own contract when the Environment has none", async () => {
+ // Hard 50: two contract variants of one service live in the cases, not in the shared Environment.
+ await db
+ .update(agentEvalEnvironments)
+ .set({ config: { ...(await environmentConfig()), toolManifests: {} } } as never);
+ await expect(service().checkBindingGroups([binding])).rejects.toThrow(
+ 'no original tool contract',
+ );
+ await service().checkBindingGroups([binding], [contract]);
+ });
+
+ it('authenticates the stored connection with its decrypted credentials', async () => {
+ await service().checkBindings(binding, contract);
+ const [url, init] = mocked.fetch.mock.calls[0];
+ expect(String(url)).toMatch(/^https:\/\/mock\.test\/sessions\/eval-connection-check-[\w-]+$/);
+ expect(new Headers(init.headers).get('Authorization')).toBe('Bearer stored-secret');
+ });
+
+ it('forwards a tool call to the mock for this case attempt', async () => {
+ const { snapshots } = await service().resolveBindings(binding, undefined, contract);
+ mocked.fetch.mockResolvedValueOnce(
+ Response.json({ data: { content: 'inbox', success: true }, success: true }),
+ );
+ const result = await service().execute('gmail', snapshots, {
+ apiName: 'read',
+ args: '{}',
+ attemptId: 'attempt-1',
+ caseId: 'case-1',
+ });
+ expect(result).toEqual({ content: 'inbox', success: true });
+ const [url, init] = mocked.fetch.mock.calls.at(-1)!;
+ expect(url).toBe('https://mock.test/tool-exec/dataset/gmail/exec');
+ expect(new Headers(init.headers).get('Authorization')).toBe('Bearer stored-secret');
+ expect(JSON.parse(init.body)).toMatchObject({
+ data: { apiName: 'read', identifier: 'gmail' },
+ metadata: { attemptId: 'attempt-1', caseId: 'case-1' },
+ });
+ });
+
+ it('is unavailable to a Dataset whose cases do not use the Environment', async () => {
+ const other = new AgentEvalConnectorService(db, userId, 'other-dataset');
+ await expect(other.resolveBindings(binding, undefined, contract)).rejects.toBeInstanceOf(
+ EvalConnectorBindingError,
+ );
+ });
+});
diff --git a/apps/server/src/services/agentEvalConnector/index.ts b/apps/server/src/services/agentEvalConnector/index.ts
new file mode 100644
index 00000000000..288220715a3
--- /dev/null
+++ b/apps/server/src/services/agentEvalConnector/index.ts
@@ -0,0 +1,597 @@
+import { createHash } from 'node:crypto';
+
+import type { LobeChatDatabase } from '@lobechat/database';
+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
+import type {
+ EvalConnectorBindings,
+ EvalConnectorSnapshots,
+ EvalToolManifests,
+ ToolManifest,
+} from '@lobechat/types';
+import { evalToolManifestSchema, parseEnvironmentConnectionId } from '@lobechat/types';
+import { isRecord } from '@lobechat/utils/object';
+import debug from 'debug';
+import pMap from 'p-map';
+
+import { ConnectorModel, type PublicConnectorRecord } from '@/database/models/connector';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import {
+ AgentEvalEnvironmentConnectionRepo,
+ type StoredEnvironmentConnection,
+} from '@/database/repositories/agentEvalEnvironmentConnection';
+import type { ConnectorCredentials } from '@/database/schemas';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { EVAL_INFRASTRUCTURE_TOOLS } from '@/server/services/agentEvalRun/constants';
+import {
+ buildConnectorMcpParams,
+ buildHttpAuthFromCredentials,
+ syncConnectorToolsById,
+} from '@/server/services/connector/sync';
+import { ensureFreshConnectorToken } from '@/server/services/connector/tokens';
+import { mcpService } from '@/server/services/mcp';
+
+const log = debug('lobe-server:agent-eval-connector');
+
+export class EvalConnectorBindingError extends Error {
+ readonly code = 'BAD_REQUEST' as const;
+}
+
+const unavailable = () =>
+ new EvalConnectorBindingError(
+ 'The selected mock connection is unavailable. Choose an enabled HTTP connection in this Dataset that is not assigned to an Agent.',
+ );
+
+/** Persisted runs must name one Dataset before any connection can be resolved. */
+export const getEvalConnectorDatasetId = (snapshots: EvalConnectorSnapshots): string => {
+ const bindings = Object.values(snapshots);
+ const datasetId = bindings[0]?.datasetId;
+ if (!datasetId || bindings.some((binding) => binding.datasetId !== datasetId)) {
+ throw new EvalConnectorBindingError(
+ 'This run has no consistent frozen Dataset connection scope. Create a new experiment.',
+ );
+ }
+ return datasetId;
+};
+
+const bindingLabel = (identifier: string, connectorId: string) => {
+ const id = /^[\w-]{1,128}$/.test(connectorId) ? connectorId : 'unavailable';
+ const alias = /^[\w.-]{1,128}$/.test(identifier) ? ` (alias "${identifier}")` : '';
+ return `Mock connection "${id}"${alias}`;
+};
+
+const isEligible = (connector: PublicConnectorRecord | null): connector is PublicConnectorRecord =>
+ !!connector &&
+ connector.isEnabled &&
+ connector.mcpConnectionType === 'http' &&
+ !!connector.mcpServerUrl &&
+ !connector.agentId &&
+ !connector.mountedByAgentId;
+
+/** A connection stored in an Environment, in the shape connector checks read. */
+const storedRecord = (stored: StoredEnvironmentConnection): PublicConnectorRecord => ({
+ agentId: null,
+ avatar: null,
+ createdAt: new Date(0),
+ description: null,
+ hasCredentials: !!stored.connection.credentials,
+ id: stored.connectorId,
+ identifier: stored.service,
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: stored.connection.url,
+ mountedByAgentId: null,
+ name: stored.connection.name ?? stored.service,
+ sourceType: 'custom',
+ status: 'connected',
+ updatedAt: new Date(0),
+ userId: '',
+});
+
+const stable = (value: unknown): string => {
+ if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`;
+ if (value && typeof value === 'object') {
+ return `{${Object.entries(value)
+ .filter(([, item]) => item !== undefined)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([key, item]) => `${JSON.stringify(key)}:${stable(item)}`)
+ .join(',')}}`;
+ }
+ return JSON.stringify(value) ?? 'null';
+};
+
+/** Only the selected connection's own MCP route may supply its forwarding destination. */
+export const getLobeBenchForwardingEndpoint = (serverUrl: string): string => {
+ let url: URL;
+ try {
+ url = new URL(serverUrl);
+ } catch {
+ throw new EvalConnectorBindingError('The mock connection has an invalid URL.');
+ }
+ const route = url.pathname.match(/^(.*)\/mcp\/([^/]+)\/([^/]+)\/?$/);
+ if (!route || url.username || url.password || url.search || url.hash) {
+ throw new EvalConnectorBindingError(
+ 'A LobeBench connection must use its /mcp/<dataset>/<service> discovery URL without credentials or query parameters.',
+ );
+ }
+ if (!['http:', 'https:'].includes(url.protocol)) {
+ throw new EvalConnectorBindingError('The mock connection must use HTTP or HTTPS.');
+ }
+ url.pathname = `${route[1]}/tool-exec/${route[2]}/${route[3]}/exec`;
+ return url.toString();
+};
+
+/** Evaluation-specific binding uses the connector UUID, never same-name resolution. */
+export class AgentEvalConnectorService {
+ private readonly connectorModel: ConnectorModel;
+ private readonly storedConnections: AgentEvalEnvironmentConnectionRepo;
+ private readonly toolModel: ConnectorToolModel;
+
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly datasetId: string,
+ private readonly workspaceId?: string,
+ ) {
+ if (!datasetId) throw unavailable();
+ this.connectorModel = ConnectorModel.forEvaluation(db, userId, datasetId, workspaceId);
+ this.toolModel = ConnectorToolModel.forEvaluation(db, userId, datasetId, workspaceId);
+ this.storedConnections = new AgentEvalEnvironmentConnectionRepo(db, userId, workspaceId);
+ }
+
+ /** A connection stored in an Environment this Dataset uses, by its `env:` id. */
+ private findStored = (connectorId: string) =>
+ parseEnvironmentConnectionId(connectorId)
+ ? this.storedConnections.find(this.datasetId, connectorId)
+ : Promise.resolve(undefined);
+
+ /** Connection metadata from a connector row or from an Environment, never credentials. */
+ private async findPublic(connectorId: string): Promise<PublicConnectorRecord | null> {
+ if (!parseEnvironmentConnectionId(connectorId))
+ return this.connectorModel.findPublicById(connectorId);
+ const stored = await this.findStored(connectorId);
+ return stored ? storedRecord(stored) : null;
+ }
+
+ /** Request headers carrying a stored connection's decrypted credentials. */
+ private async storedHeaders(stored: StoredEnvironmentConnection) {
+ let credentials: ConnectorCredentials | null = null;
+ if (stored.connection.credentials) {
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+ const { plaintext } = await gateKeeper.decrypt(stored.connection.credentials);
+ credentials = JSON.parse(plaintext) as ConnectorCredentials;
+ }
+ const { auth, headers } = buildHttpAuthFromCredentials(credentials);
+ return this.authHeaders({
+ auth,
+ headers,
+ name: stored.service,
+ type: 'http',
+ url: stored.connection.url,
+ });
+ }
+
+ /** The LobeBench adapter authenticates /sessions/* before lookup: 200 or 404 proves the credentials. */
+ private async probeLobeBench(serverUrl: string, headers: Headers) {
+ const endpoint = new URL(getLobeBenchForwardingEndpoint(serverUrl));
+ endpoint.pathname = endpoint.pathname.replace(
+ /\/tool-exec\/[^/]+\/[^/]+\/exec$/,
+ `/sessions/eval-connection-check-${crypto.randomUUID()}`,
+ );
+ const response = await ssrfSafeFetch(endpoint.toString(), {
+ headers,
+ method: 'GET',
+ redirect: 'manual',
+ signal: AbortSignal.timeout(15_000),
+ });
+ await response.body?.cancel().catch(() => {});
+ if (![200, 404].includes(response.status)) {
+ throw new EvalConnectorBindingError(
+ `Mock connection authentication failed (HTTP ${response.status}).`,
+ );
+ }
+ }
+
+ async listAvailableConnectors() {
+ const rows = await this.connectorModel.queryPublic();
+ return rows.filter(isEligible).map(({ id, identifier, name }) => ({ id, identifier, name }));
+ }
+
+ // Other native tool aliases are intentionally mockable through the hook;
+ // only evaluation infrastructure must keep its real implementation.
+ async validateBindings(bindings: EvalConnectorBindings = {}) {
+ for (const [identifier, binding] of Object.entries(bindings)) {
+ if (!identifier || EVAL_INFRASTRUCTURE_TOOLS.includes(identifier)) {
+ throw new EvalConnectorBindingError(
+ 'This tool identifier cannot be bound to a mock connection.',
+ );
+ }
+ const connector = await this.findPublic(binding.connectorId);
+ if (!isEligible(connector)) throw unavailable();
+ if (parseEnvironmentConnectionId(binding.connectorId) && binding.transport !== 'lobe-bench') {
+ throw new EvalConnectorBindingError(
+ 'A connection stored in an Environment must use the LobeBench transport.',
+ );
+ }
+ if (binding.transport === 'lobe-bench') {
+ getLobeBenchForwardingEndpoint(connector.mcpServerUrl!);
+ }
+ }
+ }
+
+ async resolveBindings(
+ bindings: EvalConnectorBindings = {},
+ expected?: EvalConnectorSnapshots,
+ contracts?: EvalToolManifests,
+ ) {
+ if (
+ expected &&
+ Object.keys(expected).length &&
+ getEvalConnectorDatasetId(expected) !== this.datasetId
+ )
+ throw unavailable();
+ await this.validateBindings(bindings);
+ const snapshots: EvalConnectorSnapshots = Object.create(null);
+ const manifests: ToolManifest[] = [];
+ if (expected && stable(Object.keys(expected).sort()) !== stable(Object.keys(bindings).sort())) {
+ throw new EvalConnectorBindingError('The mock bindings changed. Create a new experiment.');
+ }
+ for (const [identifier, binding] of Object.entries(bindings)) {
+ const connector = await this.findPublic(binding.connectorId);
+ if (!isEligible(connector)) throw unavailable();
+ const storedConnection = await this.findStored(connector.id);
+ const stored = !!storedConnection;
+ const transport = binding.transport ?? 'mcp';
+ // A stored connection carries its Environment's frozen contract with it.
+ const original =
+ contracts?.[identifier] ??
+ expected?.[identifier]?.manifest ??
+ storedConnection?.toolManifest;
+ if ((expected || contracts || stored) && !original) {
+ throw new EvalConnectorBindingError(
+ 'This run has no original tool contract. Add the contract to its Environment and create a new experiment.',
+ );
+ }
+ const manifest = original ? evalToolManifestSchema.parse(original) : undefined;
+ if (manifest && manifest.identifier !== identifier) {
+ throw new EvalConnectorBindingError('The tool contract does not match its binding.');
+ }
+ // A stored connection has no discovery cache: its frozen contract is its tool list.
+ const tools =
+ stored && manifest
+ ? manifest.api.map((api) => ({
+ description: api.description ?? null,
+ inputSchema: api.parameters,
+ permission: 'auto',
+ toolName: api.name,
+ }))
+ : await this.toolModel.queryByConnector(connector.id);
+ const fingerprint = createHash('sha256')
+ .update(
+ stable({
+ ...(manifest && { manifest }),
+ connectorId: connector.id,
+ datasetId: this.datasetId,
+ mcpServerUrl: connector.mcpServerUrl,
+ tools: tools
+ .map(({ description, inputSchema, permission, toolName }) => ({
+ description,
+ inputSchema,
+ permission,
+ toolName,
+ }))
+ .sort((a, b) => a.toolName.localeCompare(b.toolName)),
+ transport,
+ }),
+ )
+ .digest('hex');
+ const snapshot = {
+ connectorId: connector.id,
+ datasetId: this.datasetId,
+ fingerprint,
+ transport,
+ ...(manifest && { manifest }),
+ };
+ if (expected && stable(expected[identifier]) !== stable(snapshot)) {
+ throw new EvalConnectorBindingError(
+ `${bindingLabel(identifier, connector.id)}: The mock connection or its tools changed. Create a new experiment with the current connection.`,
+ );
+ }
+ const permitted = new Set(
+ tools.filter((tool) => tool.permission === 'auto').map((tool) => tool.toolName),
+ );
+ if (!permitted.size) {
+ throw new EvalConnectorBindingError(
+ `${bindingLabel(identifier, connector.id)}: The connection has no automatically permitted tools.`,
+ );
+ }
+ if (manifest?.api.some((api) => !permitted.has(api.name))) {
+ throw new EvalConnectorBindingError(
+ `${bindingLabel(identifier, connector.id)}: The connection does not provide all original tools with automatically permitted access.`,
+ );
+ }
+ snapshots[identifier] = snapshot;
+ // Deliberately no mcpParams: operation state may retain this manifest.
+ if (manifest) manifests.push(manifest as ToolManifest);
+ }
+ return { manifests, snapshots };
+ }
+
+ /**
+ * Share discovery only within this preflight, while validating every case's
+ * aliases. `contracts[i]` are group i's own tool contracts: a connection stored
+ * in an Environment is checked against the contract of the case that brought
+ * it, which may live in the case rather than in the shared Environment.
+ */
+ async checkBindingGroups(
+ groups: EvalConnectorBindings[],
+ contracts: Array<EvalToolManifests | undefined> = [],
+ ) {
+ const startedAt = performance.now();
+ const connectionCount = new Set(
+ groups.flatMap((bindings) => Object.values(bindings).map(({ connectorId }) => connectorId)),
+ ).size;
+ const connections = new Map<
+ string,
+ Map<string, { bindings: EvalConnectorBindings; contracts?: EvalToolManifests }>
+ >();
+ let status = 'failure';
+ try {
+ for (const [index, bindings] of groups.entries()) {
+ await this.validateBindings(bindings);
+ for (const [identifier, binding] of Object.entries(bindings)) {
+ let transports = connections.get(binding.connectorId);
+ if (!transports) {
+ transports = new Map();
+ connections.set(binding.connectorId, transports);
+ }
+ const transport = binding.transport ?? 'mcp';
+ // Only a stored connection takes its contract from the case: a connector
+ // row is checked against its own discovered tools, as before.
+ const contract = parseEnvironmentConnectionId(binding.connectorId)
+ ? contracts[index]?.[identifier]
+ : undefined;
+ if (!transports.has(transport))
+ transports.set(transport, {
+ bindings: { [identifier]: binding },
+ ...(contract && { contracts: { [identifier]: contract } }),
+ });
+ }
+ }
+ await pMap(
+ connections.values(),
+ async (transports) => {
+ // Different transports still sync the same connector's tools. Serialize
+ // them to avoid competing upserts, but check each protocol independently.
+ for (const { bindings, contracts } of transports.values())
+ await this.checkBindings(bindings, contracts);
+ },
+ { concurrency: 4 },
+ );
+ status = 'success';
+ } finally {
+ log(
+ 'preflight batch groups=%d connections=%d elapsedMs=%d status=%s',
+ groups.length,
+ connectionCount,
+ Math.round(performance.now() - startedAt),
+ status,
+ );
+ }
+ }
+
+ /** Authenticated discovery is run before creation, not inferred from cached health. */
+ async checkBindings(bindings: EvalConnectorBindings = {}, contracts?: EvalToolManifests) {
+ await this.validateBindings(bindings);
+ if (Object.keys(bindings).length === 0)
+ return this.resolveBindings(bindings, undefined, contracts);
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+ const connectorModel = ConnectorModel.forEvaluation(
+ this.db,
+ this.userId,
+ this.datasetId,
+ this.workspaceId,
+ gateKeeper,
+ );
+ for (const [identifier, binding] of Object.entries(bindings)) {
+ try {
+ if (parseEnvironmentConnectionId(binding.connectorId)) {
+ const stored = await this.findStored(binding.connectorId);
+ if (!stored) throw unavailable();
+ await this.probeLobeBench(stored.connection.url, await this.storedHeaders(stored));
+ continue;
+ }
+ const publicRow = await this.connectorModel.findPublicById(binding.connectorId);
+ const credentialRow = await connectorModel.findById(binding.connectorId);
+ if (
+ !isEligible(publicRow) ||
+ !credentialRow ||
+ (publicRow.hasCredentials && !credentialRow.credentials)
+ )
+ throw unavailable();
+ await syncConnectorToolsById(
+ binding.connectorId,
+ {
+ connectorModel,
+ connectorToolModel: this.toolModel,
+ },
+ { pruneMissingAutoTools: true },
+ );
+ // The canonical LobeBench adapter authenticates /sessions/* before lookup.
+ // Its missing-session 404 therefore verifies auth; arbitrary MCP servers
+ // must use the standard adapter instead of claiming this protocol.
+ if (binding.transport === 'lobe-bench') {
+ const connector = await connectorModel.findById(binding.connectorId);
+ if (!connector?.mcpServerUrl) throw unavailable();
+ await this.probeLobeBench(
+ connector.mcpServerUrl,
+ this.authHeaders(buildConnectorMcpParams(connector)),
+ );
+ }
+ } catch (error) {
+ log(
+ 'preflight failed connector=%s errorType=%s',
+ binding.connectorId,
+ error instanceof Error ? error.name : typeof error,
+ );
+ // Report the stable connection and its representative alias, never the
+ // upstream message (which may contain credentials or private URLs).
+ const reason =
+ error instanceof EvalConnectorBindingError
+ ? error.message
+ : error instanceof Error && error.name === 'TimeoutError'
+ ? 'Could not verify the mock connection: the request timed out.'
+ : error instanceof Error && error.name === 'AbortError'
+ ? 'Could not verify the mock connection: the request was interrupted.'
+ : 'Could not verify the mock connection. Check its address, credentials and tool access.';
+ throw new EvalConnectorBindingError(
+ `${bindingLabel(identifier, binding.connectorId)}: ${reason}`,
+ );
+ }
+ }
+ return this.resolveBindings(bindings, undefined, contracts);
+ }
+
+ /** The stored connections this Dataset's Environments hold. */
+ listStoredConnections() {
+ return this.storedConnections.listForDataset(this.datasetId);
+ }
+
+ /** Authenticates a stored connection against its mock; reports the size of its frozen contract. */
+ async testStoredConnection(connectorId: string) {
+ const stored = await this.findStored(connectorId);
+ if (!stored) throw unavailable();
+ await this.probeLobeBench(stored.connection.url, await this.storedHeaders(stored));
+ return { toolCount: stored.toolManifest?.api.length ?? 0 };
+ }
+
+ private authHeaders(clientParams: ReturnType<typeof buildConnectorMcpParams>) {
+ const headers = new Headers('headers' in clientParams ? clientParams.headers : undefined);
+ const auth = 'auth' in clientParams ? clientParams.auth : undefined;
+ if (auth?.type === 'bearer') headers.set('Authorization', `Bearer ${auth.token}`);
+ if (auth?.type === 'oauth2' && auth.accessToken) {
+ headers.set('Authorization', `Bearer ${auth.accessToken}`);
+ }
+ return headers;
+ }
+
+ async execute(
+ identifier: string,
+ bindings: EvalConnectorSnapshots,
+ params: {
+ apiName: string;
+ args: string;
+ attemptId?: string;
+ callIndex?: number;
+ caseId?: string;
+ operationId?: string;
+ stepIndex?: number;
+ },
+ ) {
+ if (getEvalConnectorDatasetId(bindings) !== this.datasetId) throw unavailable();
+ const binding = Object.hasOwn(bindings, identifier) ? bindings[identifier] : undefined;
+ if (!binding) throw unavailable();
+ const approved = await this.findPublic(binding.connectorId);
+ if (!isEligible(approved)) throw unavailable();
+ const { manifests } = await this.resolveBindings(
+ { [identifier]: binding },
+ { [identifier]: binding },
+ );
+ if (!manifests[0].api.some((tool) => tool.name === params.apiName)) {
+ throw new EvalConnectorBindingError('This tool is not permitted for unattended evaluation.');
+ }
+ if (parseEnvironmentConnectionId(binding.connectorId)) {
+ const stored = await this.findStored(binding.connectorId);
+ if (!stored || stored.connection.url !== approved.mcpServerUrl) throw unavailable();
+ return this.forwardLobeBench(stored.connection.url, await this.storedHeaders(stored), params);
+ }
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+ const credentialModel = ConnectorModel.forEvaluation(
+ this.db,
+ this.userId,
+ this.datasetId,
+ this.workspaceId,
+ gateKeeper,
+ );
+ let connector = await credentialModel.findById(binding.connectorId);
+ if (
+ !connector ||
+ !connector.isEnabled ||
+ connector.agentId ||
+ connector.metadata?.mountedByAgentId ||
+ connector.mcpConnectionType !== 'http' ||
+ connector.mcpServerUrl !== approved.mcpServerUrl ||
+ (approved.hasCredentials && !connector.credentials)
+ ) {
+ throw unavailable();
+ }
+ connector = await ensureFreshConnectorToken(connector, credentialModel);
+ const clientParams = buildConnectorMcpParams(connector);
+ if (binding.transport !== 'lobe-bench') {
+ return mcpService.callTool({ argsStr: params.args, clientParams, toolName: params.apiName });
+ }
+
+ if (!connector.mcpServerUrl) throw unavailable();
+ return this.forwardLobeBench(connector.mcpServerUrl, this.authHeaders(clientParams), params);
+ }
+
+ /** One tool call forwarded to a LobeBench mock's /tool-exec route for this case attempt. */
+ private async forwardLobeBench(
+ serverUrl: string,
+ headers: Headers,
+ params: {
+ apiName: string;
+ args: string;
+ attemptId?: string;
+ callIndex?: number;
+ caseId?: string;
+ operationId?: string;
+ stepIndex?: number;
+ },
+ ) {
+ if (!params.caseId || !params.attemptId) {
+ throw new EvalConnectorBindingError(
+ 'The LobeBench mock requires a case and attempt identity.',
+ );
+ }
+ const endpoint = getLobeBenchForwardingEndpoint(serverUrl);
+ headers.set('Content-Type', 'application/json');
+ const response = await ssrfSafeFetch(endpoint, {
+ body: JSON.stringify({
+ data: {
+ apiName: params.apiName,
+ args: params.args,
+ identifier: decodeURIComponent(
+ new URL(serverUrl).pathname.replace(/\/$/, '').split('/').at(-1)!,
+ ),
+ },
+ metadata: {
+ attemptId: params.attemptId,
+ callIndex: params.callIndex,
+ caseId: params.caseId,
+ operationId: params.operationId,
+ stepIndex: params.stepIndex,
+ },
+ type: 'toolCall',
+ }),
+ headers,
+ method: 'POST',
+ redirect: 'manual',
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => {});
+ throw new EvalConnectorBindingError(`The mock connection returned HTTP ${response.status}.`);
+ }
+ const body: unknown = await response.json();
+ if (
+ !isRecord(body) ||
+ body.success !== true ||
+ !isRecord(body.data) ||
+ typeof body.data.content !== 'string' ||
+ typeof body.data.success !== 'boolean'
+ ) {
+ throw new EvalConnectorBindingError('The mock connection returned an invalid tool result.');
+ }
+ return { content: body.data.content, success: body.data.success };
+ }
+}
diff --git a/apps/server/src/services/agentEvalDatasetPackage/README.md b/apps/server/src/services/agentEvalDatasetPackage/README.md
new file mode 100644
index 00000000000..245b2cf45f5
--- /dev/null
+++ b/apps/server/src/services/agentEvalDatasetPackage/README.md
@@ -0,0 +1,118 @@
+# Dataset ZIP packages
+
+LobeBench's Dataset import reuses the Eval Lab upload dialog. A package imports
+portable content into the current account or workspace; it never installs a
+system benchmark. Benchmark assets are distributed separately and are not bundled
+with this importer. The product does not provide example packages.
+
+## Version 1
+
+Place `dataset.json` directly at the ZIP root, without an enclosing folder. Its
+`format` must be `lobehub-eval-dataset` and its `version` must be `1`.
+
+`dataset` contains a name and optional description, grading mode/configuration,
+and release/presentation/mock metadata. `cases` contains unique portable keys,
+the existing structured case content (including conversation messages and inline
+environment), optional grading mode/configuration, metadata and sort order.
+`environments` contains unique keys, names and existing environment configuration.
+A case's optional `environmentKey` references a key in this same package. The
+importer generates new database IDs for all imported rows.
+Every case must supply `evalMode` or inherit it from `dataset.evalMode`; grading
+cannot depend on a system benchmark that may not exist on the recipient's server.
+
+The contract is defined by `AgentEvalDatasetPackage` in `@lobechat/types`, validated
+by `datasetPackageSchema` in the agentEval router. Case grading and environment
+fields use the same schemas as existing case authoring. Grading rules are retained,
+not inferred from a CSV column mapping. Importing does not execute a case or judge.
+
+Root, dataset, case and environment envelopes reject unknown fields. Do not include
+database IDs, ownership fields or system flags. Grading configuration is kept as
+authored; a successful import does not validate remote dependencies.
+
+## Mock connections
+
+A private package can carry the connection settings needed by its cases. The
+optional top-level `connections` object maps package-local keys to these fields:
+
+| Field | Purpose |
+| ------------- | ------------------------------------------------------------------------------------- |
+| `name` | Display name for the imported MCP connection. |
+| `url` | HTTP or HTTPS MCP server address, without URL userinfo, query or fragment. |
+| `credentials` | Optional `{ type: 'bearer', token }` or `{ type: 'header', headers }` authentication. |
+
+The credentials belong to that external mock service. They are not LobeHub's
+deployment key and are not shared across every mock. Only distribute a private
+package with credentials to recipients authorized to use that mock.
+
+Each environment or case envelope can contain `connectionBindings`. Its keys are
+the logical service identifiers used by the case; each value contains a
+`connectionKey` referring to this package's `connections`, plus an optional
+`transport`:
+
+- `mcp` (the default) calls the selected server through the standard MCP protocol.
+- `lobe-bench` uses that server's LobeBench session adapter to isolate case state.
+ `dataset.metadata.mock.dataset`, when supplied, is its logical dataset segment.
+
+Shared environments supply reusable bindings. Inline case bindings can replace
+individual package bindings; the importer resolves the complete effective case
+mapping. Declared bindings also declare their logical services. Installed
+`config.connectorBindings` and connector database IDs are not accepted in ZIPs.
+
+Import creates fresh, scoped `user_connectors` records for referenced definitions.
+Credentials are encrypted before the database transaction. Environment and case
+configuration store only the resolved connector IDs and transport; they do not
+store URLs or credentials. Imported connections carry dataset/package provenance
+and are excluded from normal chat's automatic connector discovery. Re-importing
+the same package never overwrites an existing connection. No database migration
+or global mock token is required.
+
+The preview shows connection names, required services and whether authentication
+was supplied; it never returns connection URLs or credential values. Import can
+also select existing accessible connections, or leave missing bindings for later
+configuration in the Dataset. Before a run starts, LobeHub checks the selected
+connections and discovers their tools; the external mock verifies authentication.
+Missing or invalid connections prevent execution. A run freezes connection
+identity so changing an Environment cannot silently retarget that run.
+
+Dataset connection repair preserves case content and release identity. An
+environment shared with another dataset must be copied before changing its
+connections through this repair flow. Imported connections are not automatically
+deleted with a dataset because another environment may still reference them.
+They remain independently managed connections. Remove an unused connection from
+Settings explicitly; deleting a connection still used by a case makes that case
+require a replacement binding before it can run.
+
+Editing an imported connection preserves its evaluation-only provenance. Header
+authentication stays encrypted even when the shared connector editor submits
+headers as metadata. An omitted credential field keeps authentication, explicit
+`null` clears it, and a credential object replaces it. When the address changes,
+explicit `null` also discards headers resubmitted by the editor; retaining existing
+authentication on a new address is rejected, while explicit replacement is allowed.
+
+## Behavior and limits
+
+- Upload: at most 10 MiB compressed, 32 MiB expanded in total; `dataset.json` at most
+ 25 MiB. At most 50 ZIP entries, 5,000 cases and 500 shared environments.
+- Optional `README.md`, directories and conventional macOS metadata are tolerated.
+ Other data files are rejected, so unimported case files cannot be silently lost.
+- Unsafe paths, duplicates, encrypted/multipart/ZIP64 archives, checksum errors,
+ truncated data and unsupported compression are rejected before database writes.
+- Preview checks the complete package and displays sample inputs and counts.
+ Confirmation validates the archive again, then imports connections, environments,
+ cases and their dataset in one transaction. No external mock is contacted inside
+ that transaction; failed imports leave none of these new records behind.
+- New LobeBench datasets belong to an owned benchmark or a newly created benchmark.
+ Existing empty owned datasets may receive a package only if they have no cases
+ (including retired cases) and no runs. Otherwise import as a new dataset.
+- Existing cases, runs and results are never overwritten. To distribute a revised
+ package, import it as a new dataset and keep the old dataset for comparisons.
+- Imported metadata records the package version and SHA256 of the original
+ `dataset.json` bytes. Identical content with different ZIP timestamps has the same
+ digest. This records source identity; it does not certify the external mock version.
+- Failed imports retain their temporary upload for retry. Successful imports release
+ it through the existing upload lifecycle; there is no public package download API.
+ A private package's upload contains its supplied credentials until this cleanup
+ or the temporary-upload expiry, so it remains an account-scoped temporary asset.
+
+Database migrations still create the evaluation tables. A content seed command is
+not needed to start using LobeBench: users import separately distributed packages.
diff --git a/apps/server/src/services/agentEvalDatasetPackage/archive.test.ts b/apps/server/src/services/agentEvalDatasetPackage/archive.test.ts
new file mode 100644
index 00000000000..473e6ea3b2e
--- /dev/null
+++ b/apps/server/src/services/agentEvalDatasetPackage/archive.test.ts
@@ -0,0 +1,312 @@
+import { createHash } from 'node:crypto';
+
+import { strToU8, Zip, ZipDeflate, zipSync } from 'fflate';
+import { describe, expect, it } from 'vitest';
+
+import {
+ DATASET_PACKAGE_MAX_COMPRESSED_BYTES,
+ DATASET_PACKAGE_MAX_ENTRIES,
+ DATASET_PACKAGE_MAX_EXPANDED_BYTES,
+ DATASET_PACKAGE_MAX_MANIFEST_BYTES,
+ readDatasetPackageArchive,
+} from './archive';
+
+const manifest = { cases: [], name: 'Synthetic import test', version: 1 };
+const manifestBytes = strToU8(JSON.stringify(manifest));
+const archive = () => zipSync({ 'dataset.json': manifestBytes });
+const viewOf = (bytes: Uint8Array) =>
+ new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+
+// Helpers only inspect well-formed synthetic archives before corrupting one field.
+const directoryEntries = (bytes: Uint8Array) => {
+ const view = viewOf(bytes);
+ const end = bytes.length - 22;
+ let offset = view.getUint32(end + 16, true);
+ return Array.from({ length: view.getUint16(end + 10, true) }, () => {
+ const current = offset;
+ offset +=
+ 46 +
+ view.getUint16(offset + 28, true) +
+ view.getUint16(offset + 30, true) +
+ view.getUint16(offset + 32, true);
+ return current;
+ });
+};
+
+const replaceExpandedSize = (bytes: Uint8Array, index: number, size: number) => {
+ const view = viewOf(bytes);
+ const central = directoryEntries(bytes)[index];
+ const local = view.getUint32(central + 42, true);
+ view.setUint32(central + 24, size, true);
+ view.setUint32(local + 22, size, true);
+};
+
+const streamingArchive = () => {
+ const chunks: Uint8Array[] = [];
+ const zip = new Zip((error, chunk) => {
+ if (error) throw error;
+ chunks.push(chunk);
+ });
+ const file = new ZipDeflate('dataset.json');
+ zip.add(file);
+ file.push(manifestBytes.subarray(0, 10));
+ file.push(manifestBytes.subarray(10), true);
+ zip.end();
+ return new Uint8Array(Buffer.concat(chunks));
+};
+
+describe('readDatasetPackageArchive', () => {
+ it.each([0, 6] as const)('reads a root manifest with compression level %s', (level) => {
+ const result = readDatasetPackageArchive(zipSync({ 'dataset.json': manifestBytes }, { level }));
+
+ expect(result).toEqual({
+ manifest,
+ sha256: createHash('sha256').update(manifestBytes).digest('hex'),
+ });
+ });
+
+ it('uses manifest bytes for identity, independent of ZIP timestamp and README', () => {
+ const first = zipSync({ 'dataset.json': manifestBytes }, { mtime: new Date('2020-01-01') });
+ const second = zipSync(
+ { 'README.md': strToU8('Package instructions'), 'dataset.json': manifestBytes },
+ { mtime: new Date('2024-01-01') },
+ );
+
+ expect(readDatasetPackageArchive(first).sha256).toBe(readDatasetPackageArchive(second).sha256);
+ });
+
+ it('accepts harmless macOS metadata and standard extended timestamps', () => {
+ const bytes = zipSync({
+ '.DS_Store': strToU8('synthetic metadata'),
+ 'README.md': strToU8('No private cases included'),
+ '__MACOSX/': new Uint8Array(),
+ '__MACOSX/._dataset.json': strToU8('synthetic AppleDouble metadata'),
+ 'dataset.json': [manifestBytes, { extra: { 0x5455: new Uint8Array(5) }, os: 19 }],
+ });
+
+ expect(readDatasetPackageArchive(bytes).manifest).toEqual(manifest);
+ });
+
+ it('handles a Uint8Array view with a nonzero buffer offset', () => {
+ const bytes = archive();
+ const buffer = new Uint8Array(bytes.length + 12);
+ buffer.set(bytes, 7);
+
+ expect(readDatasetPackageArchive(buffer.subarray(7, 7 + bytes.length)).manifest).toEqual(
+ manifest,
+ );
+ });
+
+ it('accepts ZIP data descriptors emitted by streaming encoders', () => {
+ const bytes = streamingArchive();
+ expect(viewOf(bytes).getUint16(6, true) & 8).toBe(8);
+
+ expect(readDatasetPackageArchive(bytes).manifest).toEqual(manifest);
+ });
+
+ it('accepts data descriptors without the optional signature', () => {
+ const bytes = streamingArchive();
+ const view = viewOf(bytes);
+ const central = directoryEntries(bytes)[0];
+ const descriptor =
+ 30 + view.getUint16(26, true) + view.getUint16(28, true) + view.getUint32(central + 20, true);
+ const unsigned = new Uint8Array(bytes.length - 4);
+ unsigned.set(bytes.subarray(0, descriptor));
+ unsigned.set(bytes.subarray(descriptor + 4), descriptor);
+ viewOf(unsigned).setUint32(unsigned.length - 6, central - 4, true);
+
+ expect(readDatasetPackageArchive(unsigned).manifest).toEqual(manifest);
+ });
+
+ it('rejects a corrupted data descriptor', () => {
+ const bytes = streamingArchive();
+ const central = directoryEntries(bytes)[0];
+ bytes[central - 12] ^= 1;
+
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('invalid data descriptor');
+ });
+
+ it.each([0, 5, 22])('rejects missing or truncated ZIP data (%s bytes)', (length) => {
+ expect(() => readDatasetPackageArchive(new Uint8Array(length))).toThrow('end record');
+ });
+
+ it('rejects a ZIP truncated at its end', () => {
+ expect(() => readDatasetPackageArchive(archive().subarray(0, -1))).toThrow('end record');
+ });
+
+ it('rejects unexpected bytes after the archive', () => {
+ const bytes = new Uint8Array([...archive(), 1, 2, 3]);
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('end record');
+ });
+
+ it('requires dataset.json at the archive root', () => {
+ expect(() =>
+ readDatasetPackageArchive(zipSync({ 'README.md': strToU8('Instructions') })),
+ ).toThrow('dataset.json must be at the archive root');
+ expect(() =>
+ readDatasetPackageArchive(zipSync({ 'package/dataset.json': manifestBytes })),
+ ).toThrow('only dataset.json');
+ });
+
+ it.each([
+ '../.DS_Store',
+ '/dataset.json',
+ 'folder\\dataset.json',
+ 'C:/dataset.json',
+ './dataset.json',
+ 'x//._file',
+ ])('rejects unsafe paths, including metadata: %s', (name) => {
+ expect(() =>
+ readDatasetPackageArchive(
+ zipSync({ [name]: new Uint8Array(), 'dataset.json': manifestBytes }),
+ ),
+ ).toThrow('unsafe entry path');
+ });
+
+ it.each(['cases.json', 'setup.js', 'other.txt'])(
+ 'rejects unsupported data instead of ignoring %s',
+ (name) => {
+ expect(() =>
+ readDatasetPackageArchive(
+ zipSync({ [name]: strToU8('data'), 'dataset.json': manifestBytes }),
+ ),
+ ).toThrow('only dataset.json');
+ },
+ );
+
+ it('rejects duplicate dataset.json entries', () => {
+ const bytes = zipSync({ 'dataset.json': manifestBytes, 'payload.json': manifestBytes });
+ const view = viewOf(bytes);
+ const central = directoryEntries(bytes)[1];
+ const local = view.getUint32(central + 42, true);
+ bytes.set(strToU8('dataset.json'), central + 46);
+ bytes.set(strToU8('dataset.json'), local + 30);
+
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('duplicate entry names');
+ });
+
+ it('rejects encrypted ZIP entries before processing the payload', () => {
+ const bytes = archive();
+ const view = viewOf(bytes);
+ view.setUint16(directoryEntries(bytes)[0] + 8, 1, true);
+ view.setUint16(6, 1, true);
+
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('encrypted archives');
+ });
+
+ it('rejects symlinks masquerading as a manifest', () => {
+ const bytes = zipSync({ 'dataset.json': [manifestBytes, { attrs: 0xa1ff_0000, os: 3 }] });
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('symlinks and special files');
+ });
+
+ it('rejects nonempty directory entries', () => {
+ const bytes = zipSync({ 'dataset.json': manifestBytes, 'folder/': strToU8('hidden data') });
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('directory entries must be empty');
+ });
+
+ it('checks stored file integrity even when the modified payload is still JSON', () => {
+ const bytes = zipSync({ 'dataset.json': strToU8('{"version":1}') }, { level: 0 });
+ const view = viewOf(bytes);
+ const start = 30 + view.getUint16(26, true) + view.getUint16(28, true);
+ bytes[start + 11] = '2'.charCodeAt(0);
+
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('entry checksum does not match');
+ });
+
+ it('rejects conflicting local and central filenames', () => {
+ const bytes = archive();
+ bytes[30] = 'D'.charCodeAt(0);
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('entry names disagree');
+ });
+
+ it('rejects conflicting local and central sizes', () => {
+ const bytes = archive();
+ viewOf(bytes).setUint32(22, 1, true);
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('sizes or checksum disagree');
+ });
+
+ it.each([-1, 1])('rejects a DEFLATE stream with %s bytes even if ZIP sizes agree', (delta) => {
+ const original = archive();
+ const central = directoryEntries(original)[0];
+ const compressedSize = viewOf(original).getUint32(central + 20, true);
+ const bytes = new Uint8Array(original.length + delta);
+ bytes.set(original.subarray(0, delta < 0 ? central - 1 : central));
+ bytes.set(original.subarray(central), central + delta);
+ const view = viewOf(bytes);
+ view.setUint32(18, compressedSize + delta, true);
+ view.setUint32(central + delta + 20, compressedSize + delta, true);
+ view.setUint32(bytes.length - 6, central + delta, true);
+
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('invalid DEFLATE data');
+ });
+
+ it('rejects directory offsets pointing outside the ZIP file', () => {
+ const bytes = archive();
+ viewOf(bytes).setUint32(bytes.length - 6, bytes.length + 1, true);
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('truncated or overlapping');
+ });
+
+ it('rejects central directory entries that overlap earlier file data', () => {
+ const bytes = zipSync({ 'dataset.json': manifestBytes, 'README.md': strToU8('Instructions') });
+ viewOf(bytes).setUint32(directoryEntries(bytes)[1] + 42, 0, true);
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('overlapping');
+ });
+
+ it('rejects compressed archives over 10 MiB', () => {
+ expect(() =>
+ readDatasetPackageArchive(new Uint8Array(DATASET_PACKAGE_MAX_COMPRESSED_BYTES + 1)),
+ ).toThrow('10 MiB limit');
+ });
+
+ it('rejects manifest sizes over 25 MiB before inflation', () => {
+ const bytes = archive();
+ replaceExpandedSize(bytes, 0, DATASET_PACKAGE_MAX_MANIFEST_BYTES + 1);
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('25 MiB limit');
+ });
+
+ it('enforces the aggregate expanded budget including ignored metadata', () => {
+ const bytes = zipSync({ 'dataset.json': manifestBytes, '.DS_Store': strToU8('metadata') });
+ replaceExpandedSize(bytes, 1, DATASET_PACKAGE_MAX_EXPANDED_BYTES);
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('32 MiB limit');
+ });
+
+ it('bounds the actual decoder output when a compressed bomb lies about its size', () => {
+ const bytes = zipSync({
+ 'dataset.json': new Uint8Array(DATASET_PACKAGE_MAX_MANIFEST_BYTES + 1),
+ });
+ replaceExpandedSize(bytes, 0, 1024);
+ expect(bytes.length).toBeLessThan(DATASET_PACKAGE_MAX_COMPRESSED_BYTES);
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('expanded size exceeds the limit');
+ });
+
+ it('rejects excess entries, including directories and metadata', () => {
+ const files: Record<string, Uint8Array> = { 'dataset.json': manifestBytes };
+ for (let index = 0; index < DATASET_PACKAGE_MAX_ENTRIES; index++) {
+ files[`__MACOSX/._${index}`] = new Uint8Array();
+ }
+ expect(() => readDatasetPackageArchive(zipSync(files))).toThrow('between 1 and 50 entries');
+ });
+
+ it('rejects ZIP64 metadata', () => {
+ const bytes = zipSync({
+ 'dataset.json': [manifestBytes, { extra: { 1: new Uint8Array(16) } }],
+ });
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('ZIP64');
+ });
+
+ it('rejects split archives', () => {
+ const bytes = archive();
+ viewOf(bytes).setUint16(bytes.length - 18, 1, true);
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('multi-volume');
+ });
+
+ it('rejects a manifest that is not JSON', () => {
+ const bytes = zipSync({ 'dataset.json': strToU8('this is not JSON') });
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('valid UTF-8 JSON');
+ });
+
+ it('rejects malformed UTF-8 instead of replacing bytes inside the manifest', () => {
+ const bytes = zipSync({ 'dataset.json': new Uint8Array([0x22, 0xff, 0x22]) });
+ expect(() => readDatasetPackageArchive(bytes)).toThrow('valid UTF-8 JSON');
+ });
+});
diff --git a/apps/server/src/services/agentEvalDatasetPackage/archive.ts b/apps/server/src/services/agentEvalDatasetPackage/archive.ts
new file mode 100644
index 00000000000..0cda78b08bd
--- /dev/null
+++ b/apps/server/src/services/agentEvalDatasetPackage/archive.ts
@@ -0,0 +1,290 @@
+import { createHash } from 'node:crypto';
+import { inflateRawSync } from 'node:zlib';
+
+export const DATASET_PACKAGE_MAX_COMPRESSED_BYTES = 10 * 1024 * 1024;
+export const DATASET_PACKAGE_MAX_MANIFEST_BYTES = 25 * 1024 * 1024;
+export const DATASET_PACKAGE_MAX_EXPANDED_BYTES = 32 * 1024 * 1024;
+export const DATASET_PACKAGE_MAX_ENTRIES = 50;
+
+const END_RECORD = 0x0605_4b50;
+const CENTRAL_HEADER = 0x0201_4b50;
+const LOCAL_HEADER = 0x0403_4b50;
+const DATA_DESCRIPTOR = 0x0807_4b50;
+const decoder = new TextDecoder('utf-8', { fatal: true });
+
+interface ArchiveEntry {
+ compressedSize: number;
+ crc: number;
+ flags: number;
+ localOffset: number;
+ method: number;
+ name: string;
+ nameBytes: Uint8Array;
+ originalSize: number;
+}
+
+const invalid = (message: string): never => {
+ throw new Error(`Invalid dataset ZIP: ${message}`);
+};
+
+const decode = (bytes: Uint8Array, what: string): string => {
+ try {
+ return decoder.decode(bytes);
+ } catch {
+ return invalid(`${what} must use valid UTF-8`);
+ }
+};
+
+const requireRange = (start: number, size: number, end: number) => {
+ if (start < 0 || size < 0 || start > end || size > end - start) {
+ invalid('truncated or overlapping archive records');
+ }
+};
+
+const validateName = (name: string) => {
+ // eslint-disable-next-line no-control-regex -- ZIP entry paths must reject control characters.
+ if (!name || name.startsWith('/') || name.includes('\\') || /[\u0000-\u001F\u007F:]/.test(name)) {
+ invalid('unsafe entry path');
+ }
+ const segments = (name.endsWith('/') ? name.slice(0, -1) : name).split('/');
+ if (segments.some((part) => !part || part === '.' || part === '..')) {
+ invalid('unsafe entry path');
+ }
+ const leaf = segments.at(-1)!;
+ const isMacMetadata = leaf === '.DS_Store' || leaf.startsWith('._');
+ if (name !== 'dataset.json' && name !== 'README.md' && !name.endsWith('/') && !isMacMetadata) {
+ invalid('only dataset.json, README.md, directories and macOS metadata are supported');
+ }
+};
+
+const validateExtra = (view: DataView, start: number, size: number) => {
+ const end = start + size;
+ while (start < end) {
+ requireRange(start, 4, end);
+ const id = view.getUint16(start, true);
+ const length = view.getUint16(start + 2, true);
+ if (id === 0x0001) invalid('ZIP64 archives are not supported');
+ requireRange(start + 4, length, end);
+ start += 4 + length;
+ }
+};
+
+const readDirectory = (bytes: Uint8Array, view: DataView) => {
+ let endOffset = -1;
+ for (let offset = bytes.length - 22; offset >= Math.max(0, bytes.length - 65_557); offset--) {
+ if (
+ view.getUint32(offset, true) === END_RECORD &&
+ offset + 22 + view.getUint16(offset + 20, true) === bytes.length
+ ) {
+ endOffset = offset;
+ break;
+ }
+ }
+ if (endOffset < 0) invalid('missing or truncated end record');
+ const count = view.getUint16(endOffset + 10, true);
+ if (
+ view.getUint16(endOffset + 4, true) !== 0 ||
+ view.getUint16(endOffset + 6, true) !== 0 ||
+ view.getUint16(endOffset + 8, true) !== count
+ ) {
+ invalid('multi-volume archives are not supported');
+ }
+ if (count === 0xffff) invalid('ZIP64 archives are not supported');
+ if (count === 0 || count > DATASET_PACKAGE_MAX_ENTRIES) {
+ invalid(`the archive must contain between 1 and ${DATASET_PACKAGE_MAX_ENTRIES} entries`);
+ }
+ const directorySize = view.getUint32(endOffset + 12, true);
+ const directoryOffset = view.getUint32(endOffset + 16, true);
+ requireRange(directoryOffset, directorySize, endOffset);
+ if (directoryOffset + directorySize !== endOffset) invalid('invalid central directory boundary');
+
+ const entries: ArchiveEntry[] = [];
+ const names = new Set<string>();
+ let offset = directoryOffset;
+ let totalSize = 0;
+ for (let index = 0; index < count; index++) {
+ requireRange(offset, 46, endOffset);
+ if (view.getUint32(offset, true) !== CENTRAL_HEADER) invalid('invalid central directory');
+ const flags = view.getUint16(offset + 8, true);
+ const method = view.getUint16(offset + 10, true);
+ const compressedSize = view.getUint32(offset + 20, true);
+ const originalSize = view.getUint32(offset + 24, true);
+ const nameLength = view.getUint16(offset + 28, true);
+ const extraLength = view.getUint16(offset + 30, true);
+ const commentLength = view.getUint16(offset + 32, true);
+ const localOffset = view.getUint32(offset + 42, true);
+ requireRange(offset + 46, nameLength + extraLength + commentLength, endOffset);
+ if (flags & 0x0041) invalid('encrypted archives are not supported');
+ if (flags & ~0x080e) invalid('unsupported ZIP flags');
+ if (method !== 0 && method !== 8) invalid('only stored or DEFLATE entries are supported');
+ if (view.getUint16(offset + 34, true) !== 0) invalid('multi-volume entries are not supported');
+ if ([compressedSize, originalSize, localOffset].includes(0xffff_ffff)) {
+ invalid('ZIP64 entries are not supported');
+ }
+ const nameBytes = bytes.subarray(offset + 46, offset + 46 + nameLength);
+ if (!(flags & 0x0800) && nameBytes.some((value) => value > 0x7f)) {
+ invalid('non-ASCII entry names must use the UTF-8 flag');
+ }
+ const name = decode(nameBytes, 'entry names');
+ validateName(name);
+ if (names.has(name)) invalid('duplicate entry names');
+ names.add(name);
+ const fileType = (view.getUint32(offset + 38, true) >>> 16) & 0xf000;
+ if (fileType !== 0 && fileType !== 0x8000 && fileType !== 0x4000) {
+ invalid('symlinks and special files are not supported');
+ }
+ if ((fileType === 0x4000 || name.endsWith('/')) && originalSize !== 0) {
+ invalid('directory entries must be empty');
+ }
+ if (name === 'dataset.json' && originalSize > DATASET_PACKAGE_MAX_MANIFEST_BYTES) {
+ invalid('dataset.json exceeds the 25 MiB limit');
+ }
+ totalSize += originalSize;
+ if (totalSize > DATASET_PACKAGE_MAX_EXPANDED_BYTES)
+ invalid('expanded data exceeds the 32 MiB limit');
+ validateExtra(view, offset + 46 + nameLength, extraLength);
+ entries.push({
+ compressedSize,
+ crc: view.getUint32(offset + 16, true),
+ flags,
+ localOffset,
+ method,
+ name,
+ nameBytes,
+ originalSize,
+ });
+ offset += 46 + nameLength + extraLength + commentLength;
+ }
+ if (offset !== endOffset) invalid('central directory entry count does not match');
+ if (!names.has('dataset.json')) invalid('dataset.json must be at the archive root');
+ return { directoryOffset, entries: entries.sort((a, b) => a.localOffset - b.localOffset) };
+};
+
+const readPayload = (
+ bytes: Uint8Array,
+ view: DataView,
+ entry: ArchiveEntry,
+ directoryOffset: number,
+): { compressed: Uint8Array; end: number } => {
+ const offset = entry.localOffset;
+ requireRange(offset, 30, directoryOffset);
+ if (view.getUint32(offset, true) !== LOCAL_HEADER) invalid('invalid local file header');
+ if (
+ view.getUint16(offset + 6, true) !== entry.flags ||
+ view.getUint16(offset + 8, true) !== entry.method
+ ) {
+ invalid('local and central file headers disagree');
+ }
+ const nameLength = view.getUint16(offset + 26, true);
+ const extraLength = view.getUint16(offset + 28, true);
+ requireRange(offset + 30, nameLength + extraLength, directoryOffset);
+ const localName = bytes.subarray(offset + 30, offset + 30 + nameLength);
+ if (
+ localName.length !== entry.nameBytes.length ||
+ localName.some((value, i) => value !== entry.nameBytes[i])
+ ) {
+ invalid('local and central entry names disagree');
+ }
+ validateExtra(view, offset + 30 + nameLength, extraLength);
+ const start = offset + 30 + nameLength + extraLength;
+ requireRange(start, entry.compressedSize, directoryOffset);
+ let end = start + entry.compressedSize;
+ const expected = [entry.crc, entry.compressedSize, entry.originalSize];
+ for (let i = 0; i < expected.length; i++) {
+ const actual = view.getUint32(offset + 14 + i * 4, true);
+ if (actual !== expected[i] && (!(entry.flags & 8) || actual !== 0)) {
+ invalid('local and central entry sizes or checksum disagree');
+ }
+ }
+ if (entry.flags & 8) {
+ requireRange(end, 12, directoryOffset);
+ // The signature is optional, and a signature-free CRC can itself equal it.
+ const hasSignature =
+ end + 16 <= directoryOffset &&
+ view.getUint32(end, true) === DATA_DESCRIPTOR &&
+ expected.every((value, i) => view.getUint32(end + 4 + i * 4, true) === value);
+ if (hasSignature) end += 4;
+ if (expected.some((value, i) => view.getUint32(end + i * 4, true) !== value)) {
+ invalid('invalid data descriptor');
+ }
+ end += 12;
+ }
+ return { compressed: bytes.subarray(start, start + entry.compressedSize), end };
+};
+
+const crcTable = Uint32Array.from({ length: 256 }, (_, value) => {
+ let crc = value;
+ for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ (crc & 1 ? 0xedb8_8320 : 0);
+ return crc >>> 0;
+});
+
+const checksum = (bytes: Uint8Array) => {
+ let crc = 0xffff_ffff;
+ for (const value of bytes) crc = (crc >>> 8) ^ crcTable[(crc ^ value) & 0xff];
+ return (crc ^ 0xffff_ffff) >>> 0;
+};
+
+/**
+ * Read an in-memory package, without extracting paths or executing any archive content.
+ * The only data file is a root dataset.json. README.md, empty directories and macOS
+ * metadata are tolerated, but still validated and included in the resource budgets.
+ * The returned hash covers the exact manifest bytes, independent of ZIP timestamps.
+ */
+export const readDatasetPackageArchive = (
+ data: Uint8Array,
+): { manifest: unknown; sha256: string } => {
+ if (data.byteLength > DATASET_PACKAGE_MAX_COMPRESSED_BYTES) {
+ invalid('compressed data exceeds the 10 MiB limit');
+ }
+ if (data.byteLength < 22) invalid('missing or truncated end record');
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
+ const { directoryOffset, entries } = readDirectory(data, view);
+ let cursor = 0;
+ let expandedSize = 0;
+ let manifestBytes: Uint8Array | undefined;
+ for (const entry of entries) {
+ if (entry.localOffset !== cursor) invalid('unlisted, overlapping or prefixed archive data');
+ const { compressed, end } = readPayload(data, view, entry, directoryOffset);
+ cursor = end;
+ const maximum = Math.min(
+ entry.name === 'dataset.json'
+ ? DATASET_PACKAGE_MAX_MANIFEST_BYTES
+ : DATASET_PACKAGE_MAX_EXPANDED_BYTES,
+ DATASET_PACKAGE_MAX_EXPANDED_BYTES - expandedSize,
+ entry.originalSize,
+ );
+ let output: Uint8Array;
+ if (entry.method === 0) {
+ output = compressed;
+ } else {
+ try {
+ // The native decoder enforces this bound while inflating, including when
+ // the archive lies about its uncompressed size. Do not use unbounded unzip.
+ const result = inflateRawSync(compressed, {
+ info: true,
+ maxOutputLength: Math.max(1, maximum),
+ }) as unknown as { buffer: Uint8Array; engine: { bytesWritten: number } };
+ if (result.engine.bytesWritten !== compressed.byteLength)
+ invalid('trailing compressed data');
+ output = result.buffer;
+ } catch {
+ return invalid('invalid DEFLATE data or expanded size exceeds the limit');
+ }
+ }
+ if (output.byteLength > maximum || output.byteLength !== entry.originalSize) {
+ invalid('actual expanded size does not match the archive');
+ }
+ if (checksum(output) !== entry.crc) invalid('entry checksum does not match');
+ expandedSize += output.byteLength;
+ if (entry.name === 'dataset.json') manifestBytes = output;
+ }
+ if (cursor !== directoryOffset) invalid('unlisted archive data before the central directory');
+ if (!manifestBytes) return invalid('dataset.json must be at the archive root');
+ let manifest: unknown;
+ try {
+ manifest = JSON.parse(decode(manifestBytes, 'dataset.json'));
+ } catch {
+ return invalid('dataset.json must contain valid UTF-8 JSON');
+ }
+ return { manifest, sha256: createHash('sha256').update(manifestBytes).digest('hex') };
+};
diff --git a/apps/server/src/services/agentEvalMemory/README.md b/apps/server/src/services/agentEvalMemory/README.md
new file mode 100644
index 00000000000..932ed24d7ec
--- /dev/null
+++ b/apps/server/src/services/agentEvalMemory/README.md
@@ -0,0 +1,77 @@
+# Agent Eval Memory
+
+Isolated Memory for Agent Eval attempts. Every attempt (one test case in a run,
+or one pass\@k thread of it) has its own entries in `agent_eval_memories`: the
+case fixture seeded before the Agent runs, plus whatever the Agent writes. The
+Memory tool and the persona injection of an attempt read and write only those
+entries, so an attempt never touches the caller's own memories and attempts
+never see each other. Entries are evidence: nothing is deleted when the attempt
+ends; they go with their run.
+
+## Files
+
+| Path | Role |
+| -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
+| `index.ts` | `AgentEvalMemoryService`: `prepare` (seed once), `getPersonaDocument`, `runtime` (the tool), `snapshot` |
+| `search.ts` | `searchEvalMemory`: the account's hybrid Memory search run over an attempt's entries |
+| `runtime.ts` | `EvalMemoryRuntimeService`: the Memory tool surface (search, taxonomy, add, update / remove identity) |
+| `entries.ts` | Fixture β†’ drafts, the text each layer's vector is built from, the tag rule, the snapshot entry |
+| `where.ts` | `attemptWhere`: the rows of one attempt |
+| `embedding.ts` | The account's embedding model, billed to the caller as Memory usage |
+| `packages/database/src/schemas/agentEvalMemory.ts` | `agent_eval_memories` |
+| `packages/database/migrations/0199_lobe_bench_environments_and_memory.sql` | The table's BM25 index, the account Memory's definition (0093) over the headline columns and `payload` |
+| `apps/server/src/services/agentEvalRun/evalMemory.schema.ts` | zod validation of `environment.memory` before seeding |
+| `packages/database/src/utils/evalTopic.ts` | `notEvalTopic()`: keeps eval dialogue out of background Memory extraction |
+
+## One table, the account's search
+
+An entry is one row: the headline fields every layer shares (`title`,
+`summary`, `details`, `memoryCategory`, `memoryType`, `tags`), the layer's own
+part as the Memory tool received it (`payload`: `withPreference`,
+`withActivity`, …; a persona's narrative and tagline), one vector, and the
+attempt it belongs to. The vector is built from the one field of the layer the
+account's Memory embeds and searches (a preference's directives, an activity's
+narrative, a context's or identity's description); a persona has none.
+
+`searchEvalMemory` is the account's `UserMemoryQueryModel.searchMemory` with the
+rows coming from this table instead of `user_memories*`:
+
+- the same per-layer limits and the same overfetch;
+- the same two candidate passes per layer: the nearest entries by cosine
+ distance on the layer's vector (the averaged query embeddings), and the newest
+ entries whose words all match (`paradedb.match` in conjunction mode over the
+ headline columns and the layer's `payload` fields, through a BM25 index with
+ the tokenizer of 0093), or the filter-only pass when there is no query;
+- the same filters: category, status (activities, contexts), type, relationship
+ (identities), tags and labels (every requested one must be among the entry's
+ tags), time range (an entry's clock is its `capturedAt`; activities also by
+ `startsAt` / `endsAt`, identities by `episodicDate`);
+- `scoreHybridCandidates` from the product, with the same base signals;
+- the same result shape per layer, `meta.layers` and `meta.ranking` included.
+
+Experience memory is retired in the account's search and is never returned here
+either. Without pg_search (PGlite in tests; a deployment that chose another FTS
+provider) the queried lexical pass is skipped; the semantic and filter-only
+passes still run.
+
+## Lifecycle of one attempt
+
+1. **Prepare** (`trialMemory`, before the Agent runs and on resume): validate
+ `environment.memory`, embed the fixture, insert the rows with
+ `source = 'fixture'`, `capturedAt = seededAt` and the fixture's hash. A
+ resumed attempt keeps its rows and must bring the same fixture.
+2. **Run.** The reference (`run`, `topic`, optional `thread`) travels with the
+ eval context. The Memory tool (`serverRuntimes/memory.ts`) and the persona
+ injection (`operationPrep.ts`) resolve it against the attempt's topic and
+ thread and read and write only its rows. An eval run without a reference
+ fails instead of falling back to the caller.
+3. **Completion.** The attempt's Memory is captured as an `EvalMemorySnapshot`
+ (no vectors) on its result, so the run page can show the fixture beside what
+ the Agent wrote. Rows stay until the run is deleted.
+
+## Invariants
+
+- One attempt, one set of rows: `attemptWhere` is the only way to read them.
+- A removed identity stays as evidence (`removedReason`) and is hidden from
+ search and taxonomy.
+- Authentication, permissions and billing stay on the caller.
diff --git a/apps/server/src/services/agentEvalMemory/embedding.ts b/apps/server/src/services/agentEvalMemory/embedding.ts
new file mode 100644
index 00000000000..bc463b7c5b5
--- /dev/null
+++ b/apps/server/src/services/agentEvalMemory/embedding.ts
@@ -0,0 +1,121 @@
+import { DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM } from '@lobechat/const';
+import type { LobeChatDatabase } from '@lobechat/database';
+
+import { getServerDefaultFilesConfig } from '@/server/globalConfig';
+import {
+ initModelRuntimeFromDB,
+ initModelRuntimeWithUserPayload,
+} from '@/server/modules/ModelRuntime';
+import { embedUserMemoryTexts } from '@/server/services/memory/userMemory/embedding';
+import type { ToolExecutionMemoryEmbeddingRuntime } from '@/server/services/toolExecution/types';
+
+/** Embeds texts in one request; an empty text keeps its slot as `undefined`. */
+export type EvalMemoryEmbedder = (
+ texts: Array<string | null | undefined>,
+) => Promise<Array<number[] | undefined>>;
+
+/**
+ * The same embedding model the account's own Memory uses, billed to the
+ * caller as Memory usage. A server-owned runtime (a synthetic actor) wins
+ * when the tool execution context carries one.
+ */
+export const createEvalMemoryEmbedder = (options: {
+ db: LobeChatDatabase;
+ memoryEmbeddingRuntime?: ToolExecutionMemoryEmbeddingRuntime;
+ source: string;
+ userId: string;
+ workspaceId?: string;
+}): EvalMemoryEmbedder => {
+ return async (texts) => {
+ if (!texts.some((value) => typeof value === 'string' && value.trim())) {
+ return texts.map(() => undefined);
+ }
+ const defaults =
+ getServerDefaultFilesConfig().embeddingModel || DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM;
+ const model = options.memoryEmbeddingRuntime?.model ?? defaults.model;
+ const runtime = options.memoryEmbeddingRuntime
+ ? initModelRuntimeWithUserPayload(
+ options.memoryEmbeddingRuntime.provider,
+ options.memoryEmbeddingRuntime.payload,
+ { userId: options.userId },
+ )
+ : await initModelRuntimeFromDB(
+ options.db,
+ options.userId,
+ defaults.provider,
+ options.workspaceId,
+ );
+ return embedUserMemoryTexts({
+ input: texts,
+ model,
+ runtime,
+ source: options.source,
+ userId: options.userId,
+ });
+ };
+};
+
+const EMBED_ATTEMPTS = 3;
+const EMBED_RETRY_DELAY_MS = 500;
+const isTransientFailure = (message?: string) =>
+ /connection error|econnreset|etimedout|socket hang up|fetch failed|terminated|timed? ?out|\b(?:429|502|503|504)\b/i.test(
+ message ?? '',
+ );
+
+/**
+ * Model runtimes often reject with a plain payload (`{ errorType, error }`),
+ * not an Error; its text must survive into retry decisions and logs.
+ */
+const describeFailure = (error: unknown): string => {
+ if (error instanceof Error) return error.message;
+ if (typeof error === 'string') return error;
+ try {
+ return JSON.stringify(error) ?? String(error);
+ } catch {
+ return String(error);
+ }
+};
+
+/** A dropped connection to the embedding provider must not fail an attempt before the Agent runs. */
+export const embedWithRetry: (
+ embed: EvalMemoryEmbedder,
+ texts: Array<string | null | undefined>,
+) => Promise<Array<number[] | undefined>> = async (embed, texts) => {
+ for (let attempt = 1; ; attempt++) {
+ try {
+ return await embed(texts);
+ } catch (error) {
+ const message = describeFailure(error);
+ if (attempt >= EMBED_ATTEMPTS || !isTransientFailure(message)) {
+ throw new Error(`Eval Memory embedding failed: ${message}`, { cause: error });
+ }
+ await new Promise((resolve) => setTimeout(resolve, EMBED_RETRY_DELAY_MS * attempt));
+ }
+ }
+};
+
+/**
+ * Embeds with the account's model when it has a usable one, else takes the
+ * simplified path. A dropped connection is retried and then still fails the
+ * call: that is an outage, not a missing model. Any other failure (no key, no
+ * embedding model, a refused request) means the account cannot embed, so the
+ * texts get no vectors, and Memory search ranks an attempt's entries without
+ * them (`searchEvalMemory`). Once refused, the embedder stops asking.
+ */
+export const embedOrSkip = (embed: EvalMemoryEmbedder): EvalMemoryEmbedder => {
+ let unavailable = false;
+ return async (texts) => {
+ if (unavailable) return texts.map(() => undefined);
+ try {
+ return await embedWithRetry(embed, texts);
+ } catch (error) {
+ const message = describeFailure(error);
+ if (isTransientFailure(message)) throw error;
+ unavailable = true;
+ console.warn('[eval-memory] no usable embedding model, using simplified Memory search', {
+ reason: message.slice(0, 200),
+ });
+ return texts.map(() => undefined);
+ }
+ };
+};
diff --git a/apps/server/src/services/agentEvalMemory/entries.ts b/apps/server/src/services/agentEvalMemory/entries.ts
new file mode 100644
index 00000000000..8eb2a4f3e78
--- /dev/null
+++ b/apps/server/src/services/agentEvalMemory/entries.ts
@@ -0,0 +1,115 @@
+import type {
+ AgentEvalMemoryItem,
+ EvalMemoryEntry,
+ EvalMemoryFixture,
+ EvalMemoryLayer,
+} from '@lobechat/types';
+
+/** What a Memory entry is made of before it has an id, a clock and an embedding. */
+export interface EvalMemoryDraft {
+ details?: string | null;
+ layer: EvalMemoryLayer;
+ memoryCategory?: string | null;
+ memoryType?: string | null;
+ payload: Record<string, unknown>;
+ summary?: string | null;
+ tags?: string[] | null;
+ title?: string | null;
+}
+
+type Item = Record<string, any>;
+
+/** A Memory tool item (`title`, `summary`, … plus its `withX` part) as a draft. */
+export const draftOf = (
+ layer: EvalMemoryLayer,
+ item: Item,
+ payloadKey: string,
+): EvalMemoryDraft => ({
+ details: item.details ?? null,
+ layer,
+ memoryCategory: item.memoryCategory ?? null,
+ memoryType: item.memoryType ?? null,
+ payload: (item[payloadKey] ?? {}) as Record<string, unknown>,
+ summary: item.summary ?? null,
+ tags: Array.isArray(item.tags) ? item.tags : null,
+ title: item.title ?? null,
+});
+
+/** The case fixture as drafts: its persona first, then every layer's items in order. */
+export const fixtureDrafts = (fixture: EvalMemoryFixture): EvalMemoryDraft[] => [
+ ...(fixture.persona
+ ? [
+ {
+ layer: 'persona' as const,
+ payload: { narrative: fixture.persona.narrative, tagline: fixture.persona.tagline },
+ summary: fixture.persona.narrative,
+ title: fixture.persona.tagline ?? null,
+ },
+ ]
+ : []),
+ ...(fixture.preferences ?? []).map((item) => draftOf('preference', item, 'withPreference')),
+ ...(fixture.contexts ?? []).map((item) => draftOf('context', item, 'withContext')),
+ ...(fixture.activities ?? []).map((item) => draftOf('activity', item, 'withActivity')),
+ ...(fixture.experiences ?? []).map((item) => draftOf('experience', item, 'withExperience')),
+ ...(fixture.identities ?? []).map((item) => draftOf('identity', item, 'withIdentity')),
+];
+
+const text = (value: unknown): string | undefined =>
+ typeof value === 'string' && value.trim() ? value : undefined;
+
+/**
+ * The text an entry's vector is built from: the one field of its layer the
+ * account's Memory embeds and searches (a preference's directives, an
+ * activity's narrative, a context's or identity's description), so the same
+ * query ranks the entry where the account's search would. A persona has no
+ * vector; it is injected, never searched.
+ */
+export const semanticText = (
+ draft: Pick<EvalMemoryDraft, 'layer' | 'payload'>,
+): string | undefined => {
+ const p = draft.payload as Item;
+ switch (draft.layer) {
+ case 'preference': {
+ return text(p.conclusionDirectives);
+ }
+ case 'activity': {
+ return text(p.narrative);
+ }
+ case 'context':
+ case 'identity': {
+ return text(p.description);
+ }
+ case 'experience': {
+ return text(p.situation);
+ }
+ default: {
+ return undefined;
+ }
+ }
+};
+
+const stringList = (value: unknown): string[] | undefined =>
+ Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : undefined;
+
+/**
+ * The tags an entry is filtered and ranked by. The account's Memory stores an
+ * activity's `withActivity.tags` (when given) on both its rows and drops the
+ * item's own tags; every other layer keeps the item's tags.
+ */
+export const tagsOf = (row: Pick<AgentEvalMemoryItem, 'layer' | 'payload' | 'tags'>): string[] =>
+ (row.layer === 'activity' ? stringList((row.payload as Item).tags) : undefined) ?? row.tags ?? [];
+
+export const toEntry = (row: AgentEvalMemoryItem): EvalMemoryEntry => ({
+ capturedAt: row.capturedAt.toISOString(),
+ details: row.details,
+ id: row.id,
+ layer: row.layer,
+ memoryCategory: row.memoryCategory,
+ memoryType: row.memoryType,
+ payload: row.payload,
+ removedReason: row.removedReason,
+ source: row.source,
+ summary: row.summary,
+ tags: row.tags,
+ title: row.title,
+});
diff --git a/apps/server/src/services/agentEvalMemory/index.test.ts b/apps/server/src/services/agentEvalMemory/index.test.ts
new file mode 100644
index 00000000000..2089cc7148f
--- /dev/null
+++ b/apps/server/src/services/agentEvalMemory/index.test.ts
@@ -0,0 +1,808 @@
+// @vitest-environment node
+import type { EvalMemoryFixture } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '@/database/core/getTestDB';
+import { AgentEvalRunTopicModel } from '@/database/models/agentEval';
+import { UserMemoryPreferenceModel } from '@/database/models/userMemory/preference';
+import {
+ agentEvalMemories,
+ agentEvalRuns,
+ agentEvalRunTopics,
+ messages,
+ threads,
+ topics,
+ users,
+ workspaces,
+} from '@/database/schemas';
+import { cleanupDB, setupEvalChain, userId } from '@/server/services/agentEvalRun/__tests__/_setup';
+import { getEvalAttemptId } from '@/server/services/agentEvalRun/utils';
+import { memoryRuntime } from '@/server/services/toolExecution/serverRuntimes/memory';
+
+import { AgentEvalMemoryService } from './index';
+
+const mocks = vi.hoisted(() => ({
+ embed: vi.fn(),
+ initModelRuntimeFromDB: vi.fn<(serverDB: unknown, actor: string) => Promise<unknown>>(
+ async () => ({}),
+ ),
+}));
+
+vi.mock('@/server/globalConfig', () => ({
+ getServerDefaultFilesConfig: () => ({
+ embeddingModel: { model: 'test-embedding', provider: 'test' },
+ }),
+}));
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: mocks.initModelRuntimeFromDB,
+ initModelRuntimeWithUserPayload: vi.fn(),
+}));
+vi.mock('@/server/services/memory/userMemory/embedding', () => ({
+ embedUserMemoryTexts: mocks.embed,
+}));
+vi.mock('@/server/services/agentSignal/procedure', () => ({
+ emitToolOutcomeSafely: vi.fn(),
+ resolveToolOutcomeScope: vi.fn(),
+}));
+vi.mock('@/server/services/agentSignal/store/adapters/redis/policyStateStore', () => ({
+ redisPolicyStateStore: {},
+}));
+vi.mock('@/server/services/ftsSearch', () => ({ createFtsSearchRepo: vi.fn() }));
+
+const db = await getTestDB();
+
+/** A bag-of-words embedding: texts that share words are close, so ranking is lexical. */
+const vectorOf = (text: string) => {
+ const vector = Array.from({ length: 1024 }, () => 0);
+ for (const token of text.toLowerCase().split(/[^\p{L}\p{N}]+/u)) {
+ if (token.length < 2) continue;
+ let hash = 0;
+ for (const char of token) hash = (hash * 31 + (char.codePointAt(0) ?? 0)) % 1024;
+ vector[hash] += 1;
+ }
+ return vector;
+};
+
+const preference = (title: string, directive: string) => ({
+ details: directive,
+ memoryCategory: 'health',
+ memoryType: 'preference',
+ sourceIds: [],
+ summary: title,
+ tags: ['food'],
+ title,
+ withPreference: {
+ appContext: null,
+ conclusionDirectives: directive,
+ extractedLabels: [],
+ extractedScopes: [],
+ originContext: null,
+ scorePriority: 1,
+ suggestions: [],
+ type: 'health',
+ },
+});
+
+const fixture: EvalMemoryFixture = {
+ persona: { narrative: 'User is allergic to shellfish.', tagline: 'Food restrictions' },
+ preferences: [preference('No shellfish', 'Do not recommend shellfish.')],
+ seededAt: '2024-05-01T12:00:00.000Z',
+};
+
+/** One entry per remaining layer, layered on the persona + preference fixture. */
+const nativeFixture: EvalMemoryFixture = {
+ ...fixture,
+ activities: [
+ {
+ details: 'Reviewed the latest allergy panel results.',
+ memoryCategory: 'health',
+ memoryType: 'activity',
+ sourceIds: [],
+ summary: 'Allergist appointment',
+ tags: ['appointment'],
+ title: 'Allergist follow-up',
+ withActivity: {
+ associatedLocations: [{ name: 'City Allergy Clinic', type: 'clinic' }],
+ associatedObjects: [],
+ associatedSubjects: [{ name: 'Dr. Kim', type: 'person' }],
+ endsAt: '2024-05-03T15:00:00Z',
+ feedback: 'Reassuring visit.',
+ narrative: 'User reviewed allergy panel results with Dr. Kim.',
+ notes: null,
+ startsAt: '2024-05-03T14:00:00Z',
+ status: 'completed',
+ tags: ['health'],
+ timezone: 'UTC',
+ type: 'appointment',
+ },
+ },
+ ],
+ contexts: [
+ {
+ details: 'Planning a shellfish-free wedding menu with the caterer.',
+ memoryCategory: 'personal',
+ memoryType: 'context',
+ sourceIds: [],
+ summary: 'Wedding menu planning',
+ tags: ['wedding'],
+ title: 'Wedding catering',
+ withContext: {
+ associatedObjects: [{ extra: null, name: 'Catering contract', type: 'item' }],
+ associatedSubjects: [{ extra: null, name: 'Caterer', type: 'person' }],
+ currentStatus: 'ongoing',
+ description: 'The user is finalizing a shellfish-free menu for their wedding.',
+ labels: ['wedding', 'menu'],
+ scoreImpact: 0.8,
+ scoreUrgency: 0.6,
+ title: 'Wedding menu',
+ type: 'project',
+ },
+ },
+ ],
+ experiences: [
+ {
+ details: 'Reacted to hidden shrimp paste in a sauce.',
+ memoryCategory: 'health',
+ memoryType: 'other',
+ sourceIds: [],
+ summary: 'Learned to ask about sauces',
+ tags: ['dining'],
+ title: 'Hidden shellfish in sauces',
+ withExperience: {
+ action: 'Asked the kitchen for ingredient lists.',
+ keyLearning: 'Always ask about sauce bases.',
+ knowledgeValueScore: 0.7,
+ labels: ['allergy'],
+ possibleOutcome: 'Fewer accidental exposures.',
+ problemSolvingScore: 0.8,
+ reasoning: 'Shrimp paste is a common hidden ingredient.',
+ scoreConfidence: 0.9,
+ situation: 'Had a reaction at a Thai restaurant.',
+ type: 'lesson',
+ },
+ },
+ ],
+ identities: [
+ {
+ details: null,
+ memoryCategory: 'professional',
+ memoryType: 'fact',
+ summary: 'User works as a pastry chef.',
+ tags: ['career'],
+ title: 'Pastry chef',
+ withIdentity: {
+ description: 'Runs the dessert station at a bistro.',
+ episodicDate: null,
+ extractedLabels: ['culinary'],
+ relationship: 'self',
+ role: 'pastry chef',
+ scoreConfidence: 0.9,
+ sourceEvidence: null,
+ sourceIds: [],
+ type: 'professional',
+ },
+ },
+ ],
+};
+
+const trial = async () => {
+ const chain = await setupEvalChain({});
+ return { runId: chain.run.id, testCaseId: chain.testCase.id, topicId: chain.topic.id };
+};
+
+/** Another attempt of the same run and case: its own topic, so its own Memory. */
+const anotherAttempt = async (of: { runId: string; testCaseId: string }) => {
+ const [topic] = await db
+ .insert(topics)
+ .values({ title: 'Eval Topic 2', trigger: 'eval', userId })
+ .returning();
+ await new AgentEvalRunTopicModel(db, userId).batchCreate([
+ { runId: of.runId, testCaseId: of.testCaseId, topicId: topic.id },
+ ]);
+ return { ...of, topicId: topic.id };
+};
+
+const runtimeFor = (
+ reference: Awaited<ReturnType<AgentEvalMemoryService['prepare']>>,
+ topicId: string,
+ extra: Record<string, unknown> = {},
+) =>
+ memoryRuntime.factory({
+ evalMemory: reference,
+ isEval: true,
+ serverDB: db,
+ toolManifestMap: {},
+ topicId,
+ userId,
+ ...extra,
+ } as any);
+
+type SearchState = {
+ activities: Record<string, any>[];
+ contexts: Record<string, any>[];
+ experiences: Record<string, any>[];
+ identities?: Record<string, any>[];
+ preferences: Record<string, any>[];
+};
+
+describe('AgentEvalMemoryService', () => {
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ mocks.embed.mockImplementation(async ({ input }: { input: Array<string | null | undefined> }) =>
+ input.map((text) => (text ? vectorOf(text) : undefined)),
+ );
+ await cleanupDB();
+ });
+
+ it("seeds the fixture as the attempt's own entries and finds them through the Memory tool", async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ const reference = await service.prepare({ ...params, fixture: nativeFixture });
+ expect(reference).toEqual({
+ fixtureHash: expect.any(String),
+ runId: params.runId,
+ topicId: params.topicId,
+ });
+
+ // Nothing but the caller exists as a user; the caller's own Memory is untouched.
+ expect(await db.select({ id: users.id }).from(users)).toEqual([{ id: userId }]);
+ expect(await new UserMemoryPreferenceModel(db, userId).query()).toHaveLength(0);
+
+ const runtime = await runtimeFor(reference, params.topicId);
+ const read = await runtime.searchUserMemory({ effort: 'high', queries: ['shellfish'] });
+ expect(read.success).toBe(true);
+ const state = read.state as SearchState;
+ expect(state.preferences).toHaveLength(1);
+ expect(state.preferences[0]).toMatchObject({
+ conclusionDirectives: 'Do not recommend shellfish.',
+ createdAt: new Date('2024-05-01T12:00:00.000Z'),
+ // A preference's type is its memory type, as the account's Memory stores it.
+ type: 'preference',
+ });
+ expect(state.contexts[0]).toMatchObject({ currentStatus: 'ongoing', title: 'Wedding menu' });
+ expect(state.activities[0]).toMatchObject({
+ startsAt: new Date('2024-05-03T14:00:00Z'),
+ status: 'completed',
+ });
+ // Experience memory is retired: the account's search never returns it either.
+ expect(state.experiences).toEqual([]);
+ expect(state.identities?.[0]).toMatchObject({ role: 'pastry chef', relationship: 'self' });
+ expect(read.content).toContain('Do not recommend shellfish.');
+
+ const snapshot = await service.snapshot(params);
+ expect(snapshot.fixtureHash).toBe(reference.fixtureHash);
+ expect(snapshot.entries.map((e) => e.layer)).toEqual([
+ 'persona',
+ 'preference',
+ 'context',
+ 'activity',
+ 'experience',
+ 'identity',
+ ]);
+ expect(snapshot.entries.every((e) => e.source === 'fixture')).toBe(true);
+ expect(snapshot.entries.every((e) => e.capturedAt === '2024-05-01T12:00:00.000Z')).toBe(true);
+ // Vectors never leave the table.
+ expect(JSON.stringify(snapshot)).not.toContain('embedding');
+ });
+
+ it("reads the persona from the fixture and refuses another trial's reference", async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ const reference = await service.prepare({ ...params, fixture });
+ expect(await service.getPersonaDocument(reference, { topicId: params.topicId })).toEqual({
+ persona: 'User is allergic to shellfish.',
+ tagline: 'Food restrictions',
+ version: 0,
+ });
+ const [other] = await db
+ .insert(topics)
+ .values({ title: 'Other', trigger: 'eval', userId })
+ .returning();
+ await expect(service.getPersonaDocument(reference, { topicId: other.id })).rejects.toThrow(
+ 'another trial',
+ );
+ await expect(runtimeFor(reference, other.id)).rejects.toThrow('another trial');
+ // An eval attempt without a reference must not fall back to the caller's Memory.
+ await expect(
+ memoryRuntime.factory({ isEval: true, serverDB: db, toolManifestMap: {}, userId } as any),
+ ).rejects.toThrow('attempt reference');
+ });
+
+ it('keeps what the Agent writes inside its own attempt', async () => {
+ const a = await trial();
+ const b = await anotherAttempt(a);
+ const service = new AgentEvalMemoryService(db, userId);
+ const refA = await service.prepare({ ...a, fixture: {} });
+ const refB = await service.prepare({ ...b, fixture: {} });
+ const runtimeA = await runtimeFor(refA, a.topicId);
+ const written = await runtimeA.addPreferenceMemory(preference('Tea', 'Prefers oolong tea.'));
+ expect(written.success).toBe(true);
+ expect((await runtimeA.searchUserMemory({ queries: ['oolong tea'] })).state).toMatchObject({
+ preferences: [{ conclusionDirectives: 'Prefers oolong tea.' }],
+ });
+ const runtimeB = await runtimeFor(refB, b.topicId);
+ expect((await runtimeB.searchUserMemory({ queries: ['oolong tea'] })).state).toMatchObject({
+ preferences: [],
+ });
+ expect((await service.snapshot(a)).entries).toMatchObject([
+ { layer: 'preference', source: 'agent', title: 'Tea' },
+ ]);
+ expect((await service.snapshot(b)).entries).toEqual([]);
+ expect(await new UserMemoryPreferenceModel(db, userId).query()).toHaveLength(0);
+ });
+
+ it("gives each pass@k thread its own Memory and lets a sub-agent thread use its topic's", async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ const { threads } = await import('@/database/schemas');
+ const [thread1] = (await db
+ .insert(threads)
+ .values({ title: 't1', topicId: params.topicId, type: 'eval', userId } as any)
+ .returning()) as Array<{ id: string }>;
+ const [thread2] = (await db
+ .insert(threads)
+ .values({ title: 't2', topicId: params.topicId, type: 'eval', userId } as any)
+ .returning()) as Array<{ id: string }>;
+ const ref1 = await service.prepare({ ...params, fixture, threadId: thread1.id });
+ const ref2 = await service.prepare({ ...params, fixture: {}, threadId: thread2.id });
+ const runtime1 = await runtimeFor(ref1, params.topicId, { threadId: thread1.id });
+ expect((await runtime1.searchUserMemory({ queries: ['shellfish'] })).state).toMatchObject({
+ preferences: [{ conclusionDirectives: 'Do not recommend shellfish.' }],
+ });
+ const runtime2 = await runtimeFor(ref2, params.topicId, { threadId: thread2.id });
+ expect((await runtime2.searchUserMemory({ queries: ['shellfish'] })).state).toMatchObject({
+ preferences: [],
+ });
+ // A thread reference resolves only from its own thread.
+ await expect(runtimeFor(ref1, params.topicId, { threadId: thread2.id })).rejects.toThrow(
+ 'another attempt',
+ );
+ // A topic-level attempt is shared with the isolation threads its sub-agents run in.
+ const topicRef = await service.prepare({ ...params, fixture });
+ const subAgent = await runtimeFor(topicRef, params.topicId, { threadId: thread1.id });
+ expect((await subAgent.searchUserMemory({ queries: ['shellfish'] })).state).toMatchObject({
+ preferences: [{ conclusionDirectives: 'Do not recommend shellfish.' }],
+ });
+ });
+
+ it("lets the sub-agents a pass@k attempt spawned use that attempt's Memory, never a sibling's", async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ const thread = (title: string, extra: Record<string, unknown> = {}) =>
+ db
+ .insert(threads)
+ .values({ title, topicId: params.topicId, type: 'eval', userId, ...extra } as any)
+ .returning()
+ .then(([row]) => row as { id: string });
+ // A sub-agent runs in an isolation thread hanging off the tool message that started it.
+ const spawnFrom = async (parentThreadId: string, title: string) => {
+ const [message] = (await db
+ .insert(messages)
+ .values({ role: 'tool', threadId: parentThreadId, topicId: params.topicId, userId } as any)
+ .returning()) as Array<{ id: string }>;
+ return thread(title, { sourceMessageId: message.id, type: 'isolation' });
+ };
+ const attempt = await thread('attempt');
+ const sibling = await thread('sibling');
+ const reference = await service.prepare({ ...params, fixture, threadId: attempt.id });
+ await service.prepare({ ...params, fixture: {}, threadId: sibling.id });
+
+ const subAgent = await spawnFrom(attempt.id, 'sub-agent');
+ const nested = await spawnFrom(subAgent.id, 'nested sub-agent');
+ for (const threadId of [subAgent.id, nested.id]) {
+ const runtime = await runtimeFor(reference, params.topicId, { threadId });
+ expect((await runtime.searchUserMemory({ queries: ['shellfish'] })).state).toMatchObject({
+ preferences: [{ conclusionDirectives: 'Do not recommend shellfish.' }],
+ });
+ }
+
+ const siblingSubAgent = await spawnFrom(sibling.id, "sibling's sub-agent");
+ await expect(
+ runtimeFor(reference, params.topicId, { threadId: siblingSubAgent.id }),
+ ).rejects.toThrow('another attempt');
+ // An ordinary thread of the topic is not a sub-agent of the attempt either.
+ await expect(runtimeFor(reference, params.topicId, { threadId: sibling.id })).rejects.toThrow(
+ 'another attempt',
+ );
+ });
+
+ it('keeps retained deleted-thread memories out of the parent and live sibling attempts', async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ const [deletedThread, liveThread] = await db
+ .insert(threads)
+ .values([
+ { title: 'Deleted attempt', topicId: params.topicId, type: 'eval', userId },
+ { title: 'Live attempt', topicId: params.topicId, type: 'eval', userId },
+ ])
+ .returning();
+ const parentRef = await service.prepare({
+ ...params,
+ fixture: { preferences: [preference('Parent tea', 'Parent tea only.')] },
+ });
+ const deletedRef = await service.prepare({
+ ...params,
+ fixture: { preferences: [preference('Deleted tea', 'Deleted tea only.')] },
+ threadId: deletedThread.id,
+ });
+ const siblingParams = { ...params, threadId: liveThread.id };
+ const siblingRef = await service.prepare({
+ ...siblingParams,
+ fixture: { preferences: [preference('Sibling tea', 'Sibling tea only.')] },
+ });
+ const stored = await db.select().from(agentEvalMemories);
+ expect(stored.map((row) => row.attemptId).sort()).toEqual(
+ [parentRef, deletedRef, siblingRef].map(getEvalAttemptId).sort(),
+ );
+ const retained = stored.find((row) => row.threadId === deletedThread.id)!;
+
+ await db.delete(threads).where(eq(threads.id, deletedThread.id));
+ expect(
+ await db.select().from(agentEvalMemories).where(eq(agentEvalMemories.id, retained.id)),
+ ).toEqual([{ ...retained, threadId: null }]);
+ await expect(service.snapshot({ ...params, threadId: deletedThread.id })).rejects.toThrow(
+ 'Eval Memory thread does not belong to this trial',
+ );
+
+ const parentRuntime = await runtimeFor(parentRef, params.topicId);
+ expect
+ .soft((await service.snapshot(params)).entries.map((entry) => entry.title))
+ .toEqual(['Parent tea']);
+ expect
+ .soft((await parentRuntime.searchUserMemory({ queries: ['tea'] })).state)
+ .toMatchObject({ preferences: [{ conclusionDirectives: 'Parent tea only.' }] });
+ expect
+ .soft((await parentRuntime.queryTaxonomyOptions({ include: ['categories'] })).state)
+ .toMatchObject({ categories: [{ count: 1, layers: ['preference'], value: 'health' }] });
+
+ const siblingRuntime = await runtimeFor(siblingRef, params.topicId, {
+ threadId: liveThread.id,
+ });
+ expect((await service.snapshot(siblingParams)).entries.map((entry) => entry.title)).toEqual([
+ 'Sibling tea',
+ ]);
+ expect((await siblingRuntime.searchUserMemory({ queries: ['tea'] })).state).toMatchObject({
+ preferences: [{ conclusionDirectives: 'Sibling tea only.' }],
+ });
+ expect(
+ (await siblingRuntime.queryTaxonomyOptions({ include: ['categories'] })).state,
+ ).toMatchObject({ categories: [{ count: 1, layers: ['preference'], value: 'health' }] });
+ });
+
+ it('honors read-only mode', async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ const reference = await service.prepare({ ...params, fixture: {} });
+ const readOnly = await runtimeFor(reference, params.topicId, {
+ memoryToolPermission: 'read-only',
+ });
+ expect(await readOnly.addPreferenceMemory(preference('Tea', 'Prefers tea.'))).toMatchObject({
+ success: false,
+ });
+ expect((await service.snapshot(params)).entries).toEqual([]);
+ });
+
+ it('preserves writes on resume and rejects a changed fixture', async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ const reference = await service.prepare({ ...params, fixture });
+ const runtime = await runtimeFor(reference, params.topicId);
+ await runtime.addPreferenceMemory(preference('Tea', 'Prefers oolong tea.'));
+ expect(await service.prepare({ ...params, fixture })).toEqual(reference);
+ expect((await service.snapshot(params)).entries).toHaveLength(3);
+ await expect(
+ service.prepare({ ...params, fixture: { ...fixture, persona: undefined } }),
+ ).rejects.toThrow('Cannot change Memory fixture');
+ });
+
+ it('keeps empty fixture initialization durable across resume and agent writes', async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ const reference = await service.prepare({ ...params, fixture: {} });
+ const runtime = await runtimeFor(reference, params.topicId);
+ await runtime.addPreferenceMemory(preference('Tea', 'Prefers oolong tea.'));
+ await db.update(agentEvalRunTopics).set({ evalResult: null });
+
+ expect(await service.prepare({ ...params, fixture: {}, resume: true })).toEqual(reference);
+ await expect(service.prepare({ ...params, fixture })).rejects.toThrow(
+ 'Cannot change Memory fixture',
+ );
+ expect((await service.snapshot(params)).entries).toMatchObject([
+ { source: 'agent', title: 'Tea' },
+ ]);
+ expect((await runtime.queryTaxonomyOptions({ include: ['categories'] })).state).toMatchObject({
+ categories: [{ count: 1, layers: ['preference'], value: 'health' }],
+ });
+ expect(
+ await service.getPersonaDocument(reference, { topicId: params.topicId }),
+ ).toBeUndefined();
+ });
+
+ it('resumes known legacy fixture rows but refuses to guess an unrecorded empty fixture', async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ await expect(service.prepare({ ...params, fixture: {}, resume: true })).rejects.toThrow(
+ 'rerun this case instead of resuming',
+ );
+ expect(await service.snapshot(params)).toMatchObject({ entries: [], fixtureHash: null });
+ const reference = await service.prepare({ ...params, fixture });
+ // A prior release stored provenance only on nonempty fixture rows.
+ await db.update(topics).set({ metadata: null }).where(eq(topics.id, params.topicId));
+ expect(await service.prepare({ ...params, fixture, resume: true })).toEqual(reference);
+ expect((await service.snapshot(params)).entries).toHaveLength(2);
+ expect(mocks.embed).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps agent-written evidence with explicitly unknown legacy fixture provenance', async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ const reference = await service.prepare({ ...params, fixture: {} });
+ await (
+ await runtimeFor(reference, params.topicId)
+ ).addPreferenceMemory(preference('Tea', 'Prefers oolong tea.'));
+ // Simulate an attempt prepared before empty fixtures had a marker.
+ await db.update(topics).set({ metadata: null }).where(eq(topics.id, params.topicId));
+ expect(await service.snapshot(params)).toMatchObject({
+ entries: [{ source: 'agent', title: 'Tea' }],
+ fixtureHash: null,
+ });
+ await expect(service.prepare({ ...params, fixture: {}, resume: true })).rejects.toThrow(
+ 'rerun this case instead of resuming',
+ );
+ });
+
+ it('lets workspace collaborators share the stable attempt owner across all Memory operations', async () => {
+ const params = await trial();
+ const collaborator = 'eval-memory-collaborator';
+ const workspaceId = 'eval-memory-workspace';
+ await db.insert(users).values({ id: collaborator });
+ await db.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Eval workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ await db.update(agentEvalRuns).set({ workspaceId }).where(eq(agentEvalRuns.id, params.runId));
+ await db.update(agentEvalRunTopics).set({ workspaceId });
+ await db.update(topics).set({ workspaceId, metadata: { evalHistoryTailMessageId: 'keep' } });
+ const [thread] = await db
+ .insert(threads)
+ .values({
+ topicId: params.topicId,
+ type: 'eval',
+ userId: collaborator,
+ workspaceId,
+ })
+ .returning();
+ const target = { ...params, threadId: thread.id };
+ const service = new AgentEvalMemoryService(db, collaborator, workspaceId);
+ const reference = await service.prepare({ ...target, fixture });
+ const runtime = await runtimeFor(reference, params.topicId, {
+ threadId: thread.id,
+ userId: collaborator,
+ workspaceId,
+ });
+ expect((await runtime.searchUserMemory({ queries: ['shellfish'] })).state).toMatchObject({
+ preferences: [{ conclusionDirectives: 'Do not recommend shellfish.' }],
+ });
+ expect(
+ await service.getPersonaDocument(reference, { topicId: params.topicId, threadId: thread.id }),
+ ).toMatchObject({ persona: 'User is allergic to shellfish.' });
+ await runtime.addPreferenceMemory(preference('Tea', 'Prefers oolong tea.'));
+ expect(
+ await new AgentEvalMemoryService(db, userId, workspaceId).prepare({ ...target, fixture }),
+ ).toEqual(reference);
+ expect((await service.snapshot(target)).entries).toHaveLength(3);
+ expect((await db.select().from(agentEvalMemories)).every((row) => row.userId === userId)).toBe(
+ true,
+ );
+ expect(mocks.initModelRuntimeFromDB.mock.calls.every((call) => call[1] === userId)).toBe(true);
+ expect((await db.select().from(topics))[0].metadata?.evalHistoryTailMessageId).toBe('keep');
+ await expect(
+ new AgentEvalMemoryService(db, collaborator, 'another-workspace').prepare({
+ ...target,
+ fixture,
+ }),
+ ).rejects.toThrow('not found');
+ await expect(new AgentEvalMemoryService(db, collaborator).snapshot(target)).rejects.toThrow(
+ 'not found',
+ );
+ });
+
+ it("uses the new topic creator when a collaborator reruns another member's run", async () => {
+ const params = await trial();
+ const collaborator = 'eval-memory-rerun-collaborator';
+ const workspaceId = 'eval-memory-rerun-workspace';
+ await db.insert(users).values({ id: collaborator });
+ await db.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Eval workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ await db.update(agentEvalRuns).set({ workspaceId }).where(eq(agentEvalRuns.id, params.runId));
+ await db.update(agentEvalRunTopics).set({ userId: collaborator, workspaceId });
+ await db.update(topics).set({ userId: collaborator, workspaceId });
+ const service = new AgentEvalMemoryService(db, userId, workspaceId);
+ await service.prepare({ ...params, fixture });
+ expect((await service.snapshot(params)).entries).toHaveLength(2);
+ expect(
+ (await db.select().from(agentEvalMemories)).every((row) => row.userId === collaborator),
+ ).toBe(true);
+ expect(mocks.initModelRuntimeFromDB.mock.calls.every((call) => call[1] === collaborator)).toBe(
+ true,
+ );
+ });
+
+ it('updates and removes identities, keeping removed ones as evidence', async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ const reference = await service.prepare({ ...params, fixture: nativeFixture });
+ const runtime = await runtimeFor(reference, params.topicId);
+ const identity = (await service.snapshot(params)).entries.find((e) => e.layer === 'identity')!;
+ const updated = await runtime.updateIdentityMemory({
+ id: identity.id,
+ mergeStrategy: 'merge',
+ set: { withIdentity: { role: 'head pastry chef' } },
+ } as any);
+ expect(updated.success).toBe(true);
+ const search = (await runtime.searchUserMemory({ queries: ['pastry chef'] }))
+ .state as SearchState;
+ expect(search.identities?.[0]).toMatchObject({
+ description: 'Runs the dessert station at a bistro.',
+ role: 'head pastry chef',
+ });
+ expect(
+ await runtime.removeIdentityMemory({ id: identity.id, reason: 'Changed jobs.' }),
+ ).toMatchObject({ success: true });
+ expect(
+ ((await runtime.searchUserMemory({ queries: ['pastry chef'] })).state as SearchState)
+ .identities,
+ ).toEqual([]);
+ expect(
+ (await service.snapshot(params)).entries.find((e) => e.id === identity.id),
+ ).toMatchObject({
+ removedReason: 'Changed jobs.',
+ });
+ expect(await runtime.removeIdentityMemory({ id: 'missing', reason: 'x' })).toMatchObject({
+ success: false,
+ });
+ });
+
+ it('filters by facets and time, and lists the taxonomy of what the attempt holds', async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ const reference = await service.prepare({ ...params, fixture: nativeFixture });
+ const runtime = await runtimeFor(reference, params.topicId);
+ const before = (
+ await runtime.searchUserMemory({
+ effort: 'high',
+ timeRange: { end: new Date('2024-04-30T00:00:00Z') },
+ })
+ ).state as SearchState;
+ expect(before.preferences).toEqual([]);
+ const after = (
+ await runtime.searchUserMemory({
+ effort: 'high',
+ timeRange: { start: new Date('2024-04-30T00:00:00Z') },
+ })
+ ).state as SearchState;
+ expect(after.preferences).toHaveLength(1);
+ expect(after.contexts).toHaveLength(1);
+ const tagged = (await runtime.searchUserMemory({ effort: 'high', tags: ['wedding'] }))
+ .state as SearchState;
+ expect(tagged.contexts).toHaveLength(1);
+ expect(tagged.preferences).toEqual([]);
+ const taxonomy = await runtime.queryTaxonomyOptions({ include: ['categories', 'tags'] });
+ expect(taxonomy.success).toBe(true);
+ expect(taxonomy.state).toMatchObject({
+ categories: expect.arrayContaining([
+ { count: 3, layers: expect.any(Array), value: 'health' },
+ ]),
+ tags: expect.arrayContaining([{ count: 1, layers: ['context'], value: 'wedding' }]),
+ types: [],
+ });
+ });
+
+ it('retries a seed embedding after a dropped connection, and fails if it stays down', async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ mocks.embed
+ .mockRejectedValueOnce(new Error('connection error: ECONNRESET'))
+ .mockImplementationOnce(async ({ input }: { input: Array<string | undefined> }) =>
+ input.map((text) => (text ? vectorOf(text) : undefined)),
+ );
+ await service.prepare({ ...params, fixture });
+ expect(mocks.embed).toHaveBeenCalledTimes(2);
+ const snapshot = await service.snapshot(params);
+ expect(snapshot.entries).toHaveLength(2);
+ expect(snapshot.retrieval).toBeUndefined();
+
+ const other = await anotherAttempt(params);
+ mocks.embed.mockRejectedValue(new Error('connection error: ECONNRESET'));
+ await expect(service.prepare({ ...other, fixture })).rejects.toThrow('ECONNRESET');
+ expect(await service.snapshot(other)).toMatchObject({ entries: [], fixtureHash: null });
+ });
+
+ it('takes the simplified path when the account has no usable embedding model', async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ mocks.embed.mockRejectedValue(new Error('invalid api key'));
+ const reference = await service.prepare({ ...params, fixture: nativeFixture });
+
+ const runtime = await runtimeFor(reference, params.topicId);
+ const added = await runtime.addPreferenceMemory(preference('Tea', 'Prefers oolong tea.'));
+ expect(added.success).toBe(true);
+
+ // No vectors anywhere, and the model was asked only once per embedder.
+ const rows = await db
+ .select({ embedding: agentEvalMemories.embedding })
+ .from(agentEvalMemories)
+ .where(eq(agentEvalMemories.topicId, params.topicId));
+ expect(rows.length).toBeGreaterThan(1);
+ expect(rows.every((row) => row.embedding === null)).toBe(true);
+
+ // Every entry is still found: words in the query rank, nothing needs a vector.
+ const read = await runtime.searchUserMemory({
+ effort: 'high',
+ queries: ['what do they drink'],
+ });
+ expect(read.success).toBe(true);
+ const state = read.state as SearchState;
+ expect(state.preferences.map((p) => p.conclusionDirectives)).toEqual(
+ expect.arrayContaining(['Prefers oolong tea.', 'Do not recommend shellfish.']),
+ );
+ expect(state.contexts[0]).toMatchObject({ title: 'Wedding menu' });
+
+ const snapshot = await service.snapshot(params);
+ expect(snapshot.retrieval).toBe('simplified');
+ expect(snapshot.entries.map((e) => e.source)).toContain('agent');
+ });
+
+ it('reads a runtime error payload: retries a dropped connection and logs why it cannot embed', async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ mocks.embed
+ .mockRejectedValueOnce({
+ error: { message: 'connection error: ECONNRESET' },
+ errorType: 'ProviderBizError',
+ })
+ .mockImplementationOnce(async ({ input }: { input: Array<string | undefined> }) =>
+ input.map((text) => (text ? vectorOf(text) : undefined)),
+ );
+ await service.prepare({ ...params, fixture });
+ expect(mocks.embed).toHaveBeenCalledTimes(2);
+ expect((await service.snapshot(params)).retrieval).toBeUndefined();
+
+ const other = await anotherAttempt(params);
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ mocks.embed.mockRejectedValue({
+ error: { message: 'Incorrect API key provided' },
+ errorType: 'InvalidProviderAPIKey',
+ });
+ await service.prepare({ ...other, fixture });
+ const reason = (warn.mock.calls.at(-1)?.[1] as { reason: string }).reason;
+ expect(reason).toContain('InvalidProviderAPIKey');
+ expect(reason).not.toContain('[object Object]');
+ warn.mockRestore();
+ });
+
+ it('rejects oversized fixtures, foreign trials and non-eval topics before writing', async () => {
+ const params = await trial();
+ const service = new AgentEvalMemoryService(db, userId);
+ const preferences = Array.from({ length: 51 }, (_, i) => preference(`p${i}`, `d${i}`));
+ await expect(service.prepare({ ...params, fixture: { preferences } })).rejects.toThrow(
+ '50 entries',
+ );
+ await expect(
+ new AgentEvalMemoryService(db, 'someone-else').prepare({ ...params, fixture }),
+ ).rejects.toThrow('not owned');
+ await db
+ .update(topics)
+ .set({ trigger: 'manual' as any })
+ .where(eq(topics.id, params.topicId));
+ await expect(service.prepare({ ...params, fixture })).rejects.toThrow('not found');
+ expect(await db.select().from(agentEvalMemories)).toEqual([]);
+ });
+});
diff --git a/apps/server/src/services/agentEvalMemory/index.ts b/apps/server/src/services/agentEvalMemory/index.ts
new file mode 100644
index 00000000000..88b848f62bd
--- /dev/null
+++ b/apps/server/src/services/agentEvalMemory/index.ts
@@ -0,0 +1,366 @@
+import { createHash } from 'node:crypto';
+
+import type { LobeChatDatabase } from '@lobechat/database';
+import {
+ type EvalMemoryFixture,
+ type EvalMemoryReference,
+ type EvalMemorySnapshot,
+ ThreadType,
+} from '@lobechat/types';
+import { and, asc, eq, sql } from 'drizzle-orm';
+
+import {
+ agentEvalMemories,
+ agentEvalRuns,
+ agentEvalRunTopics,
+ messages,
+ threads,
+ topics,
+} from '@/database/schemas';
+import { buildWorkspaceWhere } from '@/database/utils/workspace';
+import { evalMemoryFixtureSchema } from '@/server/services/agentEvalRun/evalMemory.schema';
+import { getEvalAttemptId } from '@/server/services/agentEvalRun/utils';
+import type { ToolExecutionMemoryEmbeddingRuntime } from '@/server/services/toolExecution/types';
+
+import { createEvalMemoryEmbedder, embedOrSkip } from './embedding';
+import { fixtureDrafts, semanticText, toEntry } from './entries';
+import { EvalMemoryRuntimeService } from './runtime';
+import { attemptWhere } from './where';
+
+type MemoryDatabase =
+ LobeChatDatabase | Parameters<Parameters<LobeChatDatabase['transaction']>[0]>[0];
+
+/** How deep sub-agents may nest inside one attempt (a sub-agent of a sub-agent …). */
+const MAX_SUB_AGENT_DEPTH = 4;
+
+export interface EvalMemoryTrial {
+ resume?: boolean;
+ runId: string;
+ testCaseId: string;
+ threadId?: string;
+ topicId: string;
+}
+
+const fixtureDigest = (value: unknown): string => {
+ const normalize = (item: unknown): unknown =>
+ Array.isArray(item)
+ ? item.map(normalize)
+ : item && typeof item === 'object'
+ ? Object.fromEntries(
+ Object.entries(item)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([key, item]) => [key, normalize(item)]),
+ )
+ : item;
+ return createHash('sha256')
+ .update(JSON.stringify(normalize(value)))
+ .digest('hex');
+};
+
+export const EMPTY_FIXTURE_HASH = fixtureDigest({});
+
+export class EvalMemoryFixtureConflictError extends Error {}
+
+const assertFixture = (
+ state: { fixtureHash?: string | null; hasEntries: boolean },
+ fixtureHash: string,
+ requireInitialized: boolean,
+) => {
+ if (state.fixtureHash && state.fixtureHash !== fixtureHash)
+ throw new EvalMemoryFixtureConflictError('Cannot change Memory fixture while resuming a trial');
+ if (!state.fixtureHash && (requireInitialized || state.hasEntries))
+ throw new EvalMemoryFixtureConflictError(
+ 'Memory fixture initialization was not recorded; rerun this case instead of resuming',
+ );
+};
+
+/**
+ * Memory of eval attempts, kept apart from the account's own Memory: each
+ * attempt (a run's topic, or one pass@k thread of it) gets its own entries,
+ * seeded from the case fixture before the Agent runs. The Memory tool and
+ * the persona injection of the attempt read and write only those entries,
+ * and the tool searches them as the account's Memory is searched; the
+ * caller stays the actor for authorization; the topic's stable creator
+ * owns the Memory entries and embedding configuration across collaborators.
+ * Entries are evidence: nothing is deleted when the attempt ends.
+ */
+export class AgentEvalMemoryService {
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {}
+
+ private trialQuery(
+ db: MemoryDatabase,
+ trial: Pick<EvalMemoryTrial, 'runId' | 'topicId'> & { testCaseId?: string },
+ ) {
+ const scope = { userId: this.userId, workspaceId: this.workspaceId };
+ return db
+ .select({ ownerId: topics.userId })
+ .from(agentEvalRunTopics)
+ .innerJoin(agentEvalRuns, eq(agentEvalRuns.id, agentEvalRunTopics.runId))
+ .innerJoin(topics, eq(topics.id, agentEvalRunTopics.topicId))
+ .where(
+ and(
+ eq(agentEvalRunTopics.runId, trial.runId),
+ eq(agentEvalRunTopics.topicId, trial.topicId),
+ trial.testCaseId ? eq(agentEvalRunTopics.testCaseId, trial.testCaseId) : undefined,
+ buildWorkspaceWhere(scope, agentEvalRuns),
+ buildWorkspaceWhere(scope, agentEvalRunTopics),
+ buildWorkspaceWhere(scope, topics),
+ eq(agentEvalRunTopics.userId, topics.userId),
+ eq(topics.trigger, 'eval'),
+ ),
+ );
+ }
+
+ private async resolveOwner(
+ db: MemoryDatabase,
+ trial: Pick<EvalMemoryTrial, 'runId' | 'threadId' | 'topicId'> & { testCaseId?: string },
+ lock = false,
+ ) {
+ const query = this.trialQuery(db, trial);
+ const [row] = await (lock ? query.for('update', { of: agentEvalRunTopics }) : query);
+ if (!row) throw new Error('Eval Memory trial not found or not owned by caller');
+ if (trial.threadId) {
+ const [thread] = await db
+ .select({ id: threads.id })
+ .from(threads)
+ .where(
+ and(
+ eq(threads.id, trial.threadId),
+ eq(threads.topicId, trial.topicId),
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, threads),
+ ),
+ );
+ if (!thread) throw new Error('Eval Memory thread does not belong to this trial');
+ }
+ return row.ownerId;
+ }
+
+ private async initialization(
+ db: MemoryDatabase,
+ ownerId: string,
+ trial: Pick<EvalMemoryTrial, 'runId' | 'threadId' | 'topicId'>,
+ ) {
+ const [topic] = await db
+ .select({ metadata: topics.metadata })
+ .from(topics)
+ .where(eq(topics.id, trial.topicId));
+ const marker = topic?.metadata?.evalMemoryFixtures?.[getEvalAttemptId(trial)];
+ const entries = await db
+ .select({ fixtureHash: agentEvalMemories.fixtureHash })
+ .from(agentEvalMemories)
+ .where(attemptWhere(ownerId, trial, { includeRemoved: true }));
+ return {
+ fixtureHash: marker ?? entries.find((entry) => entry.fixtureHash)?.fixtureHash,
+ hasEntries: entries.length > 0,
+ };
+ }
+
+ /** Read-only eligibility check for the UI/API, before any workflow is scheduled. */
+ async assertResumeFixture(params: EvalMemoryTrial & { fixture: EvalMemoryFixture }) {
+ const fixture = evalMemoryFixtureSchema.parse(params.fixture);
+ const ownerId = await this.resolveOwner(this.db, params);
+ const state = await this.initialization(this.db, ownerId, params);
+ assertFixture(state, fixtureDigest(fixture), true);
+ }
+
+ /** Seed once, including an empty fixture; resume must bring the recorded fixture. */
+ async prepare(
+ params: EvalMemoryTrial & { fixture: EvalMemoryFixture },
+ ): Promise<EvalMemoryReference> {
+ const fixture = evalMemoryFixtureSchema.parse(params.fixture);
+ const fixtureHash = fixtureDigest(fixture);
+ const reference: EvalMemoryReference = {
+ fixtureHash,
+ runId: params.runId,
+ ...(params.threadId && { threadId: params.threadId }),
+ topicId: params.topicId,
+ };
+ const ownerId = await this.resolveOwner(this.db, params);
+ const existing = await this.initialization(this.db, ownerId, params);
+ assertFixture(existing, fixtureHash, !!params.resume);
+ const drafts = fixtureDrafts(fixture);
+ // Only a new fixture needs embeddings. Reuse the topic owner's configuration
+ // when another workspace editor starts or resumes the attempt.
+ const embeddings =
+ !existing.fixtureHash && drafts.length > 0
+ ? await embedOrSkip(
+ createEvalMemoryEmbedder({
+ db: this.db,
+ source: 'evalMemory:seed',
+ userId: ownerId,
+ workspaceId: this.workspaceId,
+ }),
+ )(drafts.map(semanticText))
+ : [];
+
+ return this.db.transaction(async (tx) => {
+ const lockedOwner = await this.resolveOwner(tx, params, true);
+ if (lockedOwner !== ownerId) throw new Error('Eval Memory trial owner changed');
+ const seeded = await this.initialization(tx, ownerId, params);
+ assertFixture(seeded, fixtureHash, !!params.resume);
+ if (!seeded.fixtureHash && drafts.length > 0) {
+ const capturedAt = fixture.seededAt ? new Date(fixture.seededAt) : new Date();
+ // Written in fixture order, a millisecond apart, as rows the Memory tool
+ // writes one after another are: the search's recency order among seeded
+ // entries is then the fixture's, not the page order of one bulk insert.
+ const writtenAt = Date.now();
+ await tx.insert(agentEvalMemories).values(
+ drafts.map((draft, index) => ({
+ ...draft,
+ attemptId: getEvalAttemptId(reference),
+ capturedAt,
+ createdAt: new Date(writtenAt + index),
+ updatedAt: new Date(writtenAt + index),
+ embedding: embeddings[index] ?? null,
+ fixtureHash,
+ runId: params.runId,
+ source: 'fixture' as const,
+ threadId: params.threadId ?? null,
+ topicId: params.topicId,
+ userId: ownerId,
+ })),
+ );
+ }
+ // Separate initialization evidence from searchable entries. The SQL merge
+ // preserves unrelated metadata and other pass@k attempts. The RunTopic lock
+ // serializes initialization, and neither Resume nor result resets clear it.
+ await tx
+ .update(topics)
+ .set({
+ metadata: sql`jsonb_set(COALESCE(${topics.metadata}, '{}'::jsonb), '{evalMemoryFixtures}',
+ COALESCE(${topics.metadata}->'evalMemoryFixtures', '{}'::jsonb) ||
+ ${JSON.stringify({ [getEvalAttemptId(reference)]: fixtureHash })}::jsonb)`,
+ })
+ .where(eq(topics.id, params.topicId));
+ return reference;
+ });
+ }
+
+ /**
+ * The reference must name the attempt the caller is executing: a pass@k
+ * thread resolves from that thread and the sub-agent threads it spawned, a
+ * topic-level attempt from its topic and any of its sub-agent threads.
+ */
+ private async assertContext(
+ reference: EvalMemoryReference,
+ context: { threadId?: string | null; topicId?: string | null },
+ ) {
+ if (!context.topicId || context.topicId !== reference.topicId)
+ throw new Error('Eval Memory belongs to another trial');
+ if (!reference.threadId || !context.threadId || reference.threadId === context.threadId) return;
+ if (await this.isSubAgentThreadOf(context.threadId, reference.threadId, reference.topicId))
+ return;
+ throw new Error('Eval Memory belongs to another attempt of this trial');
+ }
+
+ /**
+ * Whether `threadId` is a sub-agent's isolation thread spawned, directly or
+ * through nested sub-agents, from the attempt thread. An isolation thread
+ * hangs off the tool message that started it; that message lives in the
+ * spawning thread. A sibling attempt's sub-agents never lead back here.
+ */
+ private async isSubAgentThreadOf(threadId: string, attemptThreadId: string, topicId: string) {
+ const scope = { userId: this.userId, workspaceId: this.workspaceId };
+ let current = threadId;
+ for (let depth = 0; depth < MAX_SUB_AGENT_DEPTH; depth++) {
+ const [row] = await this.db
+ .select({
+ parentThreadId: threads.parentThreadId,
+ sourceThreadId: messages.threadId,
+ type: threads.type,
+ })
+ .from(threads)
+ .leftJoin(
+ messages,
+ and(eq(messages.id, threads.sourceMessageId), eq(messages.topicId, topicId)),
+ )
+ .where(
+ and(
+ eq(threads.id, current),
+ eq(threads.topicId, topicId),
+ buildWorkspaceWhere(scope, threads),
+ ),
+ )
+ .limit(1);
+ const parent = row?.parentThreadId ?? row?.sourceThreadId;
+ if (!row || row.type !== ThreadType.Isolation || !parent) return false;
+ if (parent === attemptThreadId) return true;
+ current = parent;
+ }
+ return false;
+ }
+
+ /** The persona the attempt's prompt is built from (the fixture's, never the caller's). */
+ async getPersonaDocument(
+ reference: EvalMemoryReference,
+ context: { threadId?: string | null; topicId?: string | null },
+ ): Promise<{ persona: string; tagline?: string | null; version: number } | undefined> {
+ await this.assertContext(reference, context);
+ const ownerId = await this.resolveOwner(this.db, reference);
+ const [row] = await this.db
+ .select({ summary: agentEvalMemories.summary, title: agentEvalMemories.title })
+ .from(agentEvalMemories)
+ .where(and(attemptWhere(ownerId, reference), eq(agentEvalMemories.layer, 'persona')))
+ .orderBy(asc(agentEvalMemories.createdAt))
+ .limit(1);
+ if (!row?.summary) return undefined;
+ return { persona: row.summary, tagline: row.title, version: 0 };
+ }
+
+ /** The Memory tool of the attempt. */
+ async runtime(options: {
+ memoryEffort: 'high' | 'low' | 'medium';
+ memoryEmbeddingRuntime?: ToolExecutionMemoryEmbeddingRuntime;
+ reference: EvalMemoryReference;
+ context: { threadId?: string | null; topicId?: string | null };
+ }) {
+ await this.assertContext(options.reference, options.context);
+ const ownerId = await this.resolveOwner(this.db, options.reference);
+ return new EvalMemoryRuntimeService({
+ db: this.db,
+ embed: embedOrSkip(
+ createEvalMemoryEmbedder({
+ db: this.db,
+ memoryEmbeddingRuntime: options.memoryEmbeddingRuntime,
+ source: 'evalMemory:tool',
+ userId: ownerId,
+ workspaceId: this.workspaceId,
+ }),
+ ),
+ memoryEffort: options.memoryEffort,
+ reference: options.reference,
+ userId: ownerId,
+ });
+ }
+
+ /** Everything the attempt's Memory holds, removed entries included, oldest first. */
+ async snapshot(
+ trial: Pick<EvalMemoryTrial, 'runId' | 'threadId' | 'topicId'>,
+ ): Promise<EvalMemorySnapshot> {
+ const ownerId = await this.resolveOwner(this.db, trial);
+ const rows = await this.db
+ .select()
+ .from(agentEvalMemories)
+ .where(attemptWhere(ownerId, trial, { includeRemoved: true }))
+ .orderBy(asc(agentEvalMemories.capturedAt), asc(agentEvalMemories.createdAt));
+ const initialized = await this.initialization(this.db, ownerId, trial);
+ // Legacy empty fixtures have no hash. Preserve their actual entries without
+ // claiming that the initial fixture was empty or dropping snapshot evidence.
+ const fixtureHash = initialized.fixtureHash ?? null;
+ // An entry that has searchable text but no vector was written without a
+ // usable embedding model: the attempt ran on the simplified Memory search.
+ const simplified = rows.some((row) => !row.embedding && !!semanticText(row));
+ return {
+ attemptId: getEvalAttemptId(trial),
+ entries: rows.map(toEntry),
+ fixtureHash,
+ ...(simplified && { retrieval: 'simplified' as const }),
+ };
+ }
+}
+
+export { EvalMemoryRuntimeService } from './runtime';
diff --git a/apps/server/src/services/agentEvalMemory/parity.test.ts b/apps/server/src/services/agentEvalMemory/parity.test.ts
new file mode 100644
index 00000000000..b173c60620f
--- /dev/null
+++ b/apps/server/src/services/agentEvalMemory/parity.test.ts
@@ -0,0 +1,551 @@
+// @vitest-environment node
+import type { EvalMemoryFixture, SearchMemoryParams, SearchMemoryResult } from '@lobechat/types';
+import { eq, sql } from 'drizzle-orm';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '@/database/core/getTestDB';
+import { UserMemoryModel } from '@/database/models/userMemory';
+import {
+ agentEvalMemories,
+ userMemories,
+ userMemoriesActivities,
+ userMemoriesContexts,
+ userMemoriesIdentities,
+ userMemoriesPreferences,
+} from '@/database/schemas';
+import { cleanupDB, setupEvalChain, userId } from '@/server/services/agentEvalRun/__tests__/_setup';
+import { MemoryServerRuntimeService } from '@/server/services/toolExecution/serverRuntimes/memory';
+
+import { AgentEvalMemoryService } from './index';
+import { hasPgSearch } from './search';
+
+const mocks = vi.hoisted(() => ({
+ embed: vi.fn(),
+ initModelRuntimeFromDB: vi.fn<(serverDB: unknown, actor: string) => Promise<unknown>>(
+ async () => ({}),
+ ),
+}));
+
+vi.mock('@/server/globalConfig', () => ({
+ getServerDefaultFilesConfig: () => ({
+ embeddingModel: { model: 'test-embedding', provider: 'test' },
+ }),
+}));
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: mocks.initModelRuntimeFromDB,
+ initModelRuntimeWithUserPayload: vi.fn(),
+}));
+vi.mock('@/server/services/memory/userMemory/embedding', () => ({
+ embedUserMemoryTexts: mocks.embed,
+}));
+vi.mock('@/server/services/agentSignal/procedure', () => ({
+ emitToolOutcomeSafely: vi.fn(),
+ resolveToolOutcomeScope: vi.fn(),
+}));
+vi.mock('@/server/services/agentSignal/store/adapters/redis/policyStateStore', () => ({
+ redisPolicyStateStore: {},
+}));
+vi.mock('@/server/services/ftsSearch', () => ({ createFtsSearchRepo: vi.fn() }));
+
+const db = await getTestDB();
+/** The BM25 pass needs pg_search; PGlite has none, so queried searches run only on a server DB. */
+const bm25 = await hasPgSearch(db);
+
+/**
+ * A bag-of-words embedding: texts that share words are close, so ranking is
+ * lexical. Two small text-dependent components keep any two texts at distinct
+ * similarities: a tie (two entries equally far from the query) would leave the
+ * order to the database, as a real embedding never does.
+ */
+const vectorOf = (text: string) => {
+ const vector = Array.from({ length: 1024 }, () => 0);
+ for (const token of text.toLowerCase().split(/[^\p{L}\p{N}]+/u)) {
+ if (token.length < 2) continue;
+ let hash = 2;
+ for (const char of token) hash = (hash * 31 + (char.codePointAt(0) ?? 0)) % 1022;
+ vector[hash + 2] += 1;
+ }
+ vector[0] = 0.5;
+ vector[1] = text.length / 1000;
+ return vector;
+};
+
+/** When every entry was remembered; both stores are pinned to it. */
+const SEEDED_AT = new Date('2024-05-01T12:00:00.000Z');
+
+const preference = (
+ title: string,
+ directive: string,
+ extra: { category: string; suggestions?: string[]; tags: string[]; type: string },
+) => ({
+ details: directive,
+ memoryCategory: extra.category,
+ memoryType: 'preference',
+ sourceIds: [],
+ summary: title,
+ tags: extra.tags,
+ title,
+ withPreference: {
+ appContext: null,
+ conclusionDirectives: directive,
+ extractedLabels: [],
+ extractedScopes: [],
+ originContext: null,
+ scorePriority: 0.8,
+ suggestions: extra.suggestions ?? [],
+ type: extra.type,
+ },
+});
+
+const context = (
+ title: string,
+ description: string,
+ extra: { category: string; status: string; tags: string[] },
+) => ({
+ details: description,
+ memoryCategory: extra.category,
+ memoryType: 'context',
+ sourceIds: [],
+ summary: title,
+ tags: extra.tags,
+ title,
+ withContext: {
+ associatedObjects: [],
+ associatedSubjects: [],
+ currentStatus: extra.status,
+ description,
+ labels: [],
+ scoreImpact: 0.5,
+ scoreUrgency: 0.5,
+ title,
+ type: 'project',
+ },
+});
+
+/**
+ * Entries whose words, tags, categories and layers overlap, so every signal of
+ * the ranking (keyword, semantic, fuzzy, tags, categories, time) has something
+ * to tell apart.
+ */
+const fixture: EvalMemoryFixture = {
+ activities: [
+ {
+ details: 'Reviewed the latest allergy panel results.',
+ memoryCategory: 'health',
+ memoryType: 'activity',
+ sourceIds: [],
+ summary: 'Allergist appointment',
+ tags: ['appointment'],
+ title: 'Allergist follow-up',
+ withActivity: {
+ associatedLocations: [{ name: 'City Allergy Clinic', type: 'clinic' }],
+ associatedObjects: [],
+ associatedSubjects: [{ name: 'Dr. Kim', type: 'person' }],
+ endsAt: '2024-05-03T15:00:00Z',
+ feedback: 'Reassuring visit.',
+ narrative: 'Reviewed the allergy panel results with Dr. Kim at the City Allergy Clinic.',
+ notes: null,
+ startsAt: '2024-05-03T14:00:00Z',
+ status: 'completed',
+ tags: ['health'],
+ timezone: 'UTC',
+ type: 'appointment',
+ },
+ },
+ {
+ details: 'A routine dental cleaning.',
+ memoryCategory: 'health',
+ memoryType: 'activity',
+ sourceIds: [],
+ summary: 'Dentist cleaning',
+ tags: ['dentist'],
+ title: 'Dentist cleaning',
+ withActivity: {
+ associatedLocations: [],
+ associatedObjects: [],
+ associatedSubjects: [],
+ endsAt: null,
+ feedback: null,
+ narrative: 'Booked a dental cleaning for the first week of June.',
+ notes: null,
+ startsAt: '2024-06-04T09:00:00Z',
+ status: 'planned',
+ tags: null,
+ timezone: 'UTC',
+ type: 'appointment',
+ },
+ },
+ ],
+ contexts: [
+ context(
+ 'GA4 monitoring',
+ 'The GA4 property for the storefront is 531100373, checked every Monday.',
+ { category: 'work', status: 'ongoing', tags: ['ga4', 'analytics'] },
+ ),
+ context(
+ 'Shopify store',
+ 'The Shopify store Robin Keyboard sells mechanical keyboards; its summer sale runs in July.',
+ { category: 'work', status: 'ongoing', tags: ['shopify', 'store'] },
+ ),
+ context(
+ 'Wedding catering',
+ 'Finalizing a shellfish-free wedding menu with the caterer before June.',
+ { category: 'personal', status: 'ongoing', tags: ['wedding', 'menu'] },
+ ),
+ ],
+ identities: [
+ {
+ details: null,
+ memoryCategory: 'professional',
+ memoryType: 'fact',
+ summary: 'The user works as a pastry chef.',
+ tags: ['career'],
+ title: 'Pastry chef',
+ withIdentity: {
+ description: 'Runs the dessert station at a bistro and trains the junior bakers.',
+ episodicDate: null,
+ extractedLabels: ['culinary'],
+ relationship: 'self',
+ role: 'pastry chef',
+ scoreConfidence: 0.9,
+ sourceEvidence: null,
+ sourceIds: [],
+ type: 'professional',
+ },
+ },
+ {
+ details: null,
+ memoryCategory: 'health',
+ memoryType: 'fact',
+ summary: 'Dr. Kim is the allergist.',
+ tags: ['health'],
+ title: 'Dr. Kim',
+ withIdentity: {
+ description: 'The allergist, Dr. Kim, who reviews the allergy panel twice a year.',
+ episodicDate: null,
+ extractedLabels: [],
+ relationship: 'friend',
+ role: 'allergist',
+ scoreConfidence: 0.7,
+ sourceEvidence: null,
+ sourceIds: [],
+ type: 'personal',
+ },
+ },
+ ],
+ preferences: [
+ preference(
+ 'Confirmed trading profile',
+ 'For paper trading, use a maximum of USD 1000 per trade and apply a 5% stop-loss; never place live trades.',
+ {
+ category: 'finance',
+ suggestions: ['Confirm the stop-loss before each order.'],
+ tags: ['trading', 'risk'],
+ type: 'trading-profile',
+ },
+ ),
+ preference(
+ 'Newsletter digest preference',
+ 'Newsletters: a concise Chinese executive summary, exactly three linked sources and a short action list.',
+ { category: 'work', tags: ['newsletter', 'digest'], type: 'format' },
+ ),
+ preference(
+ 'Code comment preference',
+ 'When adding code comments, explain only the important logic and skip obvious lines.',
+ { category: 'work', tags: ['code', 'review'], type: 'coding' },
+ ),
+ preference(
+ 'Risk disclosure preference',
+ 'Always state the trading risk before suggesting any paper trade.',
+ { category: 'finance', tags: ['risk', 'compliance'], type: 'compliance' },
+ ),
+ ],
+ seededAt: SEEDED_AT.toISOString(),
+};
+
+type Layer = 'activities' | 'contexts' | 'identities' | 'preferences';
+const LAYERS: Layer[] = ['activities', 'contexts', 'identities', 'preferences'];
+
+/** The text that names an entry across both stores (ids differ). */
+const keyOf = (layer: Layer, item: Record<string, any>): string =>
+ layer === 'preferences'
+ ? item.conclusionDirectives
+ : layer === 'activities'
+ ? item.narrative
+ : item.description;
+
+const round = (value: number) => Math.round(value * 1e9) / 1e9;
+
+/** What a reader of the result sees: per layer, the entries in order, their scores and the layer meta. */
+const view = (result: SearchMemoryResult) =>
+ Object.fromEntries(
+ LAYERS.map((layer) => {
+ const items = (result[layer] ?? []) as Record<string, any>[];
+ const ranking = result.meta?.ranking?.[layer] ?? {};
+ return [
+ layer,
+ {
+ meta: result.meta?.layers[layer],
+ order: items.map((item) => keyOf(layer, item)),
+ scores: Object.fromEntries(
+ items.map((item) => [
+ keyOf(layer, item),
+ Object.fromEntries(
+ Object.entries(ranking[item.id] ?? {}).map(([k, v]) => [k, round(v as number)]),
+ ),
+ ]),
+ ),
+ },
+ ];
+ }),
+ );
+
+/** The text that names an entry across both stores (ids differ). */
+const entryKeys = [
+ ...(fixture.preferences ?? []).map((item: any) => item.withPreference.conclusionDirectives),
+ ...(fixture.contexts ?? []).map((item: any) => item.withContext.description),
+ ...(fixture.activities ?? []).map((item: any) => item.withActivity.narrative),
+ ...(fixture.identities ?? []).map((item: any) => item.withIdentity.description),
+] as string[];
+
+/**
+ * Each entry's clock: the seed time plus a minute per entry, so no two entries
+ * tie on recency (the lexical pass orders by it, and a tie's order is the
+ * database's to choose). Both stores are pinned to the same clocks.
+ */
+const clockOf = (key: string) => {
+ const index = entryKeys.indexOf(key);
+ if (index < 0) throw new Error(`Unknown entry: ${key}`);
+ return new Date(SEEDED_AT.getTime() + (index + 1) * 60_000);
+};
+
+/** Add the fixture through the account's Memory tool, then pin every row to its entry's clock. */
+const seedAccountMemory = async () => {
+ const account = new MemoryServerRuntimeService({
+ memoryEffort: 'medium',
+ memoryModel: new UserMemoryModel(db, userId),
+ serverDB: db,
+ userId,
+ });
+ for (const item of fixture.preferences ?? []) await account.addPreferenceMemory(item as any);
+ for (const item of fixture.contexts ?? []) await account.addContextMemory(item as any);
+ for (const item of fixture.activities ?? []) await account.addActivityMemory(item as any);
+ for (const item of fixture.identities ?? []) await account.addIdentityMemory(item as any);
+
+ const layers = [
+ { key: userMemoriesPreferences.conclusionDirectives, table: userMemoriesPreferences },
+ { key: userMemoriesContexts.description, table: userMemoriesContexts },
+ { key: userMemoriesActivities.narrative, table: userMemoriesActivities },
+ { key: userMemoriesIdentities.description, table: userMemoriesIdentities },
+ ] as const;
+ for (const { key, table } of layers) {
+ const rows = await db
+ .select({ id: table.id, key, memoryIds: sql<string[]>`ARRAY[]::text[]` })
+ .from(table);
+ for (const row of rows) {
+ const at = clockOf(row.key as string);
+ const clock = { accessedAt: at, capturedAt: at, createdAt: at, updatedAt: at };
+ await db.update(table).set(clock).where(eq(table.id, row.id));
+ }
+ }
+ // Base rows: through the layer rows that point at them.
+ const bases = await db
+ .select({ id: userMemories.id, layer: userMemories.memoryLayer, summary: userMemories.summary })
+ .from(userMemories);
+ for (const base of bases) {
+ const linked =
+ base.layer === 'preference'
+ ? await db
+ .select({ key: userMemoriesPreferences.conclusionDirectives })
+ .from(userMemoriesPreferences)
+ .where(eq(userMemoriesPreferences.userMemoryId, base.id))
+ : base.layer === 'activity'
+ ? await db
+ .select({ key: userMemoriesActivities.narrative })
+ .from(userMemoriesActivities)
+ .where(eq(userMemoriesActivities.userMemoryId, base.id))
+ : base.layer === 'identity'
+ ? await db
+ .select({ key: userMemoriesIdentities.description })
+ .from(userMemoriesIdentities)
+ .where(eq(userMemoriesIdentities.userMemoryId, base.id))
+ : await db
+ .select({ key: userMemoriesContexts.description })
+ .from(userMemoriesContexts)
+ .where(
+ sql`COALESCE(${userMemoriesContexts.userMemoryIds}, '[]'::jsonb) ? ${base.id}`,
+ );
+ const at = clockOf(linked[0]!.key as string);
+ await db
+ .update(userMemories)
+ .set({ capturedAt: at, createdAt: at, lastAccessedAt: at, updatedAt: at })
+ .where(eq(userMemories.id, base.id));
+ }
+ return account;
+};
+
+const seedAttemptMemory = async () => {
+ const chain = await setupEvalChain({});
+ const service = new AgentEvalMemoryService(db, userId);
+ const reference = await service.prepare({
+ fixture,
+ runId: chain.run.id,
+ testCaseId: chain.testCase.id,
+ topicId: chain.topic.id,
+ });
+ const rows = await db
+ .select({ id: agentEvalMemories.id, payload: agentEvalMemories.payload })
+ .from(agentEvalMemories);
+ for (const row of rows) {
+ const p = row.payload as Record<string, any>;
+ const key = p.conclusionDirectives ?? p.narrative ?? p.description;
+ if (typeof key !== 'string') continue;
+ const at = clockOf(key);
+ await db
+ .update(agentEvalMemories)
+ .set({ capturedAt: at, createdAt: at, updatedAt: at })
+ .where(eq(agentEvalMemories.id, row.id));
+ }
+ return service.runtime({
+ context: { topicId: chain.topic.id },
+ memoryEffort: 'medium',
+ reference,
+ });
+};
+
+const LONG_QUERY =
+ 'Earlier in this conversation the user explained that they are allergic to shellfish and are ' +
+ 'planning a shellfish-free wedding menu with their caterer; they also mentioned that they only ' +
+ 'paper trade with a strict stop-loss and like newsletter digests with three linked sources.';
+
+/** `bm25: true` cases send a short query, which the account's search answers through pg_search. */
+const cases: Array<{ bm25: boolean; name: string; params: SearchMemoryParams }> = [
+ {
+ bm25: true,
+ name: 'a query at the default effort',
+ params: { queries: ['paper trading stop loss'] },
+ },
+ {
+ bm25: true,
+ name: 'a hyphenated query at high effort',
+ params: { effort: 'high', queries: ['stop-loss before each order'] },
+ },
+ { bm25: true, name: 'a context query', params: { effort: 'high', queries: ['wedding menu'] } },
+ {
+ bm25: true,
+ name: 'a query on one layer',
+ params: { effort: 'high', layers: ['context'], queries: ['GA4'] } as SearchMemoryParams,
+ },
+ {
+ bm25: true,
+ name: 'two queries',
+ params: { effort: 'high', queries: ['newsletter', 'trading risk'] },
+ },
+ { bm25: false, name: 'a tag filter and no query', params: { effort: 'high', tags: ['risk'] } },
+ {
+ bm25: true,
+ name: 'a category filter',
+ params: { categories: ['health'], effort: 'high', queries: ['allergy'] },
+ },
+ {
+ bm25: true,
+ name: 'a status filter on activities',
+ params: {
+ effort: 'high',
+ layers: ['activity'],
+ queries: ['appointment'],
+ status: ['completed'],
+ } as SearchMemoryParams,
+ },
+ {
+ bm25: true,
+ name: 'a time intent that covers the seed',
+ params: {
+ effort: 'high',
+ queries: ['dessert'],
+ timeIntent: { end: '2024-05-31', selector: 'range', start: '2024-05-01' },
+ } as unknown as SearchMemoryParams,
+ },
+ {
+ bm25: true,
+ name: 'a time range before the seed',
+ params: {
+ effort: 'high',
+ queries: ['dessert'],
+ timeRange: { end: new Date('2023-12-31T00:00:00Z'), start: new Date('2023-01-01T00:00:00Z') },
+ },
+ },
+ { bm25: false, name: 'a query too long for the lexical pass', params: { queries: [LONG_QUERY] } },
+ {
+ bm25: true,
+ name: 'a relationship filter on identities',
+ params: { effort: 'high', queries: ['pastry chef'], relationships: ['self'] },
+ },
+ {
+ bm25: true,
+ name: 'a type filter',
+ params: { effort: 'high', queries: ['trading'], types: ['preference'] },
+ },
+ { bm25: true, name: 'low effort', params: { effort: 'low', queries: ['keyboards summer sale'] } },
+ { bm25: true, name: 'a name in two layers', params: { effort: 'high', queries: ['Dr. Kim'] } },
+ {
+ bm25: true,
+ name: 'a query with a tag filter',
+ params: { effort: 'high', queries: ['trading'], tags: ['risk'] },
+ },
+ {
+ bm25: false,
+ name: 'a time range and no query',
+ params: { effort: 'high', timeRange: { start: new Date('2024-04-30T00:00:00Z') } },
+ },
+];
+
+/**
+ * The attempt's Memory tool must answer exactly as the account's Memory tool
+ * answers for the same entries: the same entries per layer, in the same order,
+ * with the same scores. The account's side is the product runtime over
+ * `user_memories*`; the attempt's side is the eval runtime over
+ * `agent_eval_memories`.
+ */
+describe('eval Memory search parity with the account Memory', () => {
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ mocks.embed.mockImplementation(async ({ input }: { input: Array<string | null | undefined> }) =>
+ input.map((text) => (text ? vectorOf(text) : undefined)),
+ );
+ await cleanupDB();
+ });
+
+ const compare = async (params: SearchMemoryParams) => {
+ const account = await seedAccountMemory();
+ const attempt = await seedAttemptMemory();
+
+ const expected = view(await account.searchMemory(params));
+ const actual = view(await attempt.searchMemory(params));
+
+ expect(actual).toEqual(expected);
+ // The case must exercise something: at least one layer returned an entry,
+ // unless its time range ends before anything was remembered.
+ const returned = LAYERS.reduce((sum, layer) => sum + expected[layer].order.length, 0);
+ const beforeSeed = !!params.timeRange?.end && params.timeRange.end < SEEDED_AT;
+ if (beforeSeed) expect(returned).toBe(0);
+ else expect(returned).toBeGreaterThan(0);
+ };
+
+ it.each(cases.filter((c) => !c.bm25))('ranks $name the same', ({ params }) => compare(params));
+
+ it.skipIf(!bm25).each(cases.filter((c) => c.bm25))(
+ 'ranks $name the same (with the BM25 pass)',
+ ({ params }) => compare(params),
+ );
+
+ it.skipIf(!bm25)('searches with the lexical pass when pg_search is present', async () => {
+ const attempt = await seedAttemptMemory();
+ // Words that appear only in the directives: the semantic pass alone (bag of words) would
+ // also find it, so check the keyword signal itself.
+ const result = await attempt.searchMemory({ effort: 'high', queries: ['live trades'] });
+ const top = result.preferences[0] as Record<string, any>;
+ expect(top.conclusionDirectives).toContain('never place live trades');
+ expect(result.meta?.ranking?.preferences?.[top.id]?.keyword).toBeGreaterThan(0);
+ });
+});
diff --git a/apps/server/src/services/agentEvalMemory/runtime.ts b/apps/server/src/services/agentEvalMemory/runtime.ts
new file mode 100644
index 00000000000..3ac4fb8f8ee
--- /dev/null
+++ b/apps/server/src/services/agentEvalMemory/runtime.ts
@@ -0,0 +1,347 @@
+import type { MemoryRuntimeService } from '@lobechat/builtin-tool-memory/executionRuntime';
+import type { LobeChatDatabase } from '@lobechat/database';
+import type {
+ ActivityMemoryItemSchema,
+ AddIdentityActionSchema,
+ ContextMemoryItemSchema,
+ ExperienceMemoryItemSchema,
+ PreferenceMemoryItemSchema,
+ RemoveIdentityActionSchema,
+ UpdateIdentityToolInputSchema,
+} from '@lobechat/memory-user-memory/schemas';
+import type {
+ AddActivityMemoryResult,
+ AddContextMemoryResult,
+ AddExperienceMemoryResult,
+ AddIdentityMemoryResult,
+ AddPreferenceMemoryResult,
+ AgentEvalMemoryItem,
+ EvalMemoryReference,
+ QueryTaxonomyOptionsParams,
+ QueryTaxonomyOptionsResult,
+ RemoveIdentityMemoryResult,
+ SearchMemoryParams,
+ SearchMemoryResult,
+ UpdateIdentityMemoryResult,
+} from '@lobechat/types';
+import { and, asc, eq } from 'drizzle-orm';
+import type { z } from 'zod';
+
+import { normalizeUserMemorySearchQueries } from '@/database/models/userMemory';
+import { agentEvalMemories } from '@/database/schemas';
+import { getEvalAttemptId } from '@/server/services/agentEvalRun/utils';
+import {
+ type MemorySearchEffort,
+ normalizeSearchMemoryParams,
+ resolveMemorySearchTopK,
+} from '@/server/services/memory/userMemory/searchParams';
+
+import type { EvalMemoryEmbedder } from './embedding';
+import { draftOf, type EvalMemoryDraft, semanticText } from './entries';
+import { searchEvalMemory } from './search';
+import { attemptWhere } from './where';
+
+export { attemptWhere } from './where';
+
+type Payload = Record<string, any>;
+
+const asList = (value: unknown): string[] =>
+ Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : [];
+
+/** The account's Memory reads an unknown effort as medium. */
+const normalizeEffort = (value: unknown, fallback: MemorySearchEffort): MemorySearchEffort => {
+ if (value === undefined || value === null) return fallback;
+ return value === 'low' || value === 'medium' || value === 'high' ? value : 'medium';
+};
+
+/**
+ * The Memory tool of an eval attempt. Same surface as the account's Memory
+ * runtime, backed by the attempt's own rows: the fixture it was seeded with
+ * plus what the Agent writes during the attempt. Search is the account's
+ * hybrid search run over those rows (`searchEvalMemory`), with the queries
+ * embedded by the account's embedding model and the effort's limits.
+ */
+export class EvalMemoryRuntimeService implements MemoryRuntimeService {
+ constructor(
+ private readonly options: {
+ db: LobeChatDatabase;
+ embed: EvalMemoryEmbedder;
+ memoryEffort: MemorySearchEffort;
+ reference: EvalMemoryReference;
+ userId: string;
+ },
+ ) {}
+
+ private get db() {
+ return this.options.db;
+ }
+
+ private rows = (includeRemoved = false) =>
+ this.db
+ .select()
+ .from(agentEvalMemories)
+ .where(attemptWhere(this.options.userId, this.options.reference, { includeRemoved }))
+ .orderBy(asc(agentEvalMemories.capturedAt), asc(agentEvalMemories.createdAt));
+
+ private save = async (draft: EvalMemoryDraft) => {
+ const { reference, userId } = this.options;
+ const [embedding] = await this.options.embed([semanticText(draft)]);
+ const [row] = await this.db
+ .insert(agentEvalMemories)
+ .values({
+ ...draft,
+ attemptId: getEvalAttemptId(reference),
+ capturedAt: new Date(),
+ embedding: embedding ?? null,
+ runId: reference.runId,
+ source: 'agent',
+ threadId: reference.threadId ?? null,
+ topicId: reference.topicId,
+ userId,
+ })
+ .returning();
+ return row;
+ };
+
+ private failure = (error: unknown) => ({
+ message: `Failed to save memory: ${error instanceof Error ? error.message : String(error)}`,
+ success: false as const,
+ });
+
+ searchMemory = async (params: SearchMemoryParams): Promise<SearchMemoryResult> => {
+ const normalized = normalizeSearchMemoryParams(params);
+ const queries = normalizeUserMemorySearchQueries(normalized.queries);
+ const queryEmbeddings =
+ queries.length > 0
+ ? (await this.options.embed(queries)).filter((e): e is number[] => !!e)
+ : [];
+ const effort = normalizeEffort(normalized.effort, this.options.memoryEffort);
+ return searchEvalMemory({
+ db: this.db,
+ params: { ...normalized, queries, topK: resolveMemorySearchTopK(effort, normalized) },
+ queryEmbeddings,
+ reference: this.options.reference,
+ userId: this.options.userId,
+ });
+ };
+
+ queryTaxonomyOptions = async (
+ params: QueryTaxonomyOptionsParams,
+ ): Promise<QueryTaxonomyOptionsResult> => {
+ const limit = params.limit ?? 20;
+ const q = params.q?.toLowerCase();
+ const wantedLayers = params.layers?.length ? new Set(params.layers.map(String)) : undefined;
+ const include = new Set(params.include ?? []);
+ const rows = (await this.rows()).filter(
+ (row) =>
+ row.layer !== 'persona' &&
+ (!wantedLayers || wantedLayers.has(row.layer)) &&
+ (!params.timeRange?.start || row.capturedAt >= params.timeRange.start) &&
+ (!params.timeRange?.end || row.capturedAt <= params.timeRange.end),
+ );
+ const facet = (
+ name: NonNullable<QueryTaxonomyOptionsParams['include']>[number],
+ pick: (row: AgentEvalMemoryItem) => unknown[],
+ ) => {
+ if (include.size > 0 && !include.has(name)) return { hasMore: false, items: [] };
+ const counts = new Map<string, { count: number; layers: Set<string> }>();
+ for (const row of rows) {
+ for (const value of pick(row)) {
+ if (typeof value !== 'string' || !value || (q && !value.toLowerCase().includes(q)))
+ continue;
+ const entry = counts.get(value) ?? { count: 0, layers: new Set() };
+ entry.count += 1;
+ entry.layers.add(row.layer);
+ counts.set(value, entry);
+ }
+ }
+ const items = [...counts.entries()]
+ .sort((a, b) => b[1].count - a[1].count || a[0].localeCompare(b[0]))
+ .map(([value, entry]) => ({
+ count: entry.count,
+ layers: [...entry.layers] as QueryTaxonomyOptionsResult['types'][number]['layers'],
+ value,
+ }));
+ return { hasMore: items.length > limit, items: items.slice(0, limit) };
+ };
+ const payload = (row: AgentEvalMemoryItem) => row.payload as Payload;
+ const categories = facet('categories', (row) => [row.memoryCategory]);
+ const labels = facet('labels', (row) => [
+ ...asList(payload(row).extractedLabels),
+ ...asList(payload(row).labels),
+ ]);
+ const relationships = facet('relationships', (row) => [payload(row).relationship]);
+ const roles = facet('roles', (row) => [payload(row).role]);
+ const statuses = facet('statuses', (row) => [
+ payload(row).currentStatus ?? payload(row).status,
+ ]);
+ const tags = facet('tags', (row) => asList(row.tags));
+ const types = facet('types', (row) => [row.memoryType ?? payload(row).type]);
+ return {
+ categories: categories.items,
+ hasMore: {
+ categories: categories.hasMore,
+ labels: labels.hasMore,
+ relationships: relationships.hasMore,
+ roles: roles.hasMore,
+ statuses: statuses.hasMore,
+ tags: tags.hasMore,
+ types: types.hasMore,
+ },
+ labels: labels.items,
+ relationships: relationships.items,
+ roles: roles.items,
+ statuses: statuses.items,
+ tags: tags.items,
+ types: types.items,
+ };
+ };
+
+ addContextMemory = async (
+ input: z.infer<typeof ContextMemoryItemSchema>,
+ ): Promise<AddContextMemoryResult> => {
+ try {
+ const row = await this.save(draftOf('context', input, 'withContext'));
+ return {
+ contextId: row.id,
+ memoryId: row.id,
+ message: 'Memory saved successfully',
+ success: true,
+ };
+ } catch (error) {
+ return this.failure(error);
+ }
+ };
+
+ addActivityMemory = async (
+ input: z.infer<typeof ActivityMemoryItemSchema>,
+ ): Promise<AddActivityMemoryResult> => {
+ try {
+ const row = await this.save(draftOf('activity', input, 'withActivity'));
+ return {
+ activityId: row.id,
+ memoryId: row.id,
+ message: 'Memory saved successfully',
+ success: true,
+ };
+ } catch (error) {
+ return this.failure(error);
+ }
+ };
+
+ addExperienceMemory = async (
+ input: z.infer<typeof ExperienceMemoryItemSchema>,
+ ): Promise<AddExperienceMemoryResult> => {
+ try {
+ const row = await this.save(draftOf('experience', input, 'withExperience'));
+ return {
+ experienceId: row.id,
+ memoryId: row.id,
+ message: 'Memory saved successfully',
+ success: true,
+ };
+ } catch (error) {
+ return this.failure(error);
+ }
+ };
+
+ addPreferenceMemory = async (
+ input: z.infer<typeof PreferenceMemoryItemSchema>,
+ ): Promise<AddPreferenceMemoryResult> => {
+ try {
+ const row = await this.save(draftOf('preference', input, 'withPreference'));
+ return {
+ memoryId: row.id,
+ message: 'Memory saved successfully',
+ preferenceId: row.id,
+ success: true,
+ };
+ } catch (error) {
+ return this.failure(error);
+ }
+ };
+
+ addIdentityMemory = async (
+ input: z.infer<typeof AddIdentityActionSchema>,
+ ): Promise<AddIdentityMemoryResult> => {
+ try {
+ const row = await this.save(draftOf('identity', input, 'withIdentity'));
+ return {
+ identityId: row.id,
+ memoryId: row.id,
+ message: 'Memory saved successfully',
+ success: true,
+ };
+ } catch (error) {
+ return this.failure(error);
+ }
+ };
+
+ private identity = async (id: string) => {
+ const [row] = await this.db
+ .select()
+ .from(agentEvalMemories)
+ .where(
+ and(
+ attemptWhere(this.options.userId, this.options.reference),
+ eq(agentEvalMemories.id, id),
+ eq(agentEvalMemories.layer, 'identity'),
+ ),
+ )
+ .limit(1);
+ return row;
+ };
+
+ updateIdentityMemory = async (
+ input: z.output<typeof UpdateIdentityToolInputSchema>,
+ ): Promise<UpdateIdentityMemoryResult> => {
+ try {
+ const row = await this.identity(input.id);
+ if (!row) return { message: `Identity memory ${input.id} not found`, success: false };
+ const set = (input.set ?? {}) as Payload;
+ const replace = String(input.mergeStrategy).toLowerCase() === 'replace';
+ const payload = replace
+ ? ((set.withIdentity ?? {}) as Record<string, unknown>)
+ : { ...row.payload, ...set.withIdentity };
+ const next: EvalMemoryDraft = {
+ details: set.details ?? (replace ? null : row.details),
+ layer: 'identity',
+ memoryCategory: set.memoryCategory ?? (replace ? null : row.memoryCategory),
+ memoryType: set.memoryType ?? (replace ? null : row.memoryType),
+ payload,
+ summary: set.summary ?? (replace ? null : row.summary),
+ tags: Array.isArray(set.tags) ? set.tags : replace ? null : row.tags,
+ title: set.title ?? (replace ? null : row.title),
+ };
+ const [embedding] = await this.options.embed([semanticText(next)]);
+ await this.db
+ .update(agentEvalMemories)
+ .set({ ...next, embedding: embedding ?? row.embedding, updatedAt: new Date() })
+ .where(eq(agentEvalMemories.id, row.id));
+ return { identityId: row.id, message: 'Identity memory updated', success: true };
+ } catch (error) {
+ return this.failure(error);
+ }
+ };
+
+ removeIdentityMemory = async (
+ input: z.infer<typeof RemoveIdentityActionSchema>,
+ ): Promise<RemoveIdentityMemoryResult> => {
+ try {
+ const row = await this.identity(input.id);
+ if (!row) return { message: `Identity memory ${input.id} not found`, success: false };
+ await this.db
+ .update(agentEvalMemories)
+ .set({ removedReason: input.reason || 'removed', updatedAt: new Date() })
+ .where(eq(agentEvalMemories.id, row.id));
+ return {
+ identityId: row.id,
+ message: 'Identity memory removed',
+ reason: input.reason,
+ success: true,
+ };
+ } catch (error) {
+ return this.failure(error);
+ }
+ };
+}
diff --git a/apps/server/src/services/agentEvalMemory/search.pgSearch.test.ts b/apps/server/src/services/agentEvalMemory/search.pgSearch.test.ts
new file mode 100644
index 00000000000..de729f27ed6
--- /dev/null
+++ b/apps/server/src/services/agentEvalMemory/search.pgSearch.test.ts
@@ -0,0 +1,46 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { describe, expect, it, vi } from 'vitest';
+
+import { hasPgSearch } from './search';
+
+describe('evaluation Memory pg_search detection', () => {
+ it('retries a failed probe so a temporary outage does not disable later lexical searches', async () => {
+ const execute = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('Temporary database connection failure'))
+ .mockResolvedValue({ rows: [{ exists: 1 }] });
+ const db = { execute } as unknown as LobeChatDatabase;
+
+ await expect(hasPgSearch(db)).resolves.toBe(false);
+ await expect(hasPgSearch(db)).resolves.toBe(true);
+ await expect(hasPgSearch(db)).resolves.toBe(true);
+ expect(execute).toHaveBeenCalledTimes(2);
+ });
+
+ it('remembers a successful probe that confirms pg_search is unavailable', async () => {
+ const execute = vi.fn().mockResolvedValue({ rows: [] });
+ const db = { execute } as unknown as LobeChatDatabase;
+
+ await expect(hasPgSearch(db)).resolves.toBe(false);
+ await expect(hasPgSearch(db)).resolves.toBe(false);
+ expect(execute).toHaveBeenCalledTimes(1);
+ });
+
+ it('shares one in-flight probe among concurrent searches', async () => {
+ let resolveProbe!: (result: { rows: object[] }) => void;
+ const execute = vi.fn(
+ () =>
+ new Promise<{ rows: object[] }>((resolve) => {
+ resolveProbe = resolve;
+ }),
+ );
+ const db = { execute } as unknown as LobeChatDatabase;
+
+ const searches = [hasPgSearch(db), hasPgSearch(db), hasPgSearch(db)];
+ expect(execute).toHaveBeenCalledTimes(1);
+ resolveProbe({ rows: [{ exists: 1 }] });
+ await expect(Promise.all(searches)).resolves.toEqual([true, true, true]);
+ await expect(hasPgSearch(db)).resolves.toBe(true);
+ expect(execute).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/server/src/services/agentEvalMemory/search.ts b/apps/server/src/services/agentEvalMemory/search.ts
new file mode 100644
index 00000000000..52bef7bb680
--- /dev/null
+++ b/apps/server/src/services/agentEvalMemory/search.ts
@@ -0,0 +1,498 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import type {
+ AgentEvalMemoryItem,
+ EvalMemoryReference,
+ SearchMemoryParams,
+ SearchMemoryResult,
+} from '@lobechat/types';
+import { LayersEnum } from '@lobechat/types';
+import debug from 'debug';
+import type { SQL } from 'drizzle-orm';
+import { and, cosineDistance, desc, eq, gte, inArray, lte, sql } from 'drizzle-orm';
+
+import {
+ buildBm25MatchCondition,
+ buildRetrievalQuery,
+ combineEmbeddings,
+ DEFAULT_HYBRID_SEARCH_LIMIT,
+ hasSearchFilters,
+ HYBRID_SEARCH_OVERFETCH_MULTIPLIER,
+ type HybridSearchLayerMeta,
+ type LayerBaseMemorySignals,
+ normalizeUserMemorySearchQueries,
+ type RankedSearchCandidate,
+ type RecommendationScoreBreakdown,
+ scoreHybridCandidates,
+ type SearchLayerKey,
+ shouldRunSemanticSearch,
+ shouldRunUserMemoryLexicalSearch,
+ toSearchTags,
+} from '@/database/models/userMemory';
+import { agentEvalMemories } from '@/database/schemas';
+
+import { tagsOf } from './entries';
+import { attemptWhere } from './where';
+
+type Payload = Record<string, any>;
+type Item = Record<string, unknown> & { id: string; tags: string[] };
+
+/** The layers the account's search ranks; experience memory is retired there too. */
+type SearchedLayer = 'activity' | 'context' | 'identity' | 'preference';
+
+interface LayerSpec {
+ layer: SearchedLayer;
+ /** The layer fields of the BM25 pass, as `payload` paths the index covers. */
+ lexicalFields: string[];
+}
+
+const LAYERS: Record<Exclude<SearchLayerKey, 'experiences'>, LayerSpec> = {
+ activities: { layer: 'activity', lexicalFields: ['narrative', 'notes', 'feedback'] },
+ contexts: { layer: 'context', lexicalFields: ['title', 'description', 'currentStatus'] },
+ identities: { layer: 'identity', lexicalFields: ['description', 'role'] },
+ preferences: { layer: 'preference', lexicalFields: ['conclusionDirectives', 'suggestions'] },
+};
+
+const HEADLINE_FIELDS = ['title', 'summary', 'details'];
+
+const log = debug('lobe-server:agentEvalMemory:search');
+const pgSearchByDb = new WeakMap<object, Promise<boolean>>();
+
+/** Whether the database can run the BM25 pass; without pg_search a queried lexical pass is skipped. */
+export const hasPgSearch = (db: LobeChatDatabase): Promise<boolean> => {
+ let known = pgSearchByDb.get(db);
+ if (!known) {
+ known = db
+ .execute(sql`SELECT 1 FROM pg_extension WHERE extname = 'pg_search'`)
+ .then((result) => result.rows.length > 0)
+ .catch(() => {
+ pgSearchByDb.delete(db);
+ log(
+ 'pg_search detection failed; skipping BM25 for this search and retrying on the next one',
+ );
+ return false;
+ });
+ pgSearchByDb.set(db, known);
+ }
+ return known;
+};
+
+const payloadText = (key: string) => sql`${agentEvalMemories.payload}->>${key}`;
+/** A payload date as a timestamp; anything that is not one is NULL rather than an error. */
+const payloadTimestamp = (key: string) =>
+ sql`CASE WHEN ${agentEvalMemories.payload}->>${key} ~ '^\\d{4}-\\d{2}-\\d{2}' THEN (${agentEvalMemories.payload}->>${key})::timestamptz END`;
+
+/**
+ * The column a time filter reads for a layer, as the account's search maps it
+ * (activities also by start and end, identities by episodic date). A seeded
+ * entry's clock is its `capturedAt`, which also stands for when it was
+ * created and updated.
+ */
+const timeColumn = (layer: SearchedLayer, field: string): SQL | undefined => {
+ switch (field) {
+ case 'capturedAt':
+ case 'createdAt':
+ case 'updatedAt': {
+ return sql`${agentEvalMemories.capturedAt}`;
+ }
+ case 'startsAt':
+ case 'endsAt': {
+ return layer === 'activity' ? payloadTimestamp(field) : undefined;
+ }
+ case 'episodicDate': {
+ return layer === 'identity' ? payloadTimestamp(field) : undefined;
+ }
+ default: {
+ return undefined;
+ }
+ }
+};
+
+const timeRangeCondition = (
+ layer: SearchedLayer,
+ timeRange: SearchMemoryParams['timeRange'],
+): SQL | undefined => {
+ if (!timeRange) return undefined;
+ const { end, field = 'capturedAt', start } = timeRange;
+ const column = timeColumn(layer, field);
+ if (!column) return sql`false`;
+ if (start && end) return and(gte(column, start), lte(column, end));
+ if (start) return gte(column, start);
+ if (end) return lte(column, end);
+ return undefined;
+};
+
+/** Every requested tag or label must be among the entry's tags (`tagsOf`). */
+const tagsCondition = (layer: SearchedLayer, params: SearchMemoryParams): SQL | undefined => {
+ const tags = toSearchTags(params);
+ if (tags.length === 0) return undefined;
+ const has = (tag: string) =>
+ layer === 'activity'
+ ? sql<boolean>`CASE WHEN jsonb_typeof(${agentEvalMemories.payload}->'tags') = 'array' THEN COALESCE(${agentEvalMemories.payload}->'tags' ? ${tag}, false) ELSE COALESCE(${agentEvalMemories.tags} ? ${tag}, false) END`
+ : sql<boolean>`COALESCE(${agentEvalMemories.tags} ? ${tag}, false)`;
+ return and(...tags.map(has));
+};
+
+/**
+ * The filters of one layer, read from the columns the account's search reads
+ * on its own tables: category from the entry, status / type / relationship
+ * from the layer part, with the defaults the Memory tool writes there.
+ */
+const layerConditions = (layer: SearchedLayer, params: SearchMemoryParams): SQL[] => {
+ const type =
+ layer === 'preference'
+ ? sql`${agentEvalMemories.memoryType}`
+ : layer === 'activity'
+ ? sql`COALESCE(${agentEvalMemories.payload}->>'type', 'other')`
+ : payloadText('type');
+ return [
+ eq(agentEvalMemories.layer, layer),
+ params.categories?.length
+ ? inArray(agentEvalMemories.memoryCategory, params.categories)
+ : undefined,
+ params.status?.length && layer === 'activity'
+ ? inArray(sql`COALESCE(${agentEvalMemories.payload}->>'status', 'pending')`, params.status)
+ : undefined,
+ params.status?.length && layer === 'context'
+ ? inArray(payloadText('currentStatus'), params.status)
+ : undefined,
+ params.relationships?.length && layer === 'identity'
+ ? inArray(payloadText('relationship'), params.relationships)
+ : undefined,
+ params.types?.length ? inArray(type, params.types) : undefined,
+ timeRangeCondition(layer, params.timeRange),
+ tagsCondition(layer, params),
+ ].filter((condition): condition is SQL => Boolean(condition));
+};
+
+const toDate = (value: unknown): Date | null => {
+ if (value instanceof Date) return value;
+ if (typeof value !== 'string' || !value) return null;
+ const date = new Date(value);
+ return Number.isNaN(date.getTime()) ? null : date;
+};
+
+/**
+ * An attempt row as the account's search returns the layer's row: the same
+ * fields, so the Memory tool formats it the same and the ranking reads the
+ * same words from it. Its clock is the entry's `capturedAt` throughout.
+ */
+export const toSearchItem = (row: AgentEvalMemoryItem, userId: string): Item => {
+ const p = row.payload as Payload;
+ const common = {
+ accessedAt: row.capturedAt,
+ capturedAt: row.capturedAt,
+ createdAt: row.capturedAt,
+ id: row.id,
+ tags: tagsOf(row),
+ updatedAt: row.capturedAt,
+ userId,
+ };
+ switch (row.layer) {
+ case 'preference': {
+ const suggestions = Array.isArray(p.suggestions)
+ ? p.suggestions.length > 0
+ ? p.suggestions.join('\n')
+ : null
+ : (p.suggestions ?? null);
+ return {
+ ...common,
+ appliesToEntityId: null,
+ conclusionDirectives: p.conclusionDirectives ?? row.summary ?? null,
+ evidenceCount: 1,
+ evidenceSource: null,
+ holderEntityId: null,
+ lastEvidenceAt: null,
+ metadata: {
+ appContext: p.appContext ?? null,
+ extractedScopes: p.extractedScopes ?? null,
+ originContext: p.originContext ?? null,
+ },
+ scope: null,
+ scorePriority: p.scorePriority ?? null,
+ suggestions,
+ type: row.memoryType ?? p.type ?? null,
+ userMemoryId: row.id,
+ };
+ }
+ case 'context': {
+ return {
+ ...common,
+ associatedObjects: p.associatedObjects ?? [],
+ associatedSubjects: p.associatedSubjects ?? [],
+ currentStatus: p.currentStatus ?? null,
+ description: p.description ?? row.summary ?? null,
+ firstSeenAt: null,
+ lastEvidenceAt: null,
+ metadata: {},
+ nextSteps: null,
+ now: null,
+ openQuestions: null,
+ scoreImpact: p.scoreImpact ?? null,
+ scoreUrgency: p.scoreUrgency ?? null,
+ synthesizedAt: null,
+ title: p.title ?? row.title ?? null,
+ type: p.type ?? null,
+ userMemoryId: row.id,
+ userMemoryIds: [row.id],
+ };
+ }
+ case 'activity': {
+ return {
+ ...common,
+ associatedLocations: p.associatedLocations ?? null,
+ associatedObjects: p.associatedObjects ?? [],
+ associatedSubjects: p.associatedSubjects ?? [],
+ dossierId: null,
+ endsAt: toDate(p.endsAt),
+ feedback: p.feedback ?? null,
+ injectable: true,
+ metadata: p.metadata ?? null,
+ narrative: p.narrative ?? row.summary ?? null,
+ notes: p.notes ?? null,
+ startsAt: toDate(p.startsAt),
+ status: p.status ?? 'pending',
+ timezone: p.timezone ?? null,
+ type: p.type ?? 'other',
+ userMemoryId: row.id,
+ };
+ }
+ case 'experience': {
+ return {
+ ...common,
+ action: p.action ?? null,
+ keyLearning: p.keyLearning ?? null,
+ metadata: null,
+ possibleOutcome: p.possibleOutcome ?? null,
+ reasoning: p.reasoning ?? null,
+ scoreConfidence: p.scoreConfidence ?? null,
+ situation: p.situation ?? row.summary ?? null,
+ type: p.type ?? row.memoryType ?? null,
+ userMemoryId: row.id,
+ };
+ }
+ default: {
+ const metadata: Record<string, unknown> = {};
+ if (p.scoreConfidence !== null && p.scoreConfidence !== undefined) {
+ metadata.scoreConfidence = p.scoreConfidence;
+ }
+ if (p.sourceEvidence !== null && p.sourceEvidence !== undefined) {
+ metadata.sourceEvidence = p.sourceEvidence;
+ }
+ return {
+ ...common,
+ description: p.description ?? row.summary ?? null,
+ entityId: null,
+ episodicDate: toDate(p.episodicDate),
+ metadata: Object.keys(metadata).length > 0 ? metadata : null,
+ relationship: p.relationship ?? null,
+ role: p.role ?? null,
+ type: p.type ?? row.memoryType ?? null,
+ userMemoryId: row.id,
+ };
+ }
+ }
+};
+
+export interface SearchEvalMemoryOptions {
+ db: LobeChatDatabase;
+ /** Normalized parameters with the effort's per-layer `topK` already resolved. */
+ params: SearchMemoryParams;
+ queryEmbeddings: number[][];
+ reference: EvalMemoryReference;
+ userId: string;
+}
+
+/**
+ * The account's hybrid Memory search, run over an attempt's own entries. Per
+ * layer it takes the same two candidate passes the account's search takes on
+ * its tables (the nearest entries by the layer's vector; the newest entries
+ * whose words all match, through the same BM25 index definition), merges them
+ * and ranks them with the account's scorer, so the same entries come back in
+ * the same order for the same query. Without pg_search a queried lexical pass
+ * cannot run and is left out; the filter-only pass and the semantic pass still
+ * run.
+ */
+export const searchEvalMemory = async (
+ options: SearchEvalMemoryOptions,
+): Promise<SearchMemoryResult> => {
+ const { db, params, queryEmbeddings, reference, userId } = options;
+ const appliedQueries = normalizeUserMemorySearchQueries(params.queries);
+ const lexicalSearch = shouldRunUserMemoryLexicalSearch(appliedQueries, queryEmbeddings);
+ const retrievalQuery = buildRetrievalQuery(appliedQueries);
+ const semanticEmbedding = combineEmbeddings(queryEmbeddings);
+ const semanticSearch =
+ !!semanticEmbedding && shouldRunSemanticSearch(appliedQueries.length, queryEmbeddings.length);
+ const unembedded = appliedQueries.length > 0 && !semanticEmbedding;
+ const bm25 = retrievalQuery && lexicalSearch ? await hasPgSearch(db) : false;
+ const limits: Record<SearchLayerKey, number> = {
+ activities: params.topK?.activities ?? DEFAULT_HYBRID_SEARCH_LIMIT,
+ contexts: params.topK?.contexts ?? DEFAULT_HYBRID_SEARCH_LIMIT,
+ experiences: params.topK?.experiences ?? DEFAULT_HYBRID_SEARCH_LIMIT,
+ identities: params.topK?.identities ?? DEFAULT_HYBRID_SEARCH_LIMIT,
+ preferences: params.topK?.preferences ?? DEFAULT_HYBRID_SEARCH_LIMIT,
+ };
+ const requestedLayers = new Set(
+ (params.layers ?? Object.values(LayersEnum)).map(String).filter((layer) => {
+ switch (layer) {
+ case LayersEnum.Activity: {
+ return limits.activities > 0;
+ }
+ case LayersEnum.Context: {
+ return limits.contexts > 0;
+ }
+ case LayersEnum.Identity: {
+ return limits.identities > 0;
+ }
+ case LayersEnum.Preference: {
+ return limits.preferences > 0;
+ }
+ default: {
+ return false;
+ }
+ }
+ }),
+ );
+
+ const own = attemptWhere(userId, reference);
+
+ const searchLayer = async (
+ key: Exclude<SearchLayerKey, 'experiences'>,
+ ): Promise<RankedSearchCandidate<Item>[]> => {
+ const spec = LAYERS[key];
+ if (!requestedLayers.has(spec.layer)) return [];
+ const limit = limits[key] * HYBRID_SEARCH_OVERFETCH_MULTIPLIER;
+ const conditions = layerConditions(spec.layer, params);
+
+ // Simplified path, when the account has no usable embedding model: an
+ // attempt holds a handful of entries, so instead of the nearest ones every
+ // entry of the layer is a candidate, newest first, and the scorer ranks
+ // them by the query's words and recency.
+ const semanticLists: AgentEvalMemoryItem[][] = unembedded
+ ? [
+ await db
+ .select()
+ .from(agentEvalMemories)
+ .where(and(own, ...conditions))
+ .orderBy(desc(agentEvalMemories.capturedAt), desc(agentEvalMemories.createdAt))
+ .limit(limit),
+ ]
+ : semanticSearch
+ ? [
+ await db
+ .select()
+ .from(agentEvalMemories)
+ .where(and(own, ...conditions))
+ .orderBy(
+ desc(sql`1 - (${cosineDistance(agentEvalMemories.embedding, semanticEmbedding!)})`),
+ ...(spec.layer === 'context' ? [desc(agentEvalMemories.createdAt)] : []),
+ )
+ .limit(limit),
+ ]
+ : [];
+
+ const lexicalLists: AgentEvalMemoryItem[][] =
+ lexicalSearch && (retrievalQuery || hasSearchFilters(params)) && (!retrievalQuery || bm25)
+ ? [
+ await db
+ .select()
+ .from(agentEvalMemories)
+ .where(
+ and(
+ own,
+ ...conditions,
+ retrievalQuery
+ ? buildBm25MatchCondition(retrievalQuery, [
+ {
+ fields: [
+ ...HEADLINE_FIELDS,
+ ...spec.lexicalFields.map((field) => `payload.${field}`),
+ ],
+ keyColumn: agentEvalMemories.id,
+ },
+ ])
+ : undefined,
+ ),
+ )
+ .orderBy(desc(agentEvalMemories.capturedAt), desc(agentEvalMemories.createdAt))
+ .limit(limit),
+ ]
+ : [];
+
+ const items = new Map<string, Item>();
+ const baseSignals = new Map<string, LayerBaseMemorySignals>();
+ for (const row of [...semanticLists.flat(), ...lexicalLists.flat()]) {
+ if (items.has(row.id)) continue;
+ items.set(row.id, toSearchItem(row, userId));
+ baseSignals.set(row.id, {
+ categories: row.memoryCategory ? [row.memoryCategory] : [],
+ memoryIds: [row.id],
+ tags: tagsOf(row),
+ times: [row.capturedAt.getTime()],
+ });
+ }
+ const asItems = (rows: AgentEvalMemoryItem[]) => rows.map((row) => items.get(row.id)!);
+
+ return scoreHybridCandidates<Item>({
+ baseSignals,
+ items: [...items.values()],
+ lexicalLists: lexicalLists.map(asItems),
+ // Same as the account's Memory (`searchHybrid*`): a query too long for
+ // the lexical pass is not fuzzy-matched either.
+ queries: lexicalSearch ? appliedQueries : [],
+ queryParams: params,
+ semanticLists: semanticLists.map(asItems),
+ });
+ };
+
+ const [activities, contexts, identities, preferences] = await Promise.all([
+ searchLayer('activities'),
+ searchLayer('contexts'),
+ searchLayer('identities'),
+ searchLayer('preferences'),
+ ]);
+
+ const layerMeta: Record<SearchLayerKey, HybridSearchLayerMeta> = {
+ activities: { hasMore: false, returned: 0, total: 0 },
+ contexts: { hasMore: false, returned: 0, total: 0 },
+ experiences: { hasMore: false, returned: 0, total: 0 },
+ identities: { hasMore: false, returned: 0, total: 0 },
+ preferences: { hasMore: false, returned: 0, total: 0 },
+ };
+ const ranking: Partial<Record<SearchLayerKey, Record<string, RecommendationScoreBreakdown>>> = {};
+ const finalizeLayer = (key: SearchLayerKey, ranked: RankedSearchCandidate<Item>[]) => {
+ const limit = limits[key];
+ const sorted = ranked.sort((left, right) => right.score.final - left.score.final);
+ const selected = sorted.slice(0, limit);
+ ranking[key] = Object.fromEntries(selected.map((entry) => [entry.item.id, entry.score]));
+ layerMeta[key] = {
+ hasMore: sorted.length > limit,
+ returned: selected.length,
+ total: sorted.length,
+ };
+ return selected.map((entry) => entry.item);
+ };
+
+ return {
+ activities: finalizeLayer('activities', activities),
+ contexts: finalizeLayer('contexts', contexts),
+ experiences: finalizeLayer('experiences', []),
+ identities: finalizeLayer('identities', identities),
+ meta: {
+ appliedFilters: {
+ categories: params.categories,
+ labels: params.labels,
+ layers: params.layers,
+ queries: appliedQueries,
+ relationships: params.relationships,
+ status: params.status,
+ tags: params.tags,
+ timeRange: params.timeRange,
+ types: params.types,
+ },
+ appliedQueries,
+ layers: layerMeta,
+ ranking,
+ },
+ preferences: finalizeLayer('preferences', preferences),
+ } as unknown as SearchMemoryResult;
+};
diff --git a/apps/server/src/services/agentEvalMemory/where.ts b/apps/server/src/services/agentEvalMemory/where.ts
new file mode 100644
index 00000000000..ae945506d28
--- /dev/null
+++ b/apps/server/src/services/agentEvalMemory/where.ts
@@ -0,0 +1,23 @@
+import type { EvalMemoryReference } from '@lobechat/types';
+import { and, eq, isNull, type SQL } from 'drizzle-orm';
+
+import { agentEvalMemories } from '@/database/schemas';
+import { getEvalAttemptId } from '@/server/services/agentEvalRun/utils';
+
+/** Rows of one attempt owned by this caller; removed entries stay out unless asked for. */
+export const attemptWhere = (
+ userId: string,
+ reference: Pick<EvalMemoryReference, 'runId' | 'threadId' | 'topicId'>,
+ options: { includeRemoved?: boolean } = {},
+): SQL =>
+ and(
+ eq(agentEvalMemories.userId, userId),
+ eq(agentEvalMemories.runId, reference.runId),
+ // Keep deleted-thread evidence out of the parent attempt's null-thread scope.
+ eq(agentEvalMemories.attemptId, getEvalAttemptId(reference)),
+ eq(agentEvalMemories.topicId, reference.topicId),
+ reference.threadId
+ ? eq(agentEvalMemories.threadId, reference.threadId)
+ : isNull(agentEvalMemories.threadId),
+ options.includeRemoved ? undefined : isNull(agentEvalMemories.removedReason),
+ ) as SQL;
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.caseAgent.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.caseAgent.test.ts
new file mode 100644
index 00000000000..93f8916f295
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.caseAgent.test.ts
@@ -0,0 +1,275 @@
+import { and, eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentEvalBenchmarkModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';
+import { agentEvalDatasets, agentEvalTestCases, agents, topics } from '@/database/schemas';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+import { CASE_AGENT_MODEL_REQUIRED } from '@/server/services/agentEvalRun/caseAgent';
+
+import { cleanupDB, serverDB, userId } from './_setup';
+
+vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return { interruptOperation: vi.fn().mockResolvedValue(true) };
+ }),
+}));
+
+vi.mock('@/server/workflows/agentEvalRun', () => ({
+ AgentEvalRunWorkflow: { triggerRunThreadTrajectory: vi.fn() },
+}));
+
+const mockExecAgent = vi.fn();
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(function () {
+ return { execAgent: mockExecAgent };
+ }),
+}));
+
+beforeEach(async () => {
+ await cleanupDB();
+ mockExecAgent.mockReset();
+});
+
+const createDataset = async (
+ cases: Array<{
+ agent?: { name?: string; plugins?: string[]; systemRole?: string; title?: string };
+ input: string;
+ }>,
+) => {
+ const benchmark = await new AgentEvalBenchmarkModel(serverDB, userId).create({
+ identifier: 'bench',
+ isSystem: false,
+ name: 'Bench',
+ rubrics: [],
+ });
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({ benchmarkId: benchmark.id, identifier: 'bench-v1', name: 'Bench v1', userId })
+ .returning();
+
+ const testCases = [];
+ for (const [index, item] of cases.entries()) {
+ const [testCase] = await serverDB
+ .insert(agentEvalTestCases)
+ .values({
+ content: {
+ input: item.input,
+ ...(item.agent && { environment: { agent: item.agent } }),
+ },
+ datasetId: dataset.id,
+ metadata: { caseId: `case-${index + 1}` },
+ sortOrder: index,
+ userId,
+ })
+ .returning();
+ testCases.push(testCase);
+ }
+
+ return { dataset, testCases };
+};
+
+const topicAgentOf = async (runId: string, testCaseId: string) => {
+ const runTopic = await new AgentEvalRunTopicModel(serverDB, userId).findByRunAndTestCase(
+ runId,
+ testCaseId,
+ );
+ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, runTopic!.topicId));
+ return topic.agentId;
+};
+
+const hiddenAgents = () =>
+ serverDB
+ .select()
+ .from(agents)
+ .where(and(eq(agents.userId, userId), eq(agents.virtual, true)));
+
+describe('AgentEvalRunService case Agents', () => {
+ it('runs each case of a model-only run on its own hidden Agent built from the case setup', async () => {
+ const { dataset, testCases } = await createDataset([
+ { agent: { plugins: ['shopify'], systemRole: 'You run a store.' }, input: 'Check orders' },
+ { agent: { plugins: [], systemRole: 'You are a coach.' }, input: 'Plan my week' },
+ ]);
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ const run = await service.createRun({
+ config: { model: 'gpt-4.1-mini', provider: 'openai' },
+ datasetId: dataset.id,
+ });
+
+ const created = await hiddenAgents();
+ expect(created).toHaveLength(2);
+
+ for (const testCase of testCases) {
+ const agentId = await topicAgentOf(run.id, testCase.id);
+ const agent = created.find((item) => item.id === agentId)!;
+ const setup = (testCase.content as any).environment.agent;
+
+ expect(agent.virtual).toBe(true);
+ expect(agent.systemRole).toBe(setup.systemRole);
+ expect(agent.plugins).toEqual(setup.plugins);
+ expect(agent.model).toBe('gpt-4.1-mini');
+ expect(agent.provider).toBe('openai');
+ expect(agent.slug).toBe(`eval-${run.id}-${testCase.id}`);
+ // No identity line reaches the prompt unless the case declares one.
+ expect(agent.name).toBeNull();
+ expect(agent.title).toBeNull();
+ }
+ });
+
+ it('applies the contender settings of a model-only run to every hidden Agent', async () => {
+ const { dataset, testCases } = await createDataset([
+ { agent: { plugins: [], systemRole: 'You run a store.' }, input: 'Check orders' },
+ ]);
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ const run = await service.createRun({
+ config: {
+ chatConfig: { reasoningEffort: 'high', thinkingBudget: 4096 },
+ model: 'gpt-4.1-mini',
+ params: { temperature: 0.2, top_p: 0.9 },
+ provider: 'openai',
+ },
+ datasetId: dataset.id,
+ });
+
+ const agentId = await topicAgentOf(run.id, testCases[0].id);
+ const agent = (await hiddenAgents()).find((item) => item.id === agentId)!;
+
+ // The same model with other settings is another contender, so the settings
+ // must reach the Agent that actually answers.
+ expect(agent.params).toMatchObject({ temperature: 0.2, top_p: 0.9 });
+ expect(agent.chatConfig).toMatchObject({ reasoningEffort: 'high', thinkingBudget: 4096 });
+ });
+
+ it('gives the hidden Agent only the identity the case declares', async () => {
+ const { dataset, testCases } = await createDataset([
+ {
+ agent: { name: 'Juniper', systemRole: 'You run a tea shop.', title: 'Shop assistant' },
+ input: 'Hi',
+ },
+ ]);
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ const run = await service.createRun({
+ config: { model: 'gpt-4.1-mini', provider: 'openai' },
+ datasetId: dataset.id,
+ });
+
+ const agentId = await topicAgentOf(run.id, testCases[0].id);
+ const [agent] = await serverDB.select().from(agents).where(eq(agents.id, agentId!));
+ expect(agent.name).toBe('Juniper');
+ expect(agent.title).toBe('Shop assistant');
+ });
+
+ it('keeps cases without a setup on the target Agent when the run picks no model', async () => {
+ const { dataset, testCases } = await createDataset([{ input: 'Plain question' }]);
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ const run = await service.createRun({ datasetId: dataset.id });
+
+ expect(await hiddenAgents()).toHaveLength(0);
+ expect(await topicAgentOf(run.id, testCases[0].id)).toBeNull();
+ });
+
+ it('rejects a case setup when neither a target Agent nor a model is chosen', async () => {
+ const { dataset } = await createDataset([
+ { agent: { systemRole: 'You run a store.' }, input: 'Check orders' },
+ ]);
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ await expect(service.createRun({ datasetId: dataset.id })).rejects.toThrow(
+ CASE_AGENT_MODEL_REQUIRED,
+ );
+ expect(await hiddenAgents()).toHaveLength(0);
+ });
+
+ it('reuses the hidden Agent when a case is retried', async () => {
+ const { dataset, testCases } = await createDataset([
+ { agent: { systemRole: 'You run a store.' }, input: 'Check orders' },
+ ]);
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ const run = await service.createRun({
+ config: { model: 'gpt-4.1-mini', provider: 'openai' },
+ datasetId: dataset.id,
+ });
+ const before = await topicAgentOf(run.id, testCases[0].id);
+
+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);
+ const runTopic = await runTopicModel.findByRunAndTestCase(run.id, testCases[0].id);
+ await runTopicModel.updateByRunAndTopic(run.id, runTopic!.topicId, { status: 'error' });
+ await service.retrySingleCase(run.id, testCases[0].id);
+
+ expect(await topicAgentOf(run.id, testCases[0].id)).toBe(before);
+ expect(await hiddenAgents()).toHaveLength(1);
+ });
+
+ it('executes each case on the Agent its topic belongs to', async () => {
+ const { dataset, testCases } = await createDataset([
+ { agent: { systemRole: 'You run a store.' }, input: 'Check orders' },
+ ]);
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ const run = await service.createRun({
+ config: { model: 'gpt-4.1-mini', provider: 'openai' },
+ datasetId: dataset.id,
+ });
+ mockExecAgent.mockResolvedValue({ operationId: 'op-1' });
+
+ await service.executeTrajectory({
+ run: { config: run.config, datasetId: dataset.id, targetAgentId: null },
+ runId: run.id,
+ testCase: { content: { input: 'Check orders' }, sortOrder: 0 },
+ testCaseId: testCases[0].id,
+ });
+
+ expect(mockExecAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: await topicAgentOf(run.id, testCases[0].id) }),
+ );
+ });
+
+ it('hands the contender settings to execAgent as its override', async () => {
+ const { dataset, testCases } = await createDataset([
+ { agent: { systemRole: 'You run a store.' }, input: 'Check orders' },
+ ]);
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ const chatConfig = { enableReasoning: true, gpt5_6ReasoningEffort: 'high' as const };
+ const run = await service.createRun({
+ config: { chatConfig, model: 'gpt-6.1-terra', provider: 'openrouter' },
+ datasetId: dataset.id,
+ });
+ mockExecAgent.mockResolvedValue({ operationId: 'op-1' });
+
+ await service.executeTrajectory({
+ run: { config: run.config, datasetId: dataset.id, targetAgentId: null },
+ runId: run.id,
+ testCase: { content: { input: 'Check orders' }, sortOrder: 0 },
+ testCaseId: testCases[0].id,
+ });
+
+ // The runtime takes reasoning effort from the account's saved per-model
+ // defaults unless an override names it: the run must use what it records.
+ expect(mockExecAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ chatConfigOverride: chatConfig }),
+ );
+ });
+
+ it('deletes the hidden Agents with the run', async () => {
+ const { dataset } = await createDataset([
+ { agent: { systemRole: 'You run a store.' }, input: 'Check orders' },
+ { agent: { systemRole: 'You are a coach.' }, input: 'Plan my week' },
+ ]);
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ const run = await service.createRun({
+ config: { model: 'gpt-4.1-mini', provider: 'openai' },
+ datasetId: dataset.id,
+ });
+ expect(await hiddenAgents()).toHaveLength(2);
+
+ await service.deleteRun(run.id);
+
+ expect(await hiddenAgents()).toHaveLength(0);
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.caseCompatibility.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.caseCompatibility.test.ts
new file mode 100644
index 00000000000..2d3a9248257
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.caseCompatibility.test.ts
@@ -0,0 +1,65 @@
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { AgentEvalRunModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';
+import { agentEvalDatasets, agentEvalTestCases, messages } from '@/database/schemas';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+import { EvalCaseCompatibilityError } from '@/server/services/agentEvalRun/caseCompatibility';
+
+import { cleanupDB, serverDB, setupEvalChain, userId } from './_setup';
+
+beforeEach(cleanupDB);
+
+describe.each(['rejudge', 'rerun', 'retryErrors', 'retrySingle'] as const)(
+ '%s case compatibility',
+ (action) => {
+ it.each(['changed version', 'retired case'] as const)(
+ 'preserves every recorded row when rejecting a %s',
+ async (reason) => {
+ const chain = await setupEvalChain({
+ assistantOutput: '42',
+ datasetEvalMode: 'contains',
+ totalCases: 1,
+ });
+ const runModel = new AgentEvalRunModel(serverDB, userId);
+ const runTopics = new AgentEvalRunTopicModel(serverDB, userId);
+ await runModel.update(chain.run.id, { config: { caseVersion: 'v1' }, status: 'completed' });
+ await serverDB
+ .update(agentEvalDatasets)
+ .set({
+ metadata: { release: reason === 'changed version' ? 'v2' : 'v1' },
+ })
+ .where(eq(agentEvalDatasets.id, chain.dataset.id));
+ if (reason === 'retired case') {
+ await serverDB
+ .update(agentEvalTestCases)
+ .set({ metadata: { retired: true } })
+ .where(eq(agentEvalTestCases.id, chain.testCase.id));
+ }
+ await runTopics.updateByRunAndTopic(chain.run.id, chain.topic.id, {
+ evalResult: {
+ error: action === 'rejudge' ? undefined : 'Provider unavailable',
+ externalResult: { evidence: 'Original judgment' },
+ },
+ passed: action === 'rejudge',
+ score: action === 'rejudge' ? 1 : undefined,
+ status: action === 'rejudge' ? 'passed' : 'error',
+ });
+ const originalRun = await runModel.findById(chain.run.id);
+ const originalTopics = await runTopics.findByRunId(chain.run.id);
+ const originalMessages = await serverDB.select().from(messages);
+ const service = new AgentEvalRunService(serverDB, userId);
+ const attempt = () => {
+ if (action === 'rejudge') return service.rejudgeRun(chain.run.id);
+ if (action === 'rerun') return service.rerunUnverifiedCases(chain.run.id);
+ if (action === 'retryErrors') return service.retryErrorCases(chain.run.id);
+ return service.retrySingleCase(chain.run.id, chain.testCase.id);
+ };
+ await expect(attempt()).rejects.toThrow(EvalCaseCompatibilityError);
+ expect(await runModel.findById(chain.run.id)).toEqual(originalRun);
+ expect(await runTopics.findByRunId(chain.run.id)).toEqual(originalTopics);
+ expect(await serverDB.select().from(messages)).toEqual(originalMessages);
+ },
+ );
+ },
+);
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRun.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRun.test.ts
index 161f00f8942..14147093c9b 100644
--- a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRun.test.ts
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRun.test.ts
@@ -92,7 +92,42 @@ describe('AgentEvalRunService', () => {
}
});
- it('should store caseSelection without changing internal topic pre-creation', async () => {
+ it('records the version of the cases the run is made on, and a retry still matches', async () => {
+ const benchmark = await new AgentEvalBenchmarkModel(serverDB, userId).create({
+ identifier: 'versioned-benchmark',
+ isSystem: false,
+ name: 'Versioned Benchmark',
+ rubrics: [],
+ });
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({
+ benchmarkId: benchmark.id,
+ identifier: 'versioned-dataset',
+ metadata: { presentation: 'realism-v3', release: '2026-10-30-realism-v4' },
+ name: 'Versioned Dataset',
+ userId,
+ })
+ .returning();
+ await serverDB.insert(agentEvalTestCases).values({
+ content: { expected: '42', input: 'Question' },
+ datasetId: dataset.id,
+ sortOrder: 1,
+ userId,
+ });
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ const params = { config: { k: 1 }, datasetId: dataset.id, id: 'run_versioned01' };
+ const run = await service.createRun(params);
+ expect((run.config as { caseVersion?: string }).caseVersion).toBe(
+ '2026-10-30-realism-v4+realism-v3',
+ );
+ // The version is captured server-side, so the same create sent again is the same run.
+ const again = await service.createRun(params);
+ expect(again.id).toBe(run.id);
+ });
+
+ it('pre-creates topics only for the cases the caseSelection keeps', async () => {
const benchmarkModel = new AgentEvalBenchmarkModel(serverDB, userId);
const benchmark = await benchmarkModel.create({
identifier: 'test-benchmark',
@@ -128,9 +163,28 @@ describe('AgentEvalRunService', () => {
// Stored verbatim
expect((run.config as any).caseSelection).toEqual(caseSelection);
- // Storage-only scope: internal pre-creation is unaffected (all cases)
+ // Only the selected case gets a topic; the other case is not part of this run.
const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);
- expect(await runTopicModel.findByRunId(run.id)).toHaveLength(2);
+ const runTopics = await runTopicModel.findByRunId(run.id);
+ expect(runTopics).toHaveLength(1);
+ const [selected] = await serverDB
+ .select()
+ .from(agentEvalTestCases)
+ .where(eq(agentEvalTestCases.id, runTopics[0].testCaseId));
+ expect(selected.metadata).toEqual({ caseId: 'case_1' });
+
+ // Excluding works the same way, and an unknown id is refused instead of skipped.
+ const excluded = await service.createRun({
+ config: { caseSelection: { caseIds: ['case_1'], mode: 'exclude' } },
+ datasetId: dataset.id,
+ });
+ expect(await runTopicModel.findByRunId(excluded.id)).toHaveLength(1);
+ await expect(
+ service.createRun({
+ config: { caseSelection: { caseIds: ['case_9'], mode: 'include' } },
+ datasetId: dataset.id,
+ }),
+ ).rejects.toThrow('not in the dataset');
});
it('should restore case messages and use their tail as the eval-thread source', async () => {
@@ -286,7 +340,7 @@ describe('AgentEvalRunService', () => {
expect(topic.metadata?.evalHistoryTailMessageId).toBe(restored.at(-1)?.id);
});
- it('should handle dataset with no test cases', async () => {
+ it('rejects an internal run on a dataset with no test cases', async () => {
const benchmarkModel = new AgentEvalBenchmarkModel(serverDB, userId);
const benchmark = await benchmarkModel.create({
identifier: 'empty-benchmark',
@@ -306,13 +360,9 @@ describe('AgentEvalRunService', () => {
.returning();
const service = new AgentEvalRunService(serverDB, userId);
- const run = await service.createRun({ datasetId: dataset.id, name: 'Empty Test' });
-
- const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);
- const runTopics = await runTopicModel.findByRunId(run.id);
-
- expect(runTopics).toHaveLength(0);
- expect(run.id).toBeTruthy();
+ await expect(
+ service.createRun({ datasetId: dataset.id, name: 'Empty Test' }),
+ ).rejects.toThrow('Select at least one test case');
});
});
});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRunAtomic.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRunAtomic.test.ts
new file mode 100644
index 00000000000..cfcc821d02f
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.createRunAtomic.test.ts
@@ -0,0 +1,89 @@
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { AgentEvalBenchmarkModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';
+import {
+ agentEvalDatasets,
+ agentEvalRuns,
+ agentEvalTestCases,
+ agents,
+ topics,
+} from '@/database/schemas';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+import { CASE_AGENT_MODEL_REQUIRED } from '@/server/services/agentEvalRun/caseAgent';
+
+import { cleanupDB, serverDB, userId } from './_setup';
+
+beforeEach(cleanupDB);
+
+const createDataset = async (withAgent = false) => {
+ const benchmark = await new AgentEvalBenchmarkModel(serverDB, userId).create({
+ identifier: 'atomic-run',
+ name: 'Atomic run',
+ isSystem: false,
+ rubrics: [],
+ });
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({ benchmarkId: benchmark.id, identifier: 'atomic-dataset', name: 'Cases', userId })
+ .returning();
+ const [testCase] = await serverDB
+ .insert(agentEvalTestCases)
+ .values({
+ content: {
+ input: 'A question',
+ ...(withAgent && { environment: { agent: { systemRole: 'A case agent' } } }),
+ },
+ datasetId: dataset.id,
+ metadata: { caseId: 'question-1' },
+ userId,
+ })
+ .returning();
+ return { dataset, testCase };
+};
+
+describe('run creation persistence', () => {
+ it('rolls back a failed case setup so the same id can be retried with corrected config', async () => {
+ const { dataset } = await createDataset(true);
+ const service = new AgentEvalRunService(serverDB, userId);
+ const params = { datasetId: dataset.id, id: 'run_atomic01' };
+
+ await expect(service.createRun(params)).rejects.toThrow(CASE_AGENT_MODEL_REQUIRED);
+ expect(await serverDB.select().from(agentEvalRuns)).toHaveLength(0);
+ expect(await serverDB.select().from(topics)).toHaveLength(0);
+ expect(await serverDB.select().from(agents).where(eq(agents.virtual, true))).toHaveLength(0);
+
+ const corrected = { ...params, config: { model: 'test-model', provider: 'openai' } };
+ const run = await service.createRun(corrected);
+ expect(run.id).toBe(params.id);
+ expect(await new AgentEvalRunTopicModel(serverDB, userId).findByRunId(run.id)).toHaveLength(1);
+ expect((await service.createRun(corrected)).id).toBe(run.id);
+ expect(await serverDB.select().from(agentEvalRuns)).toHaveLength(1);
+ });
+
+ it('rejects an exclude-all selection without leaving a run or topics', async () => {
+ const { dataset } = await createDataset();
+ const service = new AgentEvalRunService(serverDB, userId);
+
+ await expect(
+ service.createRun({
+ config: { caseSelection: { caseIds: ['question-1'], mode: 'exclude' } },
+ datasetId: dataset.id,
+ id: 'run_empty01',
+ }),
+ ).rejects.toThrow('Select at least one test case');
+ expect(await serverDB.select().from(agentEvalRuns)).toHaveLength(0);
+ expect(await serverDB.select().from(topics)).toHaveLength(0);
+ });
+
+ it('leaves selection to the external worker and keeps its no-topics creation contract', async () => {
+ const { dataset } = await createDataset();
+ const run = await new AgentEvalRunService(serverDB, userId).createRun({
+ config: { caseSelection: { caseIds: ['question-1'], mode: 'exclude' } },
+ datasetId: dataset.id,
+ mode: 'external',
+ });
+ expect(run.status).toBe('pending');
+ expect(await new AgentEvalRunTopicModel(serverDB, userId).findByRunId(run.id)).toHaveLength(0);
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.environment.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.environment.test.ts
new file mode 100644
index 00000000000..15bcfef18e8
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.environment.test.ts
@@ -0,0 +1,167 @@
+import { and, eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ AgentEvalBenchmarkModel,
+ AgentEvalEnvironmentModel,
+ AgentEvalRunTopicModel,
+} from '@/database/models/agentEval';
+import {
+ agentEvalDatasets,
+ agentEvalEnvironments,
+ agentEvalTestCases,
+ agents,
+ topics,
+} from '@/database/schemas';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+import { mergeCaseEnvironment } from '@/server/services/agentEvalRun/caseEnvironment';
+
+import { cleanupDB, serverDB, userId } from './_setup';
+
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(function () {
+ return { execAgent: vi.fn() };
+ }),
+}));
+
+const cleanup = async () => {
+ await cleanupDB();
+ await serverDB.delete(agentEvalEnvironments);
+};
+
+describe('mergeCaseEnvironment', () => {
+ it('lays the case overrides over the shared environment, field by field', () => {
+ const shared = {
+ agent: { memory: { enabled: true }, plugins: ['gmail', 'notion'], systemRole: 'You help.' },
+ mock: { services: ['gmail', 'notion'] },
+ sessionDate: '2026-07-21',
+ timezone: 'Asia/Shanghai',
+ };
+ expect(
+ mergeCaseEnvironment(shared, {
+ agent: { plugins: ['gmail'] },
+ sessionDate: '2026-07-22',
+ }),
+ ).toEqual({
+ agent: { memory: { enabled: true }, plugins: ['gmail'], systemRole: 'You help.' },
+ mock: { services: ['gmail', 'notion'] },
+ sessionDate: '2026-07-22',
+ timezone: 'Asia/Shanghai',
+ });
+ expect(mergeCaseEnvironment(shared, undefined)).toEqual(shared);
+ expect(mergeCaseEnvironment(undefined, { sessionDate: '2026-01-01' })).toEqual({
+ sessionDate: '2026-01-01',
+ });
+ });
+});
+
+describe('shared environments', () => {
+ beforeEach(cleanup);
+
+ it('runs a case on its shared environment and lets the case tweak it', async () => {
+ const environmentModel = new AgentEvalEnvironmentModel(serverDB, userId);
+ const environment = await environmentModel.create({
+ config: {
+ agent: { plugins: ['shopify'], systemRole: 'You run a store.' },
+ sessionDate: '2026-07-21',
+ },
+ identifier: 'store',
+ name: 'Store clerk',
+ });
+
+ const benchmark = await new AgentEvalBenchmarkModel(serverDB, userId).create({
+ identifier: 'bench',
+ isSystem: false,
+ name: 'Bench',
+ rubrics: [],
+ });
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({ benchmarkId: benchmark.id, identifier: 'bench-v1', name: 'Bench v1', userId })
+ .returning();
+ const [shared] = await serverDB
+ .insert(agentEvalTestCases)
+ .values({
+ content: { input: 'Check orders' },
+ datasetId: dataset.id,
+ environmentId: environment.id,
+ sortOrder: 0,
+ userId,
+ })
+ .returning();
+ const [tweaked] = await serverDB
+ .insert(agentEvalTestCases)
+ .values({
+ content: { environment: { sessionDate: '2026-07-22' }, input: 'Check returns' },
+ datasetId: dataset.id,
+ environmentId: environment.id,
+ sortOrder: 1,
+ userId,
+ })
+ .returning();
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ const run = await service.createRun({
+ config: { model: 'gpt-4.1-mini', provider: 'openai' },
+ datasetId: dataset.id,
+ });
+
+ // Both cases got a hidden Agent built from the shared environment.
+ const created = await serverDB
+ .select()
+ .from(agents)
+ .where(and(eq(agents.userId, userId), eq(agents.virtual, true)));
+ expect(created).toHaveLength(2);
+ for (const agent of created) {
+ expect(agent.systemRole).toBe('You run a store.');
+ expect(agent.plugins).toEqual(['shopify']);
+ }
+
+ // The attempt environment carries the merged result: shared clock, or the case's own.
+ const loaded = await service.loadTrajectoryData(run.id, tweaked.id);
+ expect('environment' in loaded && loaded.environment?.sessionDate).toBe('2026-07-22');
+ expect('environment' in loaded && loaded.environment?.agent?.systemRole).toBe(
+ 'You run a store.',
+ );
+ const loadedShared = await service.loadTrajectoryData(run.id, shared.id);
+ expect('environment' in loadedShared && loadedShared.environment?.sessionDate).toBe(
+ '2026-07-21',
+ );
+
+ // Each case still has its own topic and run topic.
+ const runTopics = await new AgentEvalRunTopicModel(serverDB, userId).findByRunId(run.id);
+ expect(runTopics).toHaveLength(2);
+ const topicRows = await serverDB.select().from(topics).where(eq(topics.userId, userId));
+ expect(topicRows).toHaveLength(2);
+ });
+
+ it('counts the cases pointing at each environment', async () => {
+ const environmentModel = new AgentEvalEnvironmentModel(serverDB, userId);
+ const environment = await environmentModel.create({ config: {}, name: 'Empty' });
+ const benchmark = await new AgentEvalBenchmarkModel(serverDB, userId).create({
+ identifier: 'bench',
+ isSystem: false,
+ name: 'Bench',
+ rubrics: [],
+ });
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({ benchmarkId: benchmark.id, identifier: 'bench-v1', name: 'Bench v1', userId })
+ .returning();
+ await serverDB.insert(agentEvalTestCases).values([
+ { content: { input: 'a' }, datasetId: dataset.id, environmentId: environment.id, userId },
+ { content: { input: 'b' }, datasetId: dataset.id, environmentId: environment.id, userId },
+ { content: { input: 'c' }, datasetId: dataset.id, userId },
+ ]);
+
+ const [row] = await environmentModel.query();
+ expect(row.id).toBe(environment.id);
+ expect(row.testCaseCount).toBe(2);
+
+ // Deleting the environment detaches its cases instead of deleting them.
+ await environmentModel.delete(environment.id);
+ const cases = await serverDB.select().from(agentEvalTestCases);
+ expect(cases).toHaveLength(3);
+ expect(cases.every((item) => item.environmentId === null)).toBe(true);
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.evaluate.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.evaluate.test.ts
index a9bc084c98f..cd40f95478a 100644
--- a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.evaluate.test.ts
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.evaluate.test.ts
@@ -396,6 +396,40 @@ describe('AgentEvalRunService', () => {
expect(metrics.perCaseToolCalls).toBe(2); // 6 / 3
});
+ it('estimates pass^j and pass@j for every j up to k from each case', async () => {
+ const service = new AgentEvalRunService(serverDB, userId);
+ const threads = (passed: number) =>
+ Array.from({ length: 5 }, (_, index) => ({
+ passed: index < passed,
+ score: index < passed ? 1 : 0,
+ status: index < passed ? ('passed' as const) : ('failed' as const),
+ threadId: `t${index}`,
+ }));
+ const topic = (passed: number, index: number) => ({
+ evalResult: { rubricScores: [], threads: threads(passed) },
+ passed: passed > 0,
+ runId: 'run-k5',
+ score: passed / 5,
+ status: passed > 0 ? 'passed' : 'failed',
+ topicId: `topic-${index}`,
+ });
+
+ const metrics = await service.evaluateAndFinalizeRun({
+ run: { config: { k: 5 }, id: 'run-k5' },
+ // 5 of 5, 3 of 5 and 0 of 5 attempts passed.
+ runTopics: [topic(5, 1), topic(3, 2), topic(0, 3)],
+ });
+
+ // All 3 of 3 attempts: C(5,3)/C(5,3) = 1, C(3,3)/C(5,3) = 0.1, 0.
+ expect(metrics.passAllAt?.['3']).toBeCloseTo(1.1 / 3);
+ // At least 1 of 3: 1, 1 βˆ’ C(2,3)/C(5,3) = 1, 1 βˆ’ C(5,3)/C(5,3) = 0.
+ expect(metrics.passAnyAt?.['3']).toBeCloseTo(2 / 3);
+ // One attempt: the share of attempts that passed.
+ expect(metrics.passAllAt?.['1']).toBeCloseTo((1 + 0.6) / 3);
+ // All 5 equals the run's own pass^k.
+ expect(metrics.passAllAt?.['5']).toBeCloseTo(metrics.passAllK!);
+ });
+
it('should not include passAtK/passAllK in metrics when k = 1', async () => {
const service = new AgentEvalRunService(serverDB, userId);
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.external.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.external.test.ts
index dc3c6cc8ce7..e9cf6e6d69c 100644
--- a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.external.test.ts
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.external.test.ts
@@ -472,14 +472,45 @@ describe('AgentEvalRunService external protocol', () => {
expectedTotalCases: 10,
run: { config: null, id: 'r1' },
runTopics: [
- { runId: 'r1', score: 1, status: 'passed', topicId: 't1' },
- { runId: 'r1', score: 0, status: 'failed', topicId: 't2' },
+ { passed: true, runId: 'r1', score: 1, status: 'passed', topicId: 't1' },
+ { passed: false, runId: 'r1', score: 0, status: 'failed', topicId: 't2' },
],
});
expect(metrics.totalCases).toBe(10);
expect(metrics.completedCases).toBe(2);
expect(metrics.passRate).toBeCloseTo(0.1);
+ expect(metrics.passedCases).toBe(1);
+ expect(metrics.failedCases).toBe(1);
+ expect(metrics.errorCases).toBe(0);
+ expect(metrics.passAllAt).toBeUndefined();
+ expect(metrics.passAnyAt).toBeUndefined();
+ });
+
+ it('does not turn legacy status-only results into verified verdicts', async () => {
+ const service = new AgentEvalRunService(serverDB, userId);
+ const runTopics = [
+ { runId: 'r1', score: 1, status: 'passed', topicId: 't1' },
+ { runId: 'r1', score: 0, status: 'failed', topicId: 't2' },
+ ];
+ const metrics = await service.evaluateAndFinalizeRun({
+ expectedTotalCases: 10,
+ run: { config: null, id: 'r1' },
+ runTopics,
+ });
+
+ expect(metrics).toMatchObject({
+ averageScore: 0,
+ completedCases: 2,
+ errorCases: 2,
+ failedCases: 0,
+ passedCases: 0,
+ passRate: 0,
+ totalCases: 10,
+ });
+ expect(metrics.passAllAt).toBeUndefined();
+ expect(metrics.passAnyAt).toBeUndefined();
+ expect(runTopics.map((topic) => topic.score)).toEqual([1, 0]);
});
});
});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.judgeError.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.judgeError.test.ts
new file mode 100644
index 00000000000..e074846a287
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.judgeError.test.ts
@@ -0,0 +1,555 @@
+import type * as EvalRubric from '@lobechat/eval-rubric';
+import type { EvaluateResult } from '@lobechat/eval-rubric';
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ AgentEvalBenchmarkModel,
+ AgentEvalRunModel,
+ AgentEvalRunTopicModel,
+} from '@/database/models/agentEval';
+import { ThreadModel } from '@/database/models/thread';
+import {
+ agentEvalDatasets,
+ agentEvalRunTopics,
+ agentEvalTestCases,
+ messages,
+ topics,
+} from '@/database/schemas';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+
+import { cleanupDB, serverDB, setupEvalChain, setupMultiCaseRun, userId } from './_setup';
+
+/**
+ * The judge is the only thing faked here: every test drives the real
+ * completion, aggregation, re-judge and retry paths against the test DB and
+ * asserts that a judge failure never becomes a verdict and never costs a
+ * candidate run.
+ */
+const evaluate = vi.fn<(...args: unknown[]) => Promise<EvaluateResult>>();
+vi.mock('@lobechat/eval-rubric', async (importOriginal) => ({
+ ...(await importOriginal<typeof EvalRubric>()),
+ evaluate: (...args: unknown[]) => evaluate(...args),
+}));
+
+const execAgent = vi.fn();
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(function () {
+ return { execAgent };
+ }),
+}));
+
+vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return { interruptOperation: vi.fn().mockResolvedValue(true) };
+ }),
+}));
+
+const RUBRIC_ID = 'eval-mode-contains';
+const verdict = (passed: boolean, score: number): EvaluateResult => ({
+ passed,
+ rubricResults: [
+ { passed, reason: passed ? 'matches' : 'does not match', rubricId: RUBRIC_ID, score },
+ ],
+ score,
+});
+const judgeFailure = (judgeError: string): EvaluateResult => ({
+ judgeError,
+ passed: false,
+ rubricResults: [{ judgeError, passed: false, rubricId: RUBRIC_ID, score: 0 }],
+ score: 0,
+});
+
+const runTopicModel = () => new AgentEvalRunTopicModel(serverDB, userId);
+const runModel = () => new AgentEvalRunModel(serverDB, userId);
+const service = () => new AgentEvalRunService(serverDB, userId);
+/** The model instances a service instance reads through; model methods are instance fields. */
+const depsOf = (svc: AgentEvalRunService) => svc['deps'];
+
+/** One k=1 case whose candidate answered and whose attempt cost 0.02. */
+const completeSingleCase = async (svc = service()) => {
+ const chain = await setupEvalChain({
+ assistantOutput: 'The answer is 42.',
+ datasetEvalMode: 'contains',
+ totalCases: 1,
+ });
+ const done = await svc.recordTrajectoryCompletion({
+ runId: chain.run.id,
+ status: 'completed',
+ telemetry: { completionReason: 'stop', cost: 0.02, duration: 1500, steps: 3, totalTokens: 120 },
+ testCaseId: chain.testCase.id,
+ });
+ const runTopic = await runTopicModel().findByRunAndTestCase(chain.run.id, chain.testCase.id);
+ return { ...chain, done, runTopic: runTopic! };
+};
+
+/** A k=2 case with two eval threads that both answered. */
+const setupTwoThreadCase = async (svc = service()) => {
+ const benchmark = await new AgentEvalBenchmarkModel(serverDB, userId).create({
+ identifier: 'k2-benchmark',
+ isSystem: false,
+ name: 'k2 Benchmark',
+ rubrics: [],
+ });
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({
+ benchmarkId: benchmark.id,
+ evalMode: 'contains',
+ identifier: 'k2-dataset',
+ name: 'k2 Dataset',
+ userId,
+ })
+ .returning();
+ const [testCase] = await serverDB
+ .insert(agentEvalTestCases)
+ .values({
+ content: { expected: '42', input: 'What is 6*7?' },
+ datasetId: dataset.id,
+ sortOrder: 1,
+ userId,
+ })
+ .returning();
+ const run = await runModel().create({ config: { k: 2 }, datasetId: dataset.id, name: 'k2 Run' });
+ await runModel().update(run.id, {
+ metrics: { averageScore: 0, failedCases: 0, passRate: 0, passedCases: 0, totalCases: 1 },
+ });
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({ mode: 'test', title: 'k2 Topic', trigger: 'eval', userId })
+ .returning();
+ await runTopicModel().batchCreate([
+ { runId: run.id, status: 'running', testCaseId: testCase.id, topicId: topic.id },
+ ]);
+ const threadModel = new ThreadModel(serverDB, userId);
+ const threadIds: string[] = [];
+ for (let i = 0; i < 2; i++) {
+ const thread = await threadModel.create({ topicId: topic.id, type: 'eval' });
+ threadIds.push(thread!.id);
+ await serverDB.insert(messages).values({
+ content: `attempt ${i}: 42`,
+ role: 'assistant',
+ threadId: thread!.id,
+ topicId: topic.id,
+ userId,
+ });
+ }
+ const completeThread = (index: number) =>
+ svc.recordThreadCompletion({
+ runId: run.id,
+ status: 'completed',
+ telemetry: {
+ completionReason: 'stop',
+ cost: 0.01 * (index + 1),
+ duration: 1000,
+ totalTokens: 50,
+ },
+ testCaseId: testCase.id,
+ threadId: threadIds[index],
+ topicId: topic.id,
+ });
+ return { completeThread, run, testCase, threadIds, topic };
+};
+
+beforeEach(async () => {
+ await cleanupDB();
+ vi.restoreAllMocks();
+ evaluate.mockReset();
+ execAgent.mockReset();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+});
+
+describe('judge failures on a single-attempt case', () => {
+ it('records a judge that reports judgeError as judge_error with no verdict, keeping the attempt', async () => {
+ evaluate.mockResolvedValueOnce(judgeFailure('Judge model returned no parseable verdict'));
+
+ const { done, run, runTopic, topic } = await completeSingleCase();
+
+ expect(done.allDone).toBe(true);
+ expect(runTopic.status).toBe('judge_error');
+ expect(runTopic.passed).toBeNull();
+ expect(runTopic.score).toBeNull();
+ expect(runTopic.topicId).toBe(topic.id);
+ expect(runTopic.evalResult).toMatchObject({
+ completionReason: 'stop',
+ cost: 0.02,
+ errorPhase: 'judge',
+ judgeError: 'Judge model returned no parseable verdict',
+ rubricScores: [],
+ steps: 3,
+ tokens: 120,
+ });
+
+ const metrics = (await runModel().findById(run.id))!.metrics!;
+ expect(metrics).toMatchObject({ failedCases: 0, judgeErrorCases: 1, passedCases: 0 });
+ });
+
+ it('records a judge that throws the same way', async () => {
+ evaluate.mockRejectedValueOnce(new Error('provider 502'));
+
+ const { runTopic } = await completeSingleCase();
+
+ expect(runTopic.status).toBe('judge_error');
+ expect(runTopic.passed).toBeNull();
+ expect(runTopic.score).toBeNull();
+ expect(runTopic.evalResult).toMatchObject({
+ cost: 0.02,
+ errorPhase: 'judge',
+ judgeError: 'Judge failed: provider 502',
+ });
+ });
+
+ it('keeps a real zero score as a failed verdict', async () => {
+ evaluate.mockResolvedValueOnce(verdict(false, 0));
+
+ const { run, runTopic } = await completeSingleCase();
+
+ expect(runTopic.status).toBe('failed');
+ expect(runTopic.passed).toBe(false);
+ expect(runTopic.score).toBe(0);
+ expect(runTopic.evalResult?.judgeError).toBeUndefined();
+ expect(runTopic.evalResult?.rubricScores).toEqual([
+ { reason: 'does not match', rubricId: RUBRIC_ID, score: 0 },
+ ]);
+ const metrics = (await runModel().findById(run.id))!.metrics!;
+ expect(metrics.failedCases).toBe(1);
+ expect(metrics.judgeErrorCases).toBeUndefined();
+ });
+
+ it('ignores a late completion webhook for a case already marked judge_error', async () => {
+ evaluate.mockResolvedValueOnce(judgeFailure('first'));
+ const { run, testCase } = await completeSingleCase();
+ evaluate.mockResolvedValueOnce(verdict(true, 1));
+
+ await service().recordTrajectoryCompletion({
+ runId: run.id,
+ status: 'completed',
+ telemetry: { completionReason: 'stop', cost: 0.5 },
+ testCaseId: testCase.id,
+ });
+
+ const runTopic = await runTopicModel().findByRunAndTestCase(run.id, testCase.id);
+ expect(runTopic?.status).toBe('judge_error');
+ expect(runTopic?.evalResult?.cost).toBe(0.02);
+ expect(evaluate).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('judge failures on a pass@k case', () => {
+ it('leaves the case unjudged when one of two attempts cannot be graded', async () => {
+ const { completeThread, run, testCase, threadIds } = await setupTwoThreadCase();
+ evaluate.mockResolvedValueOnce(verdict(true, 1));
+ await completeThread(0);
+ evaluate.mockResolvedValueOnce(judgeFailure('rate limited'));
+ const second = await completeThread(1);
+
+ expect(second.allThreadsDone).toBe(true);
+ const runTopic = (await runTopicModel().findByRunAndTestCase(run.id, testCase.id))!;
+ expect(runTopic.status).toBe('judge_error');
+ expect(runTopic.passed).toBeNull();
+ expect(runTopic.score).toBeNull();
+ expect(runTopic.evalResult?.passAtK).toBeUndefined();
+ expect(runTopic.evalResult?.passAllK).toBeUndefined();
+ expect(runTopic.evalResult?.judgeError).toBe(
+ '1 of 2 attempts could not be judged: rate limited',
+ );
+ expect(runTopic.evalResult?.totalCost).toBeCloseTo(0.03);
+ // Threads are listed in storage order, not completion order.
+ const byId = new Map(runTopic.evalResult!.threads!.map((t) => [t.threadId, t]));
+ expect(byId.get(threadIds[0])).toMatchObject({ passed: true, status: 'passed' });
+ const failed = byId.get(threadIds[1])!;
+ expect(failed).toMatchObject({ cost: 0.02, judgeError: 'rate limited', status: 'judge_error' });
+ expect(failed.passed).toBeUndefined();
+ expect(failed.score).toBeUndefined();
+
+ const metrics = (await runModel().findById(run.id))!.metrics!;
+ expect(metrics).toMatchObject({ failedCases: 0, judgeErrorCases: 1, passedCases: 0 });
+ });
+
+ it('re-judges only the recorded threads and restores pass@k once every attempt is graded', async () => {
+ const { completeThread, run, testCase, threadIds } = await setupTwoThreadCase();
+ evaluate.mockResolvedValueOnce(verdict(true, 1));
+ await completeThread(0);
+ evaluate.mockResolvedValueOnce(judgeFailure('rate limited'));
+ await completeThread(1);
+ await runModel().update(run.id, { status: 'completed' });
+
+ evaluate.mockResolvedValue(verdict(true, 1));
+ const result = await service().rejudgeRun(run.id);
+
+ expect(result).toEqual({ failedCases: 0, judgeErrorCases: 0, passedCases: 1, rejudged: 1 });
+ expect(evaluate).toHaveBeenCalledTimes(4);
+ expect(execAgent).not.toHaveBeenCalled();
+ const runTopic = (await runTopicModel().findByRunAndTestCase(run.id, testCase.id))!;
+ expect(runTopic.status).toBe('passed');
+ expect(runTopic.passed).toBe(true);
+ expect(runTopic.evalResult).toMatchObject({ passAllK: true, passAtK: true });
+ expect(runTopic.evalResult?.judgeError).toBeUndefined();
+ expect(runTopic.evalResult?.threads?.map((t) => t.threadId).sort()).toEqual(
+ [...threadIds].sort(),
+ );
+ const recovered = runTopic.evalResult?.threads?.find((t) => t.threadId === threadIds[1]);
+ expect(recovered).toMatchObject({ cost: 0.02, passed: true, status: 'passed' });
+ expect(recovered?.judgeError).toBeUndefined();
+ expect(runTopic.evalResult?.totalCost).toBeCloseTo(0.03);
+ const metrics = (await runModel().findById(run.id))!.metrics!;
+ expect(metrics).toMatchObject({ passAtK: 1, passRate: 1, passedCases: 1 });
+ expect(metrics.judgeErrorCases).toBeUndefined();
+ });
+});
+
+describe('recovering from judge failures', () => {
+ it('re-judges the same trajectory, surviving repeated judge failures, without running the candidate', async () => {
+ evaluate.mockResolvedValueOnce(judgeFailure('outage 1'));
+ const { run, testCase, topic } = await completeSingleCase();
+ await runModel().update(run.id, { status: 'completed' });
+
+ evaluate.mockRejectedValueOnce(new Error('outage 2'));
+ const stillBroken = await service().rejudgeRun(run.id);
+ expect(stillBroken).toEqual({
+ failedCases: 0,
+ judgeErrorCases: 1,
+ passedCases: 0,
+ rejudged: 1,
+ });
+ let runTopic = (await runTopicModel().findByRunAndTestCase(run.id, testCase.id))!;
+ expect(runTopic.status).toBe('judge_error');
+ expect(runTopic.evalResult?.judgeError).toBe('Judge failed: outage 2');
+ expect(runTopic.evalResult?.cost).toBe(0.02);
+
+ evaluate.mockResolvedValueOnce(verdict(true, 1));
+ const recovered = await service().rejudgeRun(run.id);
+ expect(recovered).toEqual({ failedCases: 0, judgeErrorCases: 0, passedCases: 1, rejudged: 1 });
+ runTopic = (await runTopicModel().findByRunAndTestCase(run.id, testCase.id))!;
+ expect(runTopic.status).toBe('passed');
+ expect(runTopic.passed).toBe(true);
+ expect(runTopic.score).toBe(1);
+ expect(runTopic.topicId).toBe(topic.id);
+ expect(runTopic.evalResult).toMatchObject({ cost: 0.02, steps: 3, tokens: 120 });
+ expect(runTopic.evalResult?.judgeError).toBeUndefined();
+ expect(runTopic.evalResult?.errorPhase).toBeUndefined();
+ expect(runTopic.evalResult?.rubricScores).toEqual([
+ { reason: 'matches', rubricId: RUBRIC_ID, score: 1 },
+ ]);
+
+ expect(execAgent).not.toHaveBeenCalled();
+ const updated = (await runModel().findById(run.id))!;
+ expect(updated.metrics).toMatchObject({ averageScore: 1, passRate: 1, passedCases: 1 });
+ expect(updated.metrics?.judgeErrorCases).toBeUndefined();
+ });
+
+ it('is never retried or resumed as if the candidate had failed', async () => {
+ evaluate.mockResolvedValueOnce(judgeFailure('outage'));
+ const { run, testCase, topic } = await completeSingleCase();
+ await runModel().update(run.id, { status: 'completed' });
+
+ await expect(service().retryErrorCases(run.id)).resolves.toEqual({ retryCount: 0 });
+ await expect(service().retrySingleCase(run.id, testCase.id)).rejects.toThrow(
+ 'Cannot retry: the attempt ran but was not judged; re-judge it instead',
+ );
+ await expect(
+ service().canResumeTrajectory({ runId: run.id, testCaseId: testCase.id }),
+ ).resolves.toMatchObject({ canResume: false });
+ await expect(service().getResumableCases(run.id)).resolves.toEqual([]);
+
+ const [row] = await serverDB
+ .select()
+ .from(agentEvalRunTopics)
+ .where(eq(agentEvalRunTopics.runId, run.id));
+ expect(row.status).toBe('judge_error');
+ expect(row.topicId).toBe(topic.id);
+ expect((await runModel().findById(run.id))?.status).toBe('completed');
+ expect(execAgent).not.toHaveBeenCalled();
+ });
+});
+
+describe('evaluateAndFinalizeRun with judge errors', () => {
+ it('counts them apart and keeps them out of failedCases and averageScore', async () => {
+ const metrics = await service().evaluateAndFinalizeRun({
+ run: { id: 'run-1' },
+ runTopics: [
+ {
+ evalResult: { cost: 0.01 },
+ passed: true,
+ runId: 'run-1',
+ score: 1,
+ status: 'passed',
+ topicId: 't1',
+ },
+ {
+ evalResult: { cost: 0.01 },
+ passed: false,
+ runId: 'run-1',
+ score: 0.2,
+ status: 'failed',
+ topicId: 't2',
+ },
+ {
+ evalResult: { cost: 0.01, errorPhase: 'judge', judgeError: 'outage', rubricScores: [] },
+ passed: null,
+ runId: 'run-1',
+ score: null,
+ status: 'judge_error',
+ topicId: 't3',
+ },
+ ],
+ });
+
+ expect(metrics).toMatchObject({
+ averageScore: 0.6,
+ errorCases: 0,
+ failedCases: 1,
+ judgeErrorCases: 1,
+ passedCases: 1,
+ totalCases: 3,
+ });
+ expect(metrics.passRate).toBeCloseTo(1 / 3);
+ expect(metrics.totalCost).toBeCloseTo(0.03);
+ });
+});
+
+describe('missing grading context', () => {
+ it('records a missing dataset as judge_error instead of leaving the case running', async () => {
+ const svc = service();
+ vi.spyOn(depsOf(svc).datasetModel, 'findById').mockResolvedValue(undefined);
+
+ const { done, runTopic } = await completeSingleCase(svc);
+
+ expect(done.allDone).toBe(true);
+ expect(runTopic.status).toBe('judge_error');
+ expect(runTopic.passed).toBeNull();
+ expect(runTopic.evalResult).toMatchObject({
+ cost: 0.02,
+ errorPhase: 'judge',
+ judgeError: 'Grading context missing: dataset',
+ });
+ expect(evaluate).not.toHaveBeenCalled();
+ });
+
+ it('records a missing test case as judge_error on the topic path', async () => {
+ const svc = service();
+ const original = depsOf(svc).runTopicModel.findByRunAndTestCase;
+ vi.spyOn(depsOf(svc).runTopicModel, 'findByRunAndTestCase').mockImplementationOnce(
+ async (runId, testCaseId) => {
+ const row = await original(runId, testCaseId);
+ return row && { ...row, testCase: null };
+ },
+ );
+
+ const { done, runTopic } = await completeSingleCase(svc);
+
+ expect(done.allDone).toBe(true);
+ expect(runTopic.status).toBe('judge_error');
+ expect(runTopic.evalResult?.judgeError).toBe('Grading context missing: test case');
+ expect(evaluate).not.toHaveBeenCalled();
+ });
+
+ it('records a missing test case as judge_error on the thread path, not as failed', async () => {
+ const svc = service();
+ const { completeThread, threadIds } = await setupTwoThreadCase(svc);
+ // Look the case up by an id that does not exist: the real query returns no
+ // row, which is the production shape of a deleted test case.
+ const originalFindById = depsOf(svc).testCaseModel.findById;
+ vi.spyOn(depsOf(svc).testCaseModel, 'findById').mockImplementation(() =>
+ originalFindById('tc_missing'),
+ );
+
+ await completeThread(0);
+
+ const thread = await new ThreadModel(serverDB, userId).findById(threadIds[0]);
+ expect(thread?.metadata).toMatchObject({
+ cost: 0.01,
+ judgeError: 'Grading context missing: test case',
+ status: 'judge_error',
+ });
+ expect(thread?.metadata).toHaveProperty('completedAt');
+ expect((thread?.metadata as Record<string, unknown>).passed).toBeUndefined();
+ expect(evaluate).not.toHaveBeenCalled();
+ });
+});
+
+describe('pass@k threads whose judge throws', () => {
+ it('still complete, so the case and the run finish instead of hanging', async () => {
+ const { completeThread, run, testCase, threadIds } = await setupTwoThreadCase();
+ evaluate.mockRejectedValue(new Error('judge down'));
+
+ const first = await completeThread(0);
+ expect(first.allThreadsDone).toBe(false);
+ const second = await completeThread(1);
+ expect(second).toEqual({ allRunDone: true, allThreadsDone: true });
+
+ const threadModel = new ThreadModel(serverDB, userId);
+ for (const threadId of threadIds) {
+ const thread = await threadModel.findById(threadId);
+ expect(thread?.metadata).toHaveProperty('completedAt');
+ expect(thread?.metadata).toMatchObject({
+ judgeError: 'Judge failed: judge down',
+ status: 'judge_error',
+ });
+ }
+ const runTopic = (await runTopicModel().findByRunAndTestCase(run.id, testCase.id))!;
+ expect(runTopic.status).toBe('judge_error');
+ expect(runTopic.evalResult?.completionReason).toBe('completed');
+ expect(runTopic.evalResult?.totalCost).toBeCloseTo(0.03);
+ });
+
+ it('cannot be resumed: a judge failure is not a failed attempt', async () => {
+ const { completeThread, run, testCase, threadIds } = await setupTwoThreadCase();
+ evaluate.mockResolvedValueOnce(verdict(true, 1));
+ await completeThread(0);
+ evaluate.mockResolvedValueOnce(judgeFailure('rate limited'));
+ await completeThread(1);
+ await runModel().update(run.id, { status: 'running' });
+
+ await expect(
+ service().canResumeTrajectory({
+ runId: run.id,
+ testCaseId: testCase.id,
+ threadId: threadIds[1],
+ }),
+ ).resolves.toEqual({ canResume: false, reason: 'Trajectory is not resumable' });
+ await expect(service().getResumableCases(run.id)).resolves.toEqual([]);
+ expect(execAgent).not.toHaveBeenCalled();
+ });
+});
+
+describe('re-judging a run with mixed outcomes', () => {
+ it('reports one verdict and one judge failure, matching the stored metrics', async () => {
+ const { cases, run } = await setupMultiCaseRun(
+ [{ assistantOutput: '42' }, { assistantOutput: '42' }],
+ { datasetEvalMode: 'contains' },
+ );
+ evaluate.mockResolvedValue(verdict(true, 1));
+ for (const { testCase } of cases) {
+ await service().recordTrajectoryCompletion({
+ runId: run.id,
+ status: 'completed',
+ telemetry: { completionReason: 'stop', cost: 0.01 },
+ testCaseId: testCase.id,
+ });
+ }
+ await runModel().update(run.id, { status: 'completed' });
+ const before = await runTopicModel().findByRunId(run.id);
+ expect(before.map((t) => t.status)).toEqual(['passed', 'passed']);
+
+ evaluate.mockReset();
+ evaluate.mockResolvedValueOnce(verdict(true, 1)).mockResolvedValueOnce(judgeFailure('outage'));
+ const result = await service().rejudgeRun(run.id);
+
+ expect(result).toEqual({ failedCases: 0, judgeErrorCases: 1, passedCases: 1, rejudged: 2 });
+ const metrics = (await runModel().findById(run.id))!.metrics!;
+ expect(metrics).toMatchObject({
+ averageScore: 1,
+ failedCases: 0,
+ judgeErrorCases: 1,
+ passRate: 0.5,
+ passedCases: 1,
+ totalCases: 2,
+ });
+ const after = await runTopicModel().findByRunId(run.id);
+ expect(after.map((t) => t.status).sort()).toEqual(['judge_error', 'passed']);
+ expect(after.map((t) => t.topicId).sort()).toEqual(before.map((t) => t.topicId).sort());
+ for (const t of after) expect(t.evalResult?.cost).toBe(0.01);
+ expect(execAgent).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.lifecycle.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.lifecycle.test.ts
index ce04f740d98..9a67c1e741b 100644
--- a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.lifecycle.test.ts
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.lifecycle.test.ts
@@ -2,7 +2,8 @@ import { eq } from 'drizzle-orm';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentEvalRunModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';
-import { topics } from '@/database/schemas';
+import { ThreadModel } from '@/database/models/thread';
+import { agentOperations, topics } from '@/database/schemas';
import { AgentEvalRunService } from '@/server/services/agentEvalRun';
import { AgentRuntimeService } from '@/server/services/agentRuntime/AgentRuntimeService';
@@ -274,6 +275,79 @@ describe('AgentEvalRunService', () => {
expect(mockInstance.interruptOperation).toHaveBeenCalledWith('op-222');
});
+ it('interrupts the sub-agent operations an attempt forked, not the finished ones', async () => {
+ const { run, cases } = await setupMultiCaseRun([{ assistantOutput: null }]);
+
+ const runModel = new AgentEvalRunModel(serverDB, userId);
+ await runModel.update(run.id, { status: 'running' });
+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);
+ const rt = await runTopicModel.findByRunAndTestCase(run.id, cases[0].testCase.id);
+ await runTopicModel.updateByRunAndTopic(rt!.runId, rt!.topicId, {
+ evalResult: { operationId: 'op-parent', rubricScores: [] },
+ status: 'running',
+ });
+ // The attempt parked on a `callSubAgent` child; one child still runs,
+ // one already finished, and a stranger's child must stay untouched.
+ await serverDB.insert(agentOperations).values([
+ { id: 'op-parent', status: 'waiting_for_async_tool', userId },
+ { id: 'op-child-live', parentOperationId: 'op-parent', status: 'running', userId },
+ { id: 'op-child-done', parentOperationId: 'op-parent', status: 'done', userId },
+ { id: 'op-other', parentOperationId: 'op-elsewhere', status: 'running', userId },
+ ]);
+
+ vi.mocked(AgentRuntimeService).mockClear();
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ await service.abortRun(run.id);
+
+ const mockInstance = vi.mocked(AgentRuntimeService).mock.results[0].value;
+ expect(mockInstance.interruptOperation).toHaveBeenCalledTimes(2);
+ expect(mockInstance.interruptOperation).toHaveBeenCalledWith('op-parent');
+ expect(mockInstance.interruptOperation).toHaveBeenCalledWith('op-child-live');
+ });
+
+ it('marks Stop before callbacks and interrupts every attempt root and open child', async () => {
+ const { run, cases } = await setupMultiCaseRun([{ assistantOutput: null }]);
+ const model = new AgentEvalRunTopicModel(serverDB, userId);
+ const topicId = cases[0].topic.id;
+ await model.updateByRunAndTopic(run.id, topicId, { status: 'running' });
+ const threadModel = new ThreadModel(serverDB, userId);
+ for (const id of ['one', 'two', 'three']) {
+ const thread = await threadModel.create({ topicId, type: 'eval' });
+ await threadModel.update(thread!.id, { metadata: { operationId: id } });
+ await serverDB.insert(agentOperations).values([
+ { id, status: 'running', userId },
+ { id: `${id}-child`, parentOperationId: id, status: 'waiting_for_async_tool', userId },
+ { id: `${id}-done`, parentOperationId: id, status: 'done', userId },
+ ]);
+ }
+ const observed: string[] = [];
+ vi.mocked(AgentRuntimeService).mockImplementationOnce(function () {
+ return {
+ interruptOperation: async (id: string) => {
+ const current = await model.findByRunAndTestCase(run.id, cases[0].testCase.id);
+ expect(current?.evalResult?.completionReason).toBe('aborted');
+ // A callback that races with interrupt is rejected by the DB predicate.
+ const late = await model.updateByRunAndTopic(run.id, topicId, {
+ status: 'passed',
+ passed: true,
+ });
+ expect(late).toBeUndefined();
+ observed.push(id);
+ },
+ } as any;
+ });
+ await new AgentEvalRunService(serverDB, userId).abortRun(run.id);
+ expect(observed.sort()).toEqual([
+ 'one',
+ 'one-child',
+ 'three',
+ 'three-child',
+ 'two',
+ 'two-child',
+ ]);
+ });
+
it('should skip interrupt for topics without operationId', async () => {
const { run, cases } = await setupMultiCaseRun([{ assistantOutput: null }]);
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.queue.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.queue.test.ts
new file mode 100644
index 00000000000..58f9d415e0d
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.queue.test.ts
@@ -0,0 +1,175 @@
+import { eq, sql } from 'drizzle-orm';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentEvalRunModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';
+import { AgentEvalExecutionRepo } from '@/database/repositories/agentEvalExecution';
+import { agentEvalRuns, agentEvalRunTopics } from '@/database/schemas';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';
+
+import { cleanupDB, serverDB, setupMultiCaseRun, userId } from './_setup';
+
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: vi.fn(),
+}));
+
+vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return { interruptOperation: vi.fn().mockResolvedValue(true) };
+ }),
+}));
+
+const triggerSpy = vi.spyOn(AgentEvalRunWorkflow, 'triggerExecuteTestCase');
+
+beforeEach(async () => {
+ await cleanupDB();
+ triggerSpy.mockReset();
+ triggerSpy.mockResolvedValue({ workflowRunId: 'wf' } as never);
+});
+
+const startedCases = () => triggerSpy.mock.calls.map(([payload]) => payload.testCaseId);
+
+/** A run of `count` cases, started (running) with the given config. */
+const setupQueuedRun = async (count: number, config: Record<string, unknown>) => {
+ const setup = await setupMultiCaseRun(Array.from({ length: count }, () => ({})));
+ await new AgentEvalRunModel(serverDB, userId).update(setup.run.id, {
+ config,
+ status: 'running',
+ });
+ // As createRun leaves them: every case waits as 'pending'.
+ await serverDB
+ .update(agentEvalRunTopics)
+ .set({ status: 'pending' })
+ .where(eq(agentEvalRunTopics.runId, setup.run.id));
+ return setup;
+};
+
+const topicOf = async (runId: string, testCaseId: string) =>
+ new AgentEvalRunTopicModel(serverDB, userId).findByRunAndTestCase(runId, testCaseId);
+
+describe('runs with a concurrency limit (maxConcurrency)', () => {
+ it('starts only as many cases as the limit allows', async () => {
+ const { run, cases } = await setupQueuedRun(5, { maxConcurrency: 2 });
+ const service = new AgentEvalRunService(serverDB, userId);
+
+ const started = await service.dispatchQueuedCases(run.id);
+
+ expect(started).toEqual([cases[0].testCase.id, cases[1].testCase.id]);
+ expect(startedCases()).toEqual(started);
+ // The two started cases hold their slots until they run: a second call starts none.
+ expect(await service.dispatchQueuedCases(run.id)).toEqual([]);
+ expect(triggerSpy).toHaveBeenCalledTimes(2);
+ });
+
+ it('leaves a run without a limit to the paginated fan-out', async () => {
+ const { run } = await setupQueuedRun(3, {});
+
+ expect(await new AgentEvalRunService(serverDB, userId).dispatchQueuedCases(run.id)).toBe(
+ undefined,
+ );
+ expect(triggerSpy).not.toHaveBeenCalled();
+ });
+
+ it('starts the next waiting case when a case finishes', async () => {
+ const { run, cases } = await setupQueuedRun(3, { maxConcurrency: 1 });
+ const service = new AgentEvalRunService(serverDB, userId);
+ await serverDB
+ .update(agentEvalRunTopics)
+ .set({ status: 'running' })
+ .where(eq(agentEvalRunTopics.testCaseId, cases[0].testCase.id));
+
+ const { allDone } = await service.recordTrajectoryCompletion({
+ runId: run.id,
+ status: 'error',
+ telemetry: { completionReason: 'error', errorMessage: 'boom' },
+ testCaseId: cases[0].testCase.id,
+ });
+
+ expect(allDone).toBe(false);
+ expect(startedCases()).toEqual([cases[1].testCase.id]);
+ });
+
+ it('frees the slots of timed-out cases', async () => {
+ const { run, cases } = await setupQueuedRun(2, { maxConcurrency: 1, timeout: 1_200_000 });
+ await serverDB
+ .update(agentEvalRuns)
+ .set({ startedAt: sql`NOW() - interval '30 minutes'` })
+ .where(eq(agentEvalRuns.id, run.id));
+ await serverDB
+ .update(agentEvalRunTopics)
+ .set({ createdAt: sql`NOW() - interval '25 minutes'`, status: 'running' })
+ .where(eq(agentEvalRunTopics.testCaseId, cases[0].testCase.id));
+ const current = await new AgentEvalRunModel(serverDB, userId).findById(run.id);
+
+ const changed = await new AgentEvalRunService(serverDB, userId).checkAndHandleRunTimeout(
+ current!,
+ );
+
+ expect(changed).toBe(true);
+ expect((await topicOf(run.id, cases[0].testCase.id))?.status).toBe('timeout');
+ expect(startedCases()).toEqual([cases[1].testCase.id]);
+ });
+
+ it('hands out a slot again when its start never reached the case', async () => {
+ const { run, cases } = await setupQueuedRun(2, { maxConcurrency: 1 });
+ const stale = new Date(Date.now() - 10 * 60_000).toISOString();
+ await serverDB
+ .update(agentEvalRunTopics)
+ .set({ evalResult: { dispatchedAt: stale } })
+ .where(eq(agentEvalRunTopics.testCaseId, cases[0].testCase.id));
+
+ const started = await new AgentEvalRunService(serverDB, userId).dispatchQueuedCases(run.id);
+
+ expect(started).toEqual([cases[0].testCase.id]);
+ });
+
+ it('gives back the slot of a case whose start could not be triggered', async () => {
+ const { run, cases } = await setupQueuedRun(3, { maxConcurrency: 2 });
+ triggerSpy.mockRejectedValueOnce(new Error('qstash down'));
+ const service = new AgentEvalRunService(serverDB, userId);
+
+ expect(await service.dispatchQueuedCases(run.id)).toEqual([cases[1].testCase.id]);
+ expect((await topicOf(run.id, cases[0].testCase.id))?.evalResult?.dispatchedAt).toBe(undefined);
+ expect(await service.dispatchQueuedCases(run.id)).toEqual([cases[0].testCase.id]);
+ });
+
+ it('fails the dispatch when no queued case could be started, so the step is retried', async () => {
+ const { run, cases } = await setupQueuedRun(2, { maxConcurrency: 1 });
+ triggerSpy.mockRejectedValueOnce(new Error('qstash down'));
+ const service = new AgentEvalRunService(serverDB, userId);
+
+ await expect(service.dispatchQueuedCases(run.id)).rejects.toThrow(
+ /Could not start any queued case/,
+ );
+ // The released slot is handed out again on the retry.
+ expect(await service.dispatchQueuedCases(run.id)).toEqual([cases[0].testCase.id]);
+ });
+
+ it('times a pass@k case from when it starts, not from when the run was created', async () => {
+ const { run, cases } = await setupQueuedRun(1, { k: 2, timeout: 1_200_000 });
+ const [{ testCase, topic }] = cases;
+ await serverDB
+ .update(agentEvalRuns)
+ .set({ startedAt: sql`NOW() - interval '30 minutes'` })
+ .where(eq(agentEvalRuns.id, run.id));
+ // The case waited 25 minutes for a slot before it started.
+ await serverDB
+ .update(agentEvalRunTopics)
+ .set({ createdAt: sql`NOW() - interval '25 minutes'` })
+ .where(eq(agentEvalRunTopics.testCaseId, testCase.id));
+
+ await new AgentEvalExecutionRepo(serverDB, userId).prepareThreadExecutions({
+ k: 2,
+ runId: run.id,
+ testCaseId: testCase.id,
+ topicId: topic.id,
+ });
+ const current = await new AgentEvalRunModel(serverDB, userId).findById(run.id);
+ const changed = await new AgentEvalRunService(serverDB, userId).checkAndHandleRunTimeout(
+ current!,
+ );
+
+ expect(changed).toBe(false);
+ expect((await topicOf(run.id, testCase.id))?.status).toBe('running');
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.rejudge.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.rejudge.test.ts
new file mode 100644
index 00000000000..3e5edc8cafd
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.rejudge.test.ts
@@ -0,0 +1,177 @@
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentEvalRunModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';
+import { agentEvalRuns } from '@/database/schemas';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+
+import { cleanupDB, serverDB, setupEvalChain, userId } from './_setup';
+
+const generateObject = vi.fn();
+vi.mock('@/server/modules/AgentRuntime/llmRelay/oneShot', () => ({
+ initModelRuntimeForRequest: vi.fn(async () => ({ generateObject })),
+}));
+
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(function () {
+ return { execAgent: vi.fn() };
+ }),
+}));
+
+const RULES = [
+ 'Must: Report both order IDs (paper_order_001, paper_order_002).',
+ 'Must not: Say the stop order filled.',
+].join('\n');
+
+/** A completed run whose one case was graded "passed" at 0.9 by the old judge. */
+const setupJudgedRun = async (status: 'error' | 'passed' = 'passed') => {
+ const chain = await setupEvalChain({
+ assistantOutput: 'Placed paper_order_001 and paper_order_002; the stop filled right away.',
+ datasetEvalConfig: { judgePrompt: RULES, model: 'judge-model', provider: 'openai' },
+ datasetEvalMode: 'rule-checklist',
+ totalCases: 1,
+ });
+ const runModel = new AgentEvalRunModel(serverDB, userId);
+ await runModel.update(chain.run.id, {
+ metrics: {
+ averageScore: 0.9,
+ duration: 1234,
+ failedCases: 0,
+ passRate: 1,
+ passedCases: 1,
+ totalCases: 1,
+ },
+ status: 'completed',
+ });
+ await new AgentEvalRunTopicModel(serverDB, userId).updateByRunAndTopic(
+ chain.run.id,
+ chain.topic.id,
+ {
+ evalResult: {
+ completionReason: 'completed',
+ cost: 0.01,
+ rubricScores: [{ reason: 'old verdict', rubricId: 'eval-mode-llm-rubric', score: 0.9 }],
+ tokens: 100,
+ },
+ passed: status === 'passed',
+ score: status === 'passed' ? 0.9 : 0,
+ status,
+ },
+ );
+ return chain;
+};
+
+beforeEach(async () => {
+ await cleanupDB();
+ generateObject.mockReset();
+ generateObject.mockResolvedValue({
+ rules: [
+ { index: 1, reason: 'Both ids are in the reply.', verdict: 'satisfied' },
+ { index: 2, reason: 'The reply says the stop filled.', verdict: 'violated' },
+ ],
+ summary: 'One rule broken.',
+ });
+});
+
+describe('AgentEvalRunService.rejudgeRun', () => {
+ it('grades the recorded attempt again with the current rules and rebuilds the metrics', async () => {
+ const { run, topic } = await setupJudgedRun();
+
+ const result = await new AgentEvalRunService(serverDB, userId).rejudgeRun(run.id);
+
+ expect(result).toEqual({ failedCases: 1, judgeErrorCases: 0, passedCases: 0, rejudged: 1 });
+ expect(generateObject).toHaveBeenCalledTimes(1);
+ const prompt = generateObject.mock.calls[0][0].messages[1].content as string;
+ expect(prompt).toContain('[Rules]\n1. Must: Report both order IDs');
+ expect(prompt).toContain('[Output]\nPlaced paper_order_001');
+
+ const runTopic = await new AgentEvalRunTopicModel(serverDB, userId).findByRunAndTestCase(
+ run.id,
+ (await serverDB.query.agentEvalRunTopics.findFirst())!.testCaseId,
+ );
+ expect(runTopic?.status).toBe('failed');
+ expect(runTopic?.score).toBe(0.5);
+ expect(runTopic?.evalResult?.rubricScores?.[0]).toMatchObject({
+ rubricId: 'eval-mode-rule-checklist',
+ score: 0.5,
+ verdicts: [
+ {
+ rule: 'Must: Report both order IDs (paper_order_001, paper_order_002).',
+ verdict: 'satisfied',
+ },
+ { rule: 'Must not: Say the stop order filled.', verdict: 'violated' },
+ ],
+ });
+ // Telemetry of the original execution is kept.
+ expect(runTopic?.evalResult?.cost).toBe(0.01);
+ expect(runTopic?.topicId).toBe(topic.id);
+
+ const [updated] = await serverDB
+ .select()
+ .from(agentEvalRuns)
+ .where(eq(agentEvalRuns.id, run.id));
+ expect(updated.metrics).toMatchObject({
+ duration: 1234,
+ failedCases: 1,
+ passRate: 0,
+ passedCases: 0,
+ totalCases: 1,
+ });
+ expect(updated.status).toBe('completed');
+ });
+
+ it('leaves cases without a verdict alone', async () => {
+ const { run } = await setupJudgedRun('error');
+
+ const result = await new AgentEvalRunService(serverDB, userId).rejudgeRun(run.id);
+
+ expect(result).toEqual({ failedCases: 0, judgeErrorCases: 0, passedCases: 0, rejudged: 0 });
+ expect(generateObject).not.toHaveBeenCalled();
+ });
+
+ it('regrades an attempt once held as an error for an empty answer as a failure', async () => {
+ // Graded before a normally finished turn with no text counted as the model's failure.
+ const chain = await setupEvalChain({
+ assistantOutput: '',
+ datasetEvalConfig: { judgePrompt: RULES, model: 'judge-model', provider: 'openai' },
+ datasetEvalMode: 'rule-checklist',
+ totalCases: 1,
+ });
+ await new AgentEvalRunModel(serverDB, userId).update(chain.run.id, {
+ metrics: { errorCases: 1, failedCases: 0, passedCases: 0, totalCases: 1 },
+ status: 'completed',
+ });
+ await new AgentEvalRunTopicModel(serverDB, userId).updateByRunAndTopic(
+ chain.run.id,
+ chain.topic.id,
+ {
+ evalResult: { completionReason: 'done', error: 'No assistant output', rubricScores: [] },
+ passed: false,
+ score: 0,
+ status: 'error',
+ },
+ );
+
+ const result = await new AgentEvalRunService(serverDB, userId).rejudgeRun(chain.run.id);
+
+ expect(result).toMatchObject({ failedCases: 1, passedCases: 0, rejudged: 1 });
+ expect(generateObject).not.toHaveBeenCalled();
+ const runTopic = await serverDB.query.agentEvalRunTopics.findFirst();
+ expect(runTopic?.status).toBe('failed');
+ expect(runTopic?.evalResult?.error).toBe('Ended without a final answer');
+ const [updated] = await serverDB
+ .select()
+ .from(agentEvalRuns)
+ .where(eq(agentEvalRuns.id, chain.run.id));
+ expect(updated.metrics).toMatchObject({ errorCases: 0, failedCases: 1 });
+ });
+
+ it('refuses a run that is still executing', async () => {
+ const { run } = await setupJudgedRun();
+ await new AgentEvalRunModel(serverDB, userId).update(run.id, { status: 'running' });
+
+ await expect(new AgentEvalRunService(serverDB, userId).rejudgeRun(run.id)).rejects.toThrow(
+ 'Cannot re-judge a running run',
+ );
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.rerun.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.rerun.test.ts
new file mode 100644
index 00000000000..9cef6f9bc93
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.rerun.test.ts
@@ -0,0 +1,142 @@
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { AgentEvalRunModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';
+import { topics } from '@/database/schemas';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+import { needsRerun } from '@/server/services/agentEvalRun/rerun';
+
+import { cleanupDB, serverDB, setupMultiCaseRun, userId } from './_setup';
+
+beforeEach(cleanupDB);
+
+describe('needsRerun', () => {
+ it('flags a case whose own status is not a verdict', () => {
+ for (const status of ['error', 'timeout', 'judge_error']) {
+ expect(needsRerun({ status })).toBe(true);
+ }
+ expect(needsRerun({ status: 'passed' })).toBe(false);
+ expect(needsRerun({ status: 'failed' })).toBe(false);
+ });
+
+ it('flags a passed case when one of its attempts has no verdict', () => {
+ expect(
+ needsRerun({
+ evalResult: { threads: [{ status: 'passed' }, { status: 'passed' }, { status: 'error' }] },
+ status: 'passed',
+ }),
+ ).toBe(true);
+ expect(
+ needsRerun({
+ evalResult: { threads: [{ status: 'passed' }, { status: 'failed' }] },
+ status: 'failed',
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('AgentEvalRunService.rerunUnverifiedCases', () => {
+ it('replaces the cases without a verdict, keeps the others and their history, and queues the run', async () => {
+ const { run, cases } = await setupMultiCaseRun(
+ [
+ { assistantOutput: '42', expected: '42' },
+ { assistantOutput: null },
+ { assistantOutput: null },
+ { assistantOutput: null },
+ ],
+ { datasetEvalMode: 'contains' },
+ );
+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);
+ const runModel = new AgentEvalRunModel(serverDB, userId);
+ const service = new AgentEvalRunService(serverDB, userId);
+
+ // Case 1: a clean pass.
+ await service.recordTrajectoryCompletion({
+ runId: run.id,
+ telemetry: { completionReason: 'stop', duration: 1000 },
+ testCaseId: cases[0].testCase.id,
+ });
+ // Case 2: the judge never graded it.
+ const rt2 = await runTopicModel.findByRunAndTestCase(run.id, cases[1].testCase.id);
+ await runTopicModel.updateByRunAndTopic(rt2!.runId, rt2!.topicId, {
+ evalResult: { error: 'Judge failed: upstream timeout', rubricScores: [] },
+ passed: undefined,
+ score: undefined,
+ status: 'judge_error',
+ });
+ // Case 3: passed on two attempts, but the third was blocked by the provider.
+ const rt3 = await runTopicModel.findByRunAndTestCase(run.id, cases[2].testCase.id);
+ await runTopicModel.updateByRunAndTopic(rt3!.runId, rt3!.topicId, {
+ evalResult: {
+ rubricScores: [],
+ threads: [
+ { passed: true, status: 'passed', threadId: 'a' },
+ { passed: true, status: 'passed', threadId: 'b' },
+ { error: 'Provider blocked the response', passed: false, status: 'error', threadId: 'c' },
+ ],
+ } as any,
+ passed: true,
+ score: 1,
+ status: 'passed',
+ });
+ // Case 4: a clean fail.
+ const rt4 = await runTopicModel.findByRunAndTestCase(run.id, cases[3].testCase.id);
+ await runTopicModel.updateByRunAndTopic(rt4!.runId, rt4!.topicId, {
+ evalResult: { rubricScores: [{ reason: 'missed', rubricId: 'judge', score: 0 }] },
+ passed: false,
+ score: 0,
+ status: 'failed',
+ });
+ await runModel.update(run.id, { status: 'completed' });
+
+ const result = await service.rerunUnverifiedCases(run.id);
+ expect(result.rerunCount).toBe(2);
+
+ const updatedRun = await runModel.findById(run.id);
+ expect(updatedRun?.status).toBe('pending');
+
+ const remaining = await runTopicModel.findByRunId(run.id);
+ expect(remaining).toHaveLength(4);
+ const byCase = new Map(remaining.map((topic) => [topic.testCaseId, topic]));
+ expect(byCase.get(cases[0].testCase.id)?.status).toBe('passed');
+ expect(byCase.get(cases[3].testCase.id)?.status).toBe('failed');
+ expect(byCase.get(cases[1].testCase.id)?.status).toBe('pending');
+ expect(byCase.get(cases[2].testCase.id)?.status).toBe('pending');
+ // Fresh Topics for the rerun cases; the old ones stay for audit.
+ expect(byCase.get(cases[1].testCase.id)?.topicId).not.toBe(cases[1].topic.id);
+ expect(byCase.get(cases[2].testCase.id)?.topicId).not.toBe(cases[2].topic.id);
+ const [oldTopic2] = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.id, cases[1].topic.id));
+ const [oldTopic3] = await serverDB
+ .select()
+ .from(topics)
+ .where(eq(topics.id, cases[2].topic.id));
+ expect(oldTopic2).toBeDefined();
+ expect(oldTopic3).toBeDefined();
+
+ // A queued run is not rerun again on top of itself.
+ await expect(service.rerunUnverifiedCases(run.id)).rejects.toThrow(
+ 'Cannot rerun a pending run',
+ );
+ });
+
+ it('leaves a run alone when every attempt has a verdict', async () => {
+ const { run, cases } = await setupMultiCaseRun([{ assistantOutput: '42', expected: '42' }], {
+ datasetEvalMode: 'contains',
+ });
+ const runModel = new AgentEvalRunModel(serverDB, userId);
+ const service = new AgentEvalRunService(serverDB, userId);
+ await service.recordTrajectoryCompletion({
+ runId: run.id,
+ telemetry: { completionReason: 'stop', duration: 1000 },
+ testCaseId: cases[0].testCase.id,
+ });
+ await runModel.update(run.id, { status: 'completed' });
+
+ const result = await service.rerunUnverifiedCases(run.id);
+ expect(result.rerunCount).toBe(0);
+ expect((await runModel.findById(run.id))?.status).toBe('completed');
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.resume.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.resume.test.ts
index 0b5bef621c5..e9bfae52782 100644
--- a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.resume.test.ts
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.resume.test.ts
@@ -3,7 +3,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentEvalRunModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';
import { ThreadModel } from '@/database/models/thread';
-import { agentEvalTestCases, messages, topics } from '@/database/schemas';
+import { agentEvalEnvironments, agentEvalTestCases, messages, topics } from '@/database/schemas';
+import { AgentEvalMemoryService } from '@/server/services/agentEvalMemory';
import { AgentEvalRunService } from '@/server/services/agentEvalRun';
import type * as AgentEvalRunWorkflowModule from '@/server/workflows/agentEvalRun';
import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';
@@ -27,6 +28,7 @@ vi.mock('@/server/workflows/agentEvalRun', async (importOriginal) => {
...actual,
AgentEvalRunWorkflow: {
...actual.AgentEvalRunWorkflow,
+ triggerFinalizeRun: vi.fn().mockResolvedValue({}),
triggerResumeAgentTrajectory: vi.fn().mockResolvedValue({}),
triggerResumeThreadTrajectory: vi.fn().mockResolvedValue({}),
},
@@ -71,6 +73,12 @@ describe('AgentEvalRunService', () => {
'should allow timeout trajectory resume when run status is %s',
async (status) => {
const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });
+ await new AgentEvalMemoryService(serverDB, userId).prepare({
+ fixture: {},
+ runId: run.id,
+ testCaseId: testCase.id,
+ topicId: topic.id,
+ });
await new AgentEvalRunModel(serverDB, userId).update(run.id, { status });
await markTopicTimeout({ runId: run.id, testCaseId: testCase.id, topicId: topic.id });
@@ -178,6 +186,13 @@ describe('AgentEvalRunService', () => {
const threadModel = new ThreadModel(serverDB, userId);
const errorThread = await threadModel.create({ topicId: topic.id, type: 'eval' });
const passedThread = await threadModel.create({ topicId: topic.id, type: 'eval' });
+ await new AgentEvalMemoryService(serverDB, userId).prepare({
+ fixture: {},
+ runId: run.id,
+ testCaseId: testCase.id,
+ topicId: topic.id,
+ threadId: errorThread!.id,
+ });
await new AgentEvalRunTopicModel(serverDB, userId).updateByRunAndTopic(run.id, topic.id, {
evalResult: {
@@ -213,6 +228,13 @@ describe('AgentEvalRunService', () => {
const threadModel = new ThreadModel(serverDB, userId);
const errorThread = await threadModel.create({ topicId: topic.id, type: 'eval' });
const passedThread = await threadModel.create({ topicId: topic.id, type: 'eval' });
+ await new AgentEvalMemoryService(serverDB, userId).prepare({
+ fixture: {},
+ runId: run.id,
+ testCaseId: testCase.id,
+ topicId: topic.id,
+ threadId: errorThread!.id,
+ });
await new AgentEvalRunTopicModel(serverDB, userId).updateByRunAndTopic(run.id, topic.id, {
evalResult: {
@@ -251,6 +273,88 @@ describe('AgentEvalRunService', () => {
});
});
+ describe.each([false, true])('Memory resume preflight (threaded=%s)', (threaded) => {
+ it.each(['unknown', 'changed'] as const)(
+ 'reports %s fixture before scheduling or changing history',
+ async (kind) => {
+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });
+ await new AgentEvalRunModel(serverDB, userId).update(run.id, {
+ config: { k: threaded ? 2 : 1 },
+ status: 'failed',
+ });
+ const thread = threaded
+ ? await new ThreadModel(serverDB, userId).create({ topicId: topic.id, type: 'eval' })
+ : undefined;
+ const target = { runId: run.id, testCaseId: testCase.id, threadId: thread?.id };
+ if (kind === 'changed') {
+ await new AgentEvalMemoryService(serverDB, userId).prepare({
+ ...target,
+ topicId: topic.id,
+ fixture: {},
+ });
+ const environment = { memory: { seededAt: '2024-05-01T12:00:00.000Z' } };
+ if (threaded) {
+ const [shared] = await serverDB
+ .insert(agentEvalEnvironments)
+ .values({
+ config: environment,
+ name: 'Changed shared fixture',
+ userId,
+ })
+ .returning();
+ await serverDB
+ .update(agentEvalTestCases)
+ .set({ environmentId: shared.id })
+ .where(eq(agentEvalTestCases.id, testCase.id));
+ } else {
+ await serverDB
+ .update(agentEvalTestCases)
+ .set({
+ content: { ...testCase.content, environment },
+ })
+ .where(eq(agentEvalTestCases.id, testCase.id));
+ }
+ }
+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);
+ await runTopicModel.updateByRunAndTopic(run.id, topic.id, {
+ status: 'timeout',
+ evalResult: {
+ error: 'original evidence',
+ ...(thread && { threads: [{ status: 'timeout', threadId: thread.id }] }),
+ },
+ });
+ const [message] = await serverDB
+ .insert(messages)
+ .values({
+ role: 'assistant',
+ content: 'partial history',
+ topicId: topic.id,
+ userId,
+ })
+ .returning();
+ const before = await runTopicModel.findByRunAndTestCase(run.id, testCase.id);
+ const beforeMetadata = (await serverDB.select().from(topics))[0].metadata;
+ const service = new AgentEvalRunService(serverDB, userId);
+ const check = await service.canResumeTrajectory(target);
+ expect(check).toMatchObject({
+ canResume: false,
+ reason: expect.stringContaining(
+ kind === 'unknown' ? 'rerun this case' : 'Cannot change Memory fixture',
+ ),
+ });
+ expect(await service.getResumableCases(run.id)).toMatchObject([
+ { testCaseId: testCase.id, threadId: thread?.id, canResume: false, reason: check.reason },
+ ]);
+ await expect(service.resumeTrajectory(target)).rejects.toThrow(check.reason);
+ expect(AgentEvalRunWorkflow.triggerResumeAgentTrajectory).not.toHaveBeenCalled();
+ expect(AgentEvalRunWorkflow.triggerResumeThreadTrajectory).not.toHaveBeenCalled();
+ expect(await runTopicModel.findByRunAndTestCase(run.id, testCase.id)).toEqual(before);
+ expect((await serverDB.select().from(topics))[0].metadata).toEqual(beforeMetadata);
+ expect(await serverDB.select().from(messages)).toContainEqual(message);
+ },
+ );
+ });
+
describe('getResumableCases', () => {
it('should include pass@k cases that have resumable threads', async () => {
const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });
@@ -263,6 +367,13 @@ describe('AgentEvalRunService', () => {
const threadModel = new ThreadModel(serverDB, userId);
const errorThread = await threadModel.create({ topicId: topic.id, type: 'eval' });
const passedThread = await threadModel.create({ topicId: topic.id, type: 'eval' });
+ await new AgentEvalMemoryService(serverDB, userId).prepare({
+ fixture: {},
+ runId: run.id,
+ testCaseId: testCase.id,
+ topicId: topic.id,
+ threadId: errorThread!.id,
+ });
await new AgentEvalRunTopicModel(serverDB, userId).updateByRunAndTopic(run.id, topic.id, {
evalResult: {
@@ -298,6 +409,12 @@ describe('AgentEvalRunService', () => {
describe('resumeTrajectory', () => {
it('should only trigger workflow for a timed-out pass@1 trajectory without mutating state', async () => {
const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });
+ await new AgentEvalMemoryService(serverDB, userId).prepare({
+ fixture: {},
+ runId: run.id,
+ testCaseId: testCase.id,
+ topicId: topic.id,
+ });
await serverDB
.update(agentEvalTestCases)
@@ -394,6 +511,13 @@ describe('AgentEvalRunService', () => {
const threadModel = new ThreadModel(serverDB, userId);
const thread = await threadModel.create({ topicId: topic.id, type: 'eval' });
const otherThread = await threadModel.create({ topicId: topic.id, type: 'eval' });
+ await new AgentEvalMemoryService(serverDB, userId).prepare({
+ fixture: {},
+ runId: run.id,
+ testCaseId: testCase.id,
+ topicId: topic.id,
+ threadId: thread!.id,
+ });
await new AgentEvalRunTopicModel(serverDB, userId).updateByRunAndTopic(run.id, topic.id, {
evalResult: {
@@ -495,6 +619,12 @@ describe('AgentEvalRunService', () => {
describe('executeResumedTrajectory', () => {
it('should claim a timeout trajectory, switch run back to running, and store operationId', async () => {
const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });
+ await new AgentEvalMemoryService(serverDB, userId).prepare({
+ fixture: {},
+ runId: run.id,
+ testCaseId: testCase.id,
+ topicId: topic.id,
+ });
await new AgentEvalRunModel(serverDB, userId).update(run.id, { status: 'failed' });
await markTopicTimeout({ runId: run.id, testCaseId: testCase.id, topicId: topic.id });
@@ -514,7 +644,7 @@ describe('AgentEvalRunService', () => {
expect(result).toEqual({ status: 'started', topicId: topic.id });
expect(mockExecAgent).toHaveBeenCalledWith(
expect.objectContaining({
- appContext: { topicId: topic.id },
+ appContext: { suppressSignal: true, topicId: topic.id },
parentMessageId: 'parent-message-id',
prompt: '',
resume: true,
@@ -531,13 +661,19 @@ describe('AgentEvalRunService', () => {
).findByRunAndTestCase(run.id, testCase.id);
expect(refreshedRunTopic?.status).toBe('running');
expect(refreshedRunTopic?.evalResult).toEqual({
+ executionId: expect.any(String),
operationId: 'op-resume-1',
- rubricScores: [],
});
});
it('does not double-count LLM calls when the completion hook runs locally', async () => {
const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });
+ await new AgentEvalMemoryService(serverDB, userId).prepare({
+ fixture: {},
+ runId: run.id,
+ testCaseId: testCase.id,
+ topicId: topic.id,
+ });
const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);
await new AgentEvalRunModel(serverDB, userId).update(run.id, { status: 'failed' });
@@ -583,6 +719,34 @@ describe('AgentEvalRunService', () => {
expect((refreshed?.evalResult as any)?.llmCalls).toBe(7);
});
+ it('keeps prior timeout evidence when the original Memory fixture was not recorded', async () => {
+ const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });
+ const runModel = new AgentEvalRunModel(serverDB, userId);
+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);
+ await runModel.update(run.id, { status: 'failed' });
+ const before = await markTopicTimeout({
+ runId: run.id,
+ testCaseId: testCase.id,
+ topicId: topic.id,
+ });
+ await expect(
+ new AgentEvalRunService(serverDB, userId).executeResumedTrajectory({
+ appContext: { topicId: topic.id },
+ parentMessageId: 'parent-message-id',
+ runId: run.id,
+ testCaseId: testCase.id,
+ topicId: topic.id,
+ userId,
+ }),
+ ).resolves.toMatchObject({
+ status: 'cancelled',
+ reason: expect.stringContaining('rerun this case instead of resuming'),
+ });
+ expect(await runTopicModel.findByRunAndTestCase(run.id, testCase.id)).toEqual(before);
+ expect((await runModel.findById(run.id))?.status).toBe('failed');
+ expect(mockExecAgent).not.toHaveBeenCalled();
+ });
+
it('should cancel when the trajectory is not resumable', async () => {
const { run, testCase, topic } = await setupEvalChain({ totalCases: 1 });
@@ -659,6 +823,14 @@ describe('AgentEvalRunService', () => {
},
} as any);
+ await new AgentEvalMemoryService(serverDB, userId).prepare({
+ fixture: {},
+ runId: run.id,
+ testCaseId: testCase.id,
+ threadId: thread!.id,
+ topicId: topic.id,
+ });
+
mockExecAgent.mockResolvedValue({ operationId: 'op-thread-resume-1' });
const result = await new AgentEvalRunService(serverDB, userId).executeResumedThreadTrajectory(
@@ -676,7 +848,7 @@ describe('AgentEvalRunService', () => {
expect(result).toEqual({ status: 'started', threadId: thread!.id, topicId: topic.id });
expect(mockExecAgent).toHaveBeenCalledWith(
expect.objectContaining({
- appContext: { threadId: thread!.id, topicId: topic.id },
+ appContext: { suppressSignal: true, threadId: thread!.id, topicId: topic.id },
initialLlmCalls: 3,
initialStepCount: 7,
parentMessageId: 'parent-message-id',
@@ -687,6 +859,9 @@ describe('AgentEvalRunService', () => {
const updatedThread = await threadModel.findById(thread!.id);
expect(updatedThread?.metadata).toEqual({
+ executionId: expect.any(String),
+ startedAt: expect.any(String),
+ status: 'running',
operationId: 'op-thread-resume-1',
testCaseId: testCase.id,
});
@@ -705,8 +880,13 @@ describe('AgentEvalRunService', () => {
).findByRunAndTestCase(run.id, testCase.id);
expect(refreshedRunTopic?.status).toBe('running');
expect(refreshedRunTopic?.evalResult).toEqual({
+ executionId: updatedThread?.metadata?.executionId,
threads: [
- { status: 'running', threadId: thread!.id },
+ {
+ executionId: updatedThread?.metadata?.executionId,
+ status: 'running',
+ threadId: thread!.id,
+ },
{ passed: true, status: 'passed', threadId: otherThread!.id },
],
});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.thread.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.thread.test.ts
index e159f0bd0a2..b901edb0648 100644
--- a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.thread.test.ts
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.thread.test.ts
@@ -340,10 +340,10 @@ describe('AgentEvalRunService', () => {
const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);
const rt = await runTopicModel.findByRunAndTestCase(run.id, testCase.id);
- // pass@k: thread 1 passed
- expect(rt?.evalResult?.passAtK).toBe(true);
- // pass^k: not all passed (thread 2 errored)
- expect(rt?.evalResult?.passAllK).toBe(false);
+ // An infrastructure failure leaves the complete attempt sample ungraded.
+ expect(rt?.status).toBe('error');
+ expect(rt?.evalResult?.passAtK).toBeUndefined();
+ expect(rt?.evalResult?.passAllK).toBeUndefined();
// Primary fields should be AVERAGES (total / k)
expect(rt?.evalResult?.cost).toBeCloseTo(0.0075); // 0.015 / 2
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.threadErrors.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.threadErrors.test.ts
new file mode 100644
index 00000000000..9e33f864aae
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.threadErrors.test.ts
@@ -0,0 +1,421 @@
+import type * as EvalRubric from '@lobechat/eval-rubric';
+import type { EvaluateResult } from '@lobechat/eval-rubric';
+import { and, eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ AgentEvalBenchmarkModel,
+ AgentEvalRunModel,
+ AgentEvalRunTopicModel,
+} from '@/database/models/agentEval';
+import { ThreadModel } from '@/database/models/thread';
+import { AgentEvalExecutionRepo } from '@/database/repositories/agentEvalExecution';
+import { agentEvalDatasets, agentEvalTestCases, messages, topics } from '@/database/schemas';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+import { AgentRuntimeService } from '@/server/services/agentRuntime/AgentRuntimeService';
+import { AiAgentService } from '@/server/services/aiAgent';
+
+import { cleanupDB, serverDB, setupEvalChain, userId } from './_setup';
+
+/**
+ * Execution errors on pass@k attempts (a provider without a key, a crash
+ * before the first model call) must stay errors: a case whose every attempt
+ * errored is an execution error of the run, not a model that failed the rules.
+ */
+const generateObject = vi.fn().mockResolvedValue({ score: 1 });
+vi.mock('@/server/modules/AgentRuntime/llmRelay/oneShot', () => ({
+ initModelRuntimeForRequest: vi.fn(async () => ({ generateObject })),
+}));
+
+const evaluate = vi.fn<(...args: unknown[]) => Promise<EvaluateResult>>();
+vi.mock('@lobechat/eval-rubric', async (importOriginal) => ({
+ ...(await importOriginal<typeof EvalRubric>()),
+ evaluate: (...args: unknown[]) => evaluate(...args),
+}));
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(function () {
+ return { execAgent: vi.fn() };
+ }),
+}));
+vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return { interruptOperation: vi.fn().mockResolvedValue(true) };
+ }),
+}));
+
+const RUBRIC_ID = 'eval-mode-contains';
+const passing: EvaluateResult = {
+ passed: true,
+ rubricResults: [{ passed: true, reason: 'matches', rubricId: RUBRIC_ID, score: 1 }],
+ score: 1,
+};
+
+const runTopicModel = () => new AgentEvalRunTopicModel(serverDB, userId);
+const runModel = () => new AgentEvalRunModel(serverDB, userId);
+
+/** A k=2 case with two eval threads; `finish` reports one of them as completed or errored. */
+const setupTwoThreadCase = async (svc: AgentEvalRunService) => {
+ const benchmark = await new AgentEvalBenchmarkModel(serverDB, userId).create({
+ identifier: 'k2-benchmark',
+ isSystem: false,
+ name: 'k2 Benchmark',
+ rubrics: [],
+ });
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({
+ benchmarkId: benchmark.id,
+ evalMode: 'contains',
+ identifier: 'k2-dataset',
+ name: 'k2 Dataset',
+ userId,
+ })
+ .returning();
+ const [testCase] = await serverDB
+ .insert(agentEvalTestCases)
+ .values({
+ content: { expected: '42', input: 'What is 6*7?' },
+ datasetId: dataset.id,
+ sortOrder: 1,
+ userId,
+ })
+ .returning();
+ const run = await runModel().create({ config: { k: 2 }, datasetId: dataset.id, name: 'k2 Run' });
+ await runModel().update(run.id, {
+ metrics: { averageScore: 0, failedCases: 0, passRate: 0, passedCases: 0, totalCases: 1 },
+ });
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({ mode: 'test', title: 'k2 Topic', trigger: 'eval', userId })
+ .returning();
+ await runTopicModel().batchCreate([
+ { runId: run.id, status: 'running', testCaseId: testCase.id, topicId: topic.id },
+ ]);
+ const threadModel = new ThreadModel(serverDB, userId);
+ const threadIds: string[] = [];
+ for (let i = 0; i < 2; i++) {
+ const thread = await threadModel.create({ topicId: topic.id, type: 'eval' });
+ threadIds.push(thread!.id);
+ await serverDB.insert(messages).values({
+ content: `attempt ${i}: 42`,
+ role: 'assistant',
+ threadId: thread!.id,
+ topicId: topic.id,
+ userId,
+ });
+ }
+ const finish = (index: number, outcome: 'completed' | 'error' | 'timeout') =>
+ svc.recordThreadCompletion({
+ runId: run.id,
+ status: outcome,
+ telemetry:
+ outcome === 'error'
+ ? { completionReason: 'error', duration: 200, errorMessage: 'InvalidProviderAPIKey' }
+ : { completionReason: 'stop', cost: 0.01, duration: 1000, totalTokens: 50 },
+ testCaseId: testCase.id,
+ threadId: threadIds[index],
+ topicId: topic.id,
+ });
+ return { finish, run, testCase, threadIds, topic };
+};
+
+beforeEach(async () => {
+ await cleanupDB();
+ vi.restoreAllMocks();
+ evaluate.mockReset();
+ generateObject.mockClear();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+});
+
+describe('pass@k attempts that fail to execute', () => {
+ it('records a case whose every attempt errored as an execution error, not a failed verdict', async () => {
+ const svc = new AgentEvalRunService(serverDB, userId);
+ const { finish, run, testCase, threadIds } = await setupTwoThreadCase(svc);
+
+ await finish(0, 'error');
+ const { allRunDone } = await finish(1, 'error');
+
+ expect(allRunDone).toBe(true);
+ expect(evaluate).not.toHaveBeenCalled();
+ const runTopic = (await runTopicModel().findByRunAndTestCase(run.id, testCase.id))!;
+ expect(runTopic.status).toBe('error');
+ expect(runTopic.passed).toBeNull();
+ const result = runTopic.evalResult as Record<string, any>;
+ expect(result.completionReason).toBe('error');
+ expect(result.error).toContain('InvalidProviderAPIKey');
+ expect(result.error).toContain('2 of 2 attempts');
+ expect(result.threads.map((t: any) => t.status)).toEqual(['error', 'error']);
+ expect(result.threads.map((t: any) => t.threadId).sort()).toEqual([...threadIds].sort());
+
+ const updated = (await runModel().findById(run.id))!;
+ expect(updated.metrics?.errorCases).toBe(1);
+ expect(updated.metrics?.failedCases).toBe(0);
+ expect(updated.metrics?.passedCases).toBe(0);
+ });
+
+ it('keeps a mixed error/pass sample unranked and preserves both attempts', async () => {
+ evaluate.mockResolvedValue(passing);
+ const svc = new AgentEvalRunService(serverDB, userId);
+ const { finish, run, testCase } = await setupTwoThreadCase(svc);
+
+ await finish(0, 'error');
+ await finish(1, 'completed');
+
+ const runTopic = (await runTopicModel().findByRunAndTestCase(run.id, testCase.id))!;
+ expect(runTopic.status).toBe('error');
+ const result = runTopic.evalResult as Record<string, any>;
+ expect(result.passAtK).toBeUndefined();
+ expect(result.passAllK).toBeUndefined();
+ expect(result.threads.map((t: any) => t.status).sort()).toEqual(['error', 'passed']);
+ const updated = (await runModel().findById(run.id))!;
+ expect(updated.metrics?.passedCases).toBe(0);
+ expect(updated.metrics?.errorCases).toBe(1);
+ });
+});
+
+describe('invalid output and Stop races', () => {
+ it.each([false, true])('classifies empty output with hitStepCap=%s', async (hitStepCap) => {
+ evaluate.mockResolvedValue(passing);
+ const svc = new AgentEvalRunService(serverDB, userId);
+ const { finish, run, testCase, threadIds, topic } = await setupTwoThreadCase(svc);
+ await runModel().update(run.id, { config: { k: 2, maxSteps: 20 } });
+ await serverDB.delete(messages).where(eq(messages.threadId, threadIds[0]));
+ await svc.recordThreadCompletion({
+ runId: run.id,
+ status: 'completed',
+ testCaseId: testCase.id,
+ threadId: threadIds[0],
+ topicId: topic.id,
+ telemetry: { completionReason: 'stop', steps: hitStepCap ? 20 : 1 },
+ });
+ await finish(1, 'completed');
+ const result = await runTopicModel().findByRunAndTestCase(run.id, testCase.id);
+ expect(result?.status).toBe(hitStepCap ? 'passed' : 'error');
+ const attempt = result?.evalResult?.threads?.find((item) => item.threadId === threadIds[0]);
+ expect(attempt?.status).toBe(hitStepCap ? 'failed' : 'error');
+ expect(attempt?.error).toContain(hitStepCap ? 'step limit' : 'No assistant output');
+ });
+
+ it('fails, not errors, an attempt the provider finished with no text', async () => {
+ // A turn that ended normally (no provider error) with an empty answer, e.g. a
+ // tool call announced and never sent: the model's outcome, which a rerun repeats.
+ evaluate.mockResolvedValue(passing);
+ const svc = new AgentEvalRunService(serverDB, userId);
+ const { finish, run, testCase, threadIds, topic } = await setupTwoThreadCase(svc);
+ await runModel().update(run.id, { config: { k: 2, maxSteps: 20 } });
+ await serverDB
+ .update(messages)
+ .set({ content: '' })
+ .where(and(eq(messages.threadId, threadIds[0]), eq(messages.role, 'assistant')));
+ await svc.recordThreadCompletion({
+ runId: run.id,
+ status: 'completed',
+ testCaseId: testCase.id,
+ threadId: threadIds[0],
+ topicId: topic.id,
+ telemetry: { completionReason: 'done', steps: 5 },
+ });
+ await finish(1, 'completed');
+ const result = await runTopicModel().findByRunAndTestCase(run.id, testCase.id);
+ const attempt = result?.evalResult?.threads?.find((item) => item.threadId === threadIds[0]);
+ expect(attempt).toMatchObject({
+ error: 'Ended without a final answer',
+ passed: false,
+ status: 'failed',
+ });
+ expect(result?.status).toBe('passed');
+ expect((await runModel().findById(run.id))?.metrics?.errorCases).toBe(0);
+ });
+
+ it('keeps a timeout mixed with a passed attempt out of model verdicts', async () => {
+ evaluate.mockResolvedValue(passing);
+ const svc = new AgentEvalRunService(serverDB, userId);
+ const { finish, run, testCase } = await setupTwoThreadCase(svc);
+ await finish(0, 'timeout');
+ await finish(1, 'completed');
+ const result = await runTopicModel().findByRunAndTestCase(run.id, testCase.id);
+ expect(result).toMatchObject({ passed: null, score: null, status: 'timeout' });
+ expect(result?.evalResult?.threads?.map((item) => item.status).sort()).toEqual([
+ 'passed',
+ 'timeout',
+ ]);
+ expect(result?.evalResult?.passAllK).toBeUndefined();
+ });
+
+ it('Stop wins when the Judge returns after the abort; stored evidence survives', async () => {
+ const svc = new AgentEvalRunService(serverDB, userId);
+ const { finish, run, testCase, threadIds, topic } = await setupTwoThreadCase(svc);
+ await runTopicModel().updateByRunAndTopic(run.id, topic.id, {
+ evalResult: {
+ operationId: 'root',
+ threads: [{ passed: true, status: 'passed', threadId: threadIds[0] }],
+ },
+ });
+ await new AgentEvalExecutionRepo(serverDB, userId).updateThreadMetadata(
+ run.id,
+ topic.id,
+ threadIds[1],
+ {
+ operationId: 'attempt',
+ retained: 'audit',
+ },
+ );
+ let resolveJudge!: (value: EvaluateResult) => void;
+ let reachedJudge!: () => void;
+ const entered = new Promise<void>((resolve) => {
+ reachedJudge = resolve;
+ });
+ evaluate.mockImplementation(() => {
+ reachedJudge();
+ return new Promise((resolve) => {
+ resolveJudge = resolve;
+ });
+ });
+ const finishing = finish(1, 'completed');
+ await entered;
+ await svc.abortRun(run.id);
+ const stoppedThread = await new ThreadModel(serverDB, userId).findById(threadIds[1]);
+ resolveJudge(passing);
+ expect(await finishing).toMatchObject({ allRunDone: false });
+ const result = await runTopicModel().findByRunAndTestCase(run.id, testCase.id);
+ expect(result).toMatchObject({ passed: null, score: null, status: 'error' });
+ expect(result?.evalResult).toMatchObject({
+ completionReason: 'aborted',
+ operationId: 'root',
+ threads: expect.arrayContaining([expect.objectContaining({ passed: true })]),
+ });
+ const thread = await new ThreadModel(serverDB, userId).findById(threadIds[1]);
+ expect(thread?.metadata).toMatchObject({ operationId: 'attempt', retained: 'audit' });
+ expect(thread?.metadata).toEqual(stoppedThread?.metadata);
+ expect(thread?.metadata).toMatchObject({
+ status: 'error',
+ error: 'Aborted',
+ executionId: expect.any(String),
+ });
+ expect(await finish(0, 'completed')).toMatchObject({ allRunDone: false });
+ expect(evaluate).toHaveBeenCalledTimes(1);
+ });
+
+ it('merges a late operation id without erasing a completed attempt', async () => {
+ evaluate.mockResolvedValue(passing);
+ const svc = new AgentEvalRunService(serverDB, userId);
+ const { finish, run, threadIds, topic } = await setupTwoThreadCase(svc);
+ await finish(0, 'completed');
+ await new AgentEvalExecutionRepo(serverDB, userId).updateThreadMetadata(
+ run.id,
+ topic.id,
+ threadIds[0],
+ {
+ operationId: 'late-id',
+ },
+ );
+ const thread = await new ThreadModel(serverDB, userId).findById(threadIds[0]);
+ expect(thread?.metadata).toMatchObject({
+ operationId: 'late-id',
+ passed: true,
+ status: 'passed',
+ });
+ expect(thread?.metadata).toHaveProperty('completedAt');
+ });
+
+ it('interrupts an operation whose startup only returns after Stop', async () => {
+ const svc = new AgentEvalRunService(serverDB, userId);
+ const { run, testCase, threadIds, topic } = await setupTwoThreadCase(svc);
+ let resolveStart!: (value: { operationId: string }) => void;
+ let started!: () => void;
+ const entered = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ vi.mocked(AiAgentService).mockImplementationOnce(function () {
+ return {
+ execAgent: () => {
+ started();
+ return new Promise((resolve) => {
+ resolveStart = resolve;
+ });
+ },
+ } as any;
+ });
+ const executing = svc.executeThreadTrajectory({
+ run,
+ runId: run.id,
+ testCase,
+ testCaseId: testCase.id,
+ threadId: threadIds[0],
+ topicId: topic.id,
+ });
+ await entered;
+ await svc.abortRun(run.id);
+ resolveStart({ operationId: 'late-operation' });
+ await executing;
+ const interrupted = vi
+ .mocked(AgentRuntimeService)
+ .mock.results.flatMap((result) =>
+ result.value.interruptOperation.mock.calls.map(([id]: [string]) => id),
+ );
+ expect(interrupted).toContain('late-operation');
+ const result = await runTopicModel().findByRunAndTestCase(run.id, testCase.id);
+ expect(result?.evalResult?.completionReason).toBe('aborted');
+ });
+});
+
+describe('actual Judge request provenance', () => {
+ it.each([false, true])(
+ 'persists requested pairs for topic and thread grading with failure=%s',
+ async (failure) => {
+ const svc = new AgentEvalRunService(serverDB, userId);
+ const requested = [{ model: 'selected-judge', provider: 'selected-provider' }];
+ evaluate.mockImplementation(async (_input, options: any) => {
+ for (let i = 0; i < 2; i++) {
+ await options.matchContext.generateObject({
+ messages: [],
+ model: 'rubric-judge',
+ provider: 'rubric-provider',
+ schema: { type: 'object' },
+ });
+ }
+ if (failure) throw new Error('Judge response could not be parsed');
+ return passing;
+ });
+ const single = await setupEvalChain({
+ assistantOutput: '42',
+ datasetEvalMode: 'contains',
+ totalCases: 1,
+ });
+ await runModel().update(single.run.id, {
+ config: { judgeModel: 'selected-judge', judgeProvider: 'selected-provider' },
+ });
+ await svc.recordTrajectoryCompletion({
+ runId: single.run.id,
+ testCaseId: single.testCase.id,
+ telemetry: { completionReason: 'stop' },
+ });
+ const singleResult = await runTopicModel().findByRunAndTestCase(
+ single.run.id,
+ single.testCase.id,
+ );
+ expect(singleResult?.status).toBe(failure ? 'judge_error' : 'passed');
+ expect(singleResult?.evalResult?.judges).toEqual(requested);
+
+ const multi = await setupTwoThreadCase(svc);
+ await runModel().update(multi.run.id, {
+ config: { k: 2, judgeModel: 'selected-judge', judgeProvider: 'selected-provider' },
+ });
+ await multi.finish(0, 'completed');
+ await multi.finish(1, 'completed');
+ const multiResult = await runTopicModel().findByRunAndTestCase(
+ multi.run.id,
+ multi.testCase.id,
+ );
+ expect(multiResult?.status).toBe(failure ? 'judge_error' : 'passed');
+ expect(multiResult?.evalResult?.threads?.map((attempt) => attempt.judges)).toEqual([
+ requested,
+ requested,
+ ]);
+ expect(generateObject).toHaveBeenCalledTimes(6);
+ expect(
+ generateObject.mock.calls.every(([payload]) => payload.model === 'selected-judge'),
+ ).toBe(true);
+ },
+ );
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.timeout.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.timeout.test.ts
index 8dd24cb3ce7..5608c5ce4d1 100644
--- a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.timeout.test.ts
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.timeout.test.ts
@@ -2,6 +2,7 @@ import { eq, sql } from 'drizzle-orm';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentEvalRunModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';
+import { AgentEvalExecutionRepo } from '@/database/repositories/agentEvalExecution';
import { agentEvalRuns, agentEvalRunTopics } from '@/database/schemas';
import { AgentEvalRunService } from '@/server/services/agentEvalRun';
import { AgentRuntimeService } from '@/server/services/agentRuntime/AgentRuntimeService';
@@ -237,15 +238,45 @@ describe('AgentEvalRunService', () => {
});
});
- it('should return false and skip when run started less than timeout ago', async () => {
+ it('should return false when no running case is older than the timeout', async () => {
+ const { run } = await setupMultiCaseRun([{ assistantOutput: null }]);
+ const runModel = new AgentEvalRunModel(serverDB, userId);
+ await runModel.update(run.id, { status: 'running' });
+ await serverDB
+ .update(agentEvalRunTopics)
+ .set({ createdAt: sql`NOW() - interval '5 minutes'`, status: 'running' })
+ .where(eq(agentEvalRunTopics.runId, run.id));
+
const service = new AgentEvalRunService(serverDB, userId);
const changed = await service.checkAndHandleRunTimeout({
+ ...(await runModel.findById(run.id))!,
config: { timeout: 1_200_000 },
- id: 'any-run-id',
- startedAt: new Date(), // just now
});
expect(changed).toBe(false);
+ const [topic] = await new AgentEvalRunTopicModel(serverDB, userId).findByRunId(run.id);
+ expect(topic.status).toBe('running');
+ });
+
+ it('should still time out a stuck case after a retry moved the run start time', async () => {
+ const { run } = await setupMultiCaseRun([{ assistantOutput: null }]);
+ const runModel = new AgentEvalRunModel(serverDB, userId);
+ // A retry moves startedAt to now; the case that kept running began 25 min ago.
+ await runModel.update(run.id, { startedAt: new Date(), status: 'running' });
+ await serverDB
+ .update(agentEvalRunTopics)
+ .set({ createdAt: sql`NOW() - interval '25 minutes'`, status: 'running' })
+ .where(eq(agentEvalRunTopics.runId, run.id));
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ const changed = await service.checkAndHandleRunTimeout({
+ ...(await runModel.findById(run.id))!,
+ config: { timeout: 1_200_000 },
+ });
+
+ expect(changed).toBe(true);
+ const [topic] = await new AgentEvalRunTopicModel(serverDB, userId).findByRunId(run.id);
+ expect(topic.status).toBe('timeout');
});
});
@@ -400,7 +431,10 @@ describe('AgentEvalRunService', () => {
.where(eq(agentEvalRunTopics.runId, run.id));
// Execute batchMarkTimeout
- const timedOut = await runTopicModel.batchMarkTimeout(run.id, 1_200_000);
+ const timedOut = await new AgentEvalExecutionRepo(serverDB, userId).batchMarkTimeout(
+ run.id,
+ 1_200_000,
+ );
// Only case 3 (running) should be marked as timeout
expect(timedOut).toHaveLength(1);
diff --git a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.trajectory.test.ts b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.trajectory.test.ts
index 4c8ec3591d3..043eda8f235 100644
--- a/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.trajectory.test.ts
+++ b/apps/server/src/services/agentEvalRun/__tests__/agentEvalRunService.trajectory.test.ts
@@ -249,6 +249,32 @@ describe('AgentEvalRunService', () => {
expect(runTopic?.evalResult?.error).toBe('No assistant output');
});
+ it('grades an attempt that hit its step cap without answering as failed, not error', async () => {
+ const { run, testCase } = await setupEvalChain({
+ assistantOutput: null,
+ benchmarkRubrics: [{ config: {}, id: 'r1', name: 'contains', type: 'contains', weight: 1 }],
+ expected: '42',
+ totalCases: 1,
+ });
+ await new AgentEvalRunModel(serverDB, userId).update(run.id, { config: { maxSteps: 20 } });
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ await service.recordTrajectoryCompletion({
+ runId: run.id,
+ telemetry: { completionReason: 'done', duration: 100, steps: 21 },
+ testCaseId: testCase.id,
+ });
+
+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);
+ const runTopic = await runTopicModel.findByRunAndTestCase(run.id, testCase.id);
+
+ expect(runTopic?.status).toBe('failed');
+ expect(runTopic?.score).toBe(0);
+ expect(runTopic?.evalResult?.error).toBe(
+ 'Reached the step limit (20) without a final answer',
+ );
+ });
+
it('should write status=failed when evaluation does not pass', async () => {
const { run, testCase } = await setupEvalChain({
assistantOutput: 'completely wrong answer',
diff --git a/apps/server/src/services/agentEvalRun/__tests__/caseFromTopic.test.ts b/apps/server/src/services/agentEvalRun/__tests__/caseFromTopic.test.ts
new file mode 100644
index 00000000000..034b9eb1ac8
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/caseFromTopic.test.ts
@@ -0,0 +1,108 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { messages, topics } from '@/database/schemas';
+import { draftCaseFromTopic } from '@/server/services/agentEvalRun/caseFromTopic';
+import { createEvalRunDeps } from '@/server/services/agentEvalRun/deps';
+
+import { cleanupDB, serverDB, userId } from './_setup';
+
+const generateObject = vi.fn();
+vi.mock('@/server/modules/AgentRuntime/llmRelay/oneShot', () => ({
+ initModelRuntimeForRequest: vi.fn(async () => ({ generateObject })),
+}));
+
+const at = (minutes: number) => new Date(Date.UTC(2026, 6, 21, 10, minutes));
+
+beforeEach(async () => {
+ await cleanupDB();
+ generateObject.mockReset();
+ generateObject.mockResolvedValue({
+ rules: [
+ 'Must: Search mail for the June invoice.',
+ 'reply in English',
+ 'Must not: Send anything.',
+ ],
+ });
+});
+
+const createConversation = async () => {
+ const [topic] = await serverDB.insert(topics).values({ title: 'Invoices', userId }).returning();
+ await serverDB.insert(messages).values([
+ {
+ content: 'Hi, I need help with invoices.',
+ createdAt: at(0),
+ role: 'user',
+ topicId: topic.id,
+ userId,
+ },
+ { content: 'Sure, which one?', createdAt: at(1), role: 'assistant', topicId: topic.id, userId },
+ {
+ content: 'Find the June invoice from Acme and tell me the amount.',
+ createdAt: at(2),
+ role: 'user',
+ topicId: topic.id,
+ userId,
+ },
+ {
+ content: 'The June invoice from Acme is $1,200.',
+ createdAt: at(4),
+ role: 'assistant',
+ topicId: topic.id,
+ userId,
+ },
+ ]);
+ return topic;
+};
+
+describe('draftCaseFromTopic', () => {
+ it('turns the last request into the case and the earlier turns into context', async () => {
+ const topic = await createConversation();
+
+ const draft = await draftCaseFromTopic(createEvalRunDeps(serverDB, userId), topic.id);
+
+ expect(draft.input).toBe('Find the June invoice from Acme and tell me the amount.');
+ expect(draft.messages.map((m) => m.role)).toEqual(['user', 'assistant']);
+ expect(draft.answer).toBe('The June invoice from Acme is $1,200.');
+ expect(draft.sessionDate).toBe('2026-07-21');
+ expect(draft.title).toBe('Find the June invoice from Acme and tell me the amount.');
+ expect(draft.agent).toBeUndefined();
+ // Drafted rules are normalised to Must / Must not lines.
+ expect(draft.rules).toEqual([
+ 'Must: Search mail for the June invoice.',
+ 'Must: reply in English',
+ 'Must not: Send anything.',
+ ]);
+ const prompt = generateObject.mock.calls[0][0].messages[1].content as string;
+ expect(prompt).toContain('[Final request]\nFind the June invoice');
+ expect(prompt).toContain('[Recorded answer]');
+ });
+
+ it('skips the rule draft when asked and survives a failed one', async () => {
+ const topic = await createConversation();
+
+ const silent = await draftCaseFromTopic(createEvalRunDeps(serverDB, userId), topic.id, {
+ draftRules: false,
+ });
+ expect(silent.rules).toEqual([]);
+ expect(generateObject).not.toHaveBeenCalled();
+
+ generateObject.mockRejectedValue(new Error('provider down'));
+ const failed = await draftCaseFromTopic(createEvalRunDeps(serverDB, userId), topic.id);
+ expect(failed.rules).toEqual([]);
+ expect(failed.input).toContain('June invoice');
+ });
+
+ it('refuses a conversation without a user request and an unknown topic', async () => {
+ const [topic] = await serverDB.insert(topics).values({ title: 'Empty', userId }).returning();
+ await serverDB
+ .insert(messages)
+ .values([{ content: 'Hello!', role: 'assistant', topicId: topic.id, userId }]);
+
+ await expect(draftCaseFromTopic(createEvalRunDeps(serverDB, userId), topic.id)).rejects.toThrow(
+ 'The conversation has no user message to test',
+ );
+ await expect(
+ draftCaseFromTopic(createEvalRunDeps(serverDB, userId), 'tpc_missing'),
+ ).rejects.toThrow('Topic not found');
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/connectorBindings.test.ts b/apps/server/src/services/agentEvalRun/__tests__/connectorBindings.test.ts
new file mode 100644
index 00000000000..05be830e651
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/connectorBindings.test.ts
@@ -0,0 +1,246 @@
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentEvalEnvironmentModel } from '@/database/models/agentEval';
+import { ConnectorModel } from '@/database/models/connector';
+import { agentEvalDatasets, agentEvalRuns, agentEvalTestCases } from '@/database/schemas';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+
+import { getCaseConnectorBindings } from '../connectorBindings';
+import { cleanupDB, serverDB, userId } from './_setup';
+
+const { listRawTools, gateKeeper } = vi.hoisted(() => ({
+ listRawTools: vi.fn(),
+ gateKeeper: {
+ decrypt: async (ciphertext: string) => ({ plaintext: ciphertext.replace(/^sealed:/, '') }),
+ encrypt: async (plaintext: string) => `sealed:${plaintext}`,
+ },
+}));
+vi.mock('@/server/services/mcp', () => ({ mcpService: { listRawTools } }));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: async () => gateKeeper },
+}));
+vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({
+ AgentRuntimeService: class {
+ interruptOperation = vi.fn();
+ },
+}));
+vi.mock('@/server/workflows/agentEvalRun', () => ({ AgentEvalRunWorkflow: {} }));
+
+beforeEach(async () => {
+ await cleanupDB();
+ listRawTools.mockReset().mockResolvedValue([{ name: 'read', inputSchema: { type: 'object' } }]);
+});
+
+const fixture = async (bound = true) => {
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({ identifier: 'private-dataset', name: 'Private dataset', userId })
+ .returning();
+ const connectorModel = ConnectorModel.forEvaluation(
+ serverDB,
+ userId,
+ dataset.id,
+ undefined,
+ gateKeeper,
+ );
+ const connector = await connectorModel.create({
+ credentials: JSON.stringify({ type: 'bearer', token: 'private-token' }),
+ identifier: 'private-mock',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://private.test/mcp',
+ metadata: { agentEval: { datasetId: dataset.id } },
+ name: 'Private mock',
+ sourceType: 'custom',
+ status: 'disconnected',
+ });
+ const environment = await new AgentEvalEnvironmentModel(serverDB, userId).create({
+ identifier: 'fixture',
+ name: 'Fixture',
+ config: {
+ mock: { services: ['notion'] },
+ toolManifests: {
+ notion: {
+ identifier: 'notion',
+ type: 'mcp',
+ meta: { title: 'Notion' },
+ api: [{ name: 'read', description: '', parameters: { type: 'object' } }],
+ },
+ },
+ ...(bound && { connectorBindings: { notion: { connectorId: connector.id } } }),
+ },
+ });
+ const cases = await serverDB
+ .insert(agentEvalTestCases)
+ .values(
+ [0, 1].map((sortOrder) => ({
+ content: { input: 'Read the fixture' },
+ datasetId: dataset.id,
+ environmentId: environment.id,
+ sortOrder,
+ userId,
+ })),
+ )
+ .returning();
+ return { cases, connector, connectorModel, dataset };
+};
+
+describe('run-bound mock connections', () => {
+ it('uses only the case effective mock services when bindings are inherited from a broader environment', () => {
+ expect(
+ getCaseConnectorBindings({
+ mock: { services: ['notion'] },
+ connectorBindings: {
+ notion: { connectorId: 'notion-id' },
+ gmail: { connectorId: 'gmail-id' },
+ },
+ }),
+ ).toEqual({ notion: { connectorId: 'notion-id' } });
+ expect(
+ getCaseConnectorBindings({
+ mock: { services: [] },
+ connectorBindings: { notion: { connectorId: 'notion-id' } },
+ }),
+ ).toEqual({});
+ });
+ it('captures shared Environment UUIDs without credentials and remains idempotent', async () => {
+ const { cases, connector, dataset } = await fixture();
+ const service = new AgentEvalRunService(serverDB, userId);
+ const params = { datasetId: dataset.id, id: 'run_mock_binding', mode: 'external' as const };
+ const run = await service.createRun(params);
+ expect(Object.keys(run.config?.connectorSnapshots ?? {}).sort()).toEqual(
+ cases.map((testCase) => testCase.id).sort(),
+ );
+ expect(run.config?.connectorSnapshots?.[cases[0].id].notion.connectorId).toBe(connector.id);
+ expect(run.config?.connectorSnapshots?.[cases[0].id].notion.datasetId).toBe(dataset.id);
+ expect(JSON.stringify(run.config)).not.toMatch(/private-token|private.test|credentials/);
+ expect(listRawTools).toHaveBeenCalledOnce();
+ expect((await service.createRun(params)).id).toBe(run.id);
+ expect(listRawTools).toHaveBeenCalledOnce();
+ const fork = await service.createRun({
+ datasetId: dataset.id,
+ parentRunId: run.id,
+ mode: 'external',
+ });
+ expect(fork.config?.connectorSnapshots?.[cases[0].id]).toEqual(
+ run.config?.connectorSnapshots?.[cases[0].id],
+ );
+ });
+
+ it('blocks changed targets before start without altering the old run snapshots', async () => {
+ const { connector, connectorModel, dataset } = await fixture();
+ const service = new AgentEvalRunService(serverDB, userId);
+ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });
+ await service.assertConnectorBindings(run);
+ await connectorModel.update(connector.id, {
+ credentials: null,
+ mcpServerUrl: 'https://different.test/mcp',
+ });
+ await expect(service.assertConnectorBindings(run)).rejects.toThrow('changed');
+ const [saved] = await serverDB.select().from(agentEvalRuns).where(eq(agentEvalRuns.id, run.id));
+ expect(saved.config?.connectorSnapshots).toEqual(run.config?.connectorSnapshots);
+ expect(saved.status).toBe(run.status);
+ });
+
+ it('checks overlapping case connections once per create or start and preserves every alias', async () => {
+ const { cases, connector, connectorModel, dataset } = await fixture();
+ const second = await connectorModel.create({
+ credentials: JSON.stringify({ type: 'bearer', token: 'second-token' }),
+ identifier: 'second-mock',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://second.test/mcp',
+ metadata: { agentEval: { datasetId: dataset.id } },
+ name: 'Second mock',
+ sourceType: 'custom',
+ status: 'disconnected',
+ });
+ for (const [index, aliases] of [
+ ['notion', 'docs'],
+ ['linear', 'gmail'],
+ ].entries()) {
+ await serverDB
+ .update(agentEvalTestCases)
+ .set({
+ content: {
+ input: 'Read the fixture',
+ environment: {
+ mock: { services: aliases },
+ toolManifests: Object.fromEntries(
+ aliases.map((identifier) => [
+ identifier,
+ {
+ identifier,
+ type: 'mcp',
+ meta: { title: identifier },
+ api: [
+ {
+ name: 'read',
+ description: 'Original read',
+ parameters: { type: 'object' },
+ },
+ ],
+ },
+ ]),
+ ),
+ connectorBindings: {
+ [aliases[0]]: { connectorId: connector.id },
+ [aliases[1]]: { connectorId: second.id, transport: 'mcp' },
+ },
+ },
+ },
+ })
+ .where(eq(agentEvalTestCases.id, cases[index].id));
+ }
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ const run = await service.createRun({ datasetId: dataset.id, mode: 'external' });
+ expect(listRawTools).toHaveBeenCalledTimes(2);
+ const snapshots = run.config!.connectorSnapshots!;
+ expect(Object.keys(snapshots[cases[0].id]).sort()).toEqual(['docs', 'notion']);
+ expect(Object.keys(snapshots[cases[1].id]).sort()).toEqual(['gmail', 'linear']);
+ expect(snapshots[cases[0].id].notion.connectorId).toEqual(
+ snapshots[cases[1].id].linear.connectorId,
+ );
+ expect(snapshots[cases[1].id].linear.manifest?.identifier).toBe('linear');
+ expect(snapshots[cases[0].id].docs.connectorId).toEqual(
+ snapshots[cases[1].id].gmail.connectorId,
+ );
+
+ await service.assertConnectorBindings(run);
+ expect(listRawTools).toHaveBeenCalledTimes(4);
+ await connectorModel.update(connector.id, {
+ credentials: JSON.stringify({ type: 'bearer', token: 'rotated-token' }),
+ });
+ await service.assertConnectorBindings(run);
+ expect(listRawTools).toHaveBeenCalledTimes(6);
+ expect(
+ listRawTools.mock.calls
+ .slice(-2)
+ .map(([params]) => params.auth.token)
+ .sort(),
+ ).toEqual(['rotated-token', 'second-token']);
+
+ const secondCaseSnapshot = snapshots[cases[1].id].gmail;
+ snapshots[cases[1].id].gmail = { ...secondCaseSnapshot, fingerprint: 'stale' };
+ await expect(service.assertConnectorBindings(run)).rejects.toThrow('changed');
+ expect(listRawTools).toHaveBeenCalledTimes(6);
+ snapshots[cases[1].id].gmail = secondCaseSnapshot;
+
+ listRawTools.mockResolvedValue([{ name: 'changed_tool', inputSchema: { type: 'object' } }]);
+ await expect(service.assertConnectorBindings(run)).rejects.toThrow('changed');
+ const [saved] = await serverDB.select().from(agentEvalRuns).where(eq(agentEvalRuns.id, run.id));
+ expect(saved.config?.connectorSnapshots).toEqual(snapshots);
+ });
+
+ it('keeps an unbound imported dataset editable but creates no run until it is connected', async () => {
+ const { dataset } = await fixture(false);
+ const service = new AgentEvalRunService(serverDB, userId);
+ await expect(service.createRun({ datasetId: dataset.id, mode: 'external' })).rejects.toThrow(
+ 'Bind these mock services',
+ );
+ expect(await serverDB.select().from(agentEvalRuns)).toEqual([]);
+ expect(listRawTools).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/evaluateCase.integration.test.ts b/apps/server/src/services/agentEvalRun/__tests__/evaluateCase.integration.test.ts
index 84cbf6ec9a6..77917f7a340 100644
--- a/apps/server/src/services/agentEvalRun/__tests__/evaluateCase.integration.test.ts
+++ b/apps/server/src/services/agentEvalRun/__tests__/evaluateCase.integration.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { eq } from 'drizzle-orm';
import { beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '@/database/core/getTestDB';
@@ -182,7 +183,7 @@ describe('evaluateCase - evalMode resolution', () => {
expect(runTopic?.score).toBe(1);
});
- it('should skip evaluation when no evalMode and no benchmark rubrics', async () => {
+ it('grades against expected with the default rubric when no evalMode and no benchmark rubrics', async () => {
const { run, testCase } = await setupEvalChain({
benchmarkRubrics: [],
datasetEvalMode: null,
@@ -201,8 +202,69 @@ describe('evaluateCase - evalMode resolution', () => {
const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);
const runTopic = await runTopicModel.findByRunAndTestCase(run.id, testCase.id);
- // Should NOT have been evaluated β€” no status change beyond telemetry write
- expect(runTopic?.status).toBeNull();
+ // Nothing configured, but `expected` exists: the default contains rubric
+ // grades it, so the case reaches a verdict instead of staying running.
+ expect(runTopic?.status).toBe('passed');
+ expect(runTopic?.score).toBe(1);
+ expect(runTopic?.evalResult?.rubricScores?.[0]?.rubricId).toBe('default-contains');
+ });
+
+ it('records judge_error when there is nothing to grade against', async () => {
+ const { run, testCase } = await setupEvalChain({
+ benchmarkRubrics: [],
+ datasetEvalMode: null,
+ output: '42',
+ testCaseEvalMode: null,
+ });
+ await serverDB
+ .update(agentEvalTestCases)
+ .set({ content: { input: 'What is 6*7?' } })
+ .where(eq(agentEvalTestCases.id, testCase.id));
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ await service.recordTrajectoryCompletion({
+ runId: run.id,
+ testCaseId: testCase.id,
+ telemetry: { completionReason: 'stop', duration: 100 },
+ });
+
+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);
+ const runTopic = await runTopicModel.findByRunAndTestCase(run.id, testCase.id);
+ expect(runTopic?.status).toBe('judge_error');
+ expect(runTopic?.passed).toBeNull();
expect(runTopic?.score).toBeNull();
+ expect(runTopic?.evalResult).toMatchObject({
+ duration: 100,
+ errorPhase: 'judge',
+ judgeError: 'No rubrics configured',
+ });
+ });
+
+ it('should not crash when benchmark rubrics is empty and evalMode is null everywhere', async () => {
+ // rubrics column is NOT NULL in DB, so worst case is empty array []
+ // Combined with evalMode=null everywhere, this exercises the "no eval rules" path
+ const { run, testCase } = await setupEvalChain({
+ benchmarkRubrics: [],
+ datasetEvalMode: null,
+ expected: '42',
+ output: '42',
+ testCaseEvalMode: null,
+ });
+
+ const service = new AgentEvalRunService(serverDB, userId);
+
+ // This should NOT throw β€” the default rubric takes over
+ await expect(
+ service.recordTrajectoryCompletion({
+ runId: run.id,
+ testCaseId: testCase.id,
+ telemetry: { completionReason: 'stop', duration: 100 },
+ }),
+ ).resolves.not.toThrow();
+
+ const runTopicModel = new AgentEvalRunTopicModel(serverDB, userId);
+ const runTopic = await runTopicModel.findByRunAndTestCase(run.id, testCase.id);
+ expect(runTopic?.score).toBe(1);
+ expect(runTopic?.status).toBe('passed');
});
});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/executionGeneration.test.ts b/apps/server/src/services/agentEvalRun/__tests__/executionGeneration.test.ts
new file mode 100644
index 00000000000..095ef461cb4
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/executionGeneration.test.ts
@@ -0,0 +1,346 @@
+import type * as EvalRubric from '@lobechat/eval-rubric';
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentEvalRunModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';
+import { ThreadModel } from '@/database/models/thread';
+import { AgentEvalExecutionRepo } from '@/database/repositories/agentEvalExecution';
+import { agentEvalDatasets, agentEvalTestCases, messages } from '@/database/schemas';
+import { AgentEvalMemoryService } from '@/server/services/agentEvalMemory';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+import { EvalResumeConflictError } from '@/server/services/agentEvalRun/resumeTarget';
+import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';
+
+import { cleanupDB, serverDB, setupEvalChain, userId } from './_setup';
+
+const mocks = vi.hoisted(() => ({ evaluate: vi.fn(), exec: vi.fn(), interrupt: vi.fn() }));
+vi.mock('@lobechat/eval-rubric', async (original) => ({
+ ...(await original<typeof EvalRubric>()),
+ evaluate: mocks.evaluate,
+}));
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(function () {
+ return { execAgent: mocks.exec };
+ }),
+}));
+vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return { interruptOperation: mocks.interrupt };
+ }),
+}));
+vi.mock('@/server/workflows/agentEvalRun', () => ({
+ AgentEvalRunWorkflow: {
+ triggerFinalizeRun: vi.fn(),
+ triggerResumeAgentTrajectory: vi.fn(),
+ triggerResumeThreadTrajectory: vi.fn(),
+ },
+}));
+const passing = {
+ passed: true,
+ rubricResults: [{ passed: true, rubricId: 'eval-mode-contains', score: 1 }],
+ score: 1,
+};
+const service = () => new AgentEvalRunService(serverDB, userId);
+const rows = () => new AgentEvalRunTopicModel(serverDB, userId);
+const runs = () => new AgentEvalRunModel(serverDB, userId);
+const attempts = () => new ThreadModel(serverDB, userId);
+
+beforeEach(async () => {
+ await cleanupDB();
+ vi.clearAllMocks();
+ mocks.evaluate.mockReset().mockResolvedValue(passing);
+ mocks.interrupt.mockReset().mockResolvedValue(true);
+ mocks.exec.mockReset().mockImplementation(async (params) => {
+ await params.onOperationCreated?.('new-operation');
+ return { operationId: 'new-operation' };
+ });
+});
+
+async function activeCase(threaded: boolean) {
+ const chain = await setupEvalChain({
+ assistantOutput: '42',
+ datasetEvalMode: 'contains',
+ totalCases: 1,
+ });
+ await runs().update(chain.run.id, {
+ config: { k: threaded ? 2 : 1 },
+ startedAt: new Date(0),
+ status: 'running',
+ });
+ const thread = threaded
+ ? await attempts().create({
+ metadata: { executionId: 'old', operationId: 'old-operation', status: 'running' },
+ topicId: chain.topic.id,
+ type: 'eval',
+ })
+ : undefined;
+ if (thread)
+ await serverDB.insert(messages).values({
+ content: '42',
+ role: 'assistant',
+ threadId: thread.id,
+ topicId: chain.topic.id,
+ userId,
+ });
+ await rows().updateByRunAndTopic(chain.run.id, chain.topic.id, {
+ createdAt: new Date(0),
+ evalResult: {
+ executionId: 'old',
+ operationId: 'old-operation',
+ threads: thread
+ ? [{ executionId: 'old', status: 'running', threadId: thread.id }]
+ : undefined,
+ },
+ status: 'running',
+ });
+ await new AgentEvalMemoryService(serverDB, userId).prepare({
+ fixture: {},
+ runId: chain.run.id,
+ testCaseId: chain.testCase.id,
+ threadId: thread?.id,
+ topicId: chain.topic.id,
+ });
+ const callback = (executionId?: string) => ({
+ executionId,
+ runId: chain.run.id,
+ status: 'done',
+ telemetry: { completionReason: 'done' },
+ testCaseId: chain.testCase.id,
+ topicId: chain.topic.id,
+ ...(thread && { threadId: thread.id }),
+ });
+ const finish = (executionId?: string) =>
+ thread
+ ? service().recordThreadCompletion(callback(executionId) as any)
+ : service().recordTrajectoryCompletion(callback(executionId));
+ const resume = async (expectedExecutionId?: string) => {
+ const params = {
+ appContext: { topicId: chain.topic.id },
+ expectedExecutionId,
+ parentMessageId: 'resume-parent',
+ runId: chain.run.id,
+ testCaseId: chain.testCase.id,
+ topicId: chain.topic.id,
+ userId,
+ };
+ return thread
+ ? service().executeResumedThreadTrajectory({
+ ...params,
+ appContext: { topicId: chain.topic.id, threadId: thread.id },
+ threadId: thread.id,
+ })
+ : service().executeResumedTrajectory(params);
+ };
+ const current = () => rows().findByRunAndTestCase(chain.run.id, chain.testCase.id);
+ return { ...chain, callback, current, finish, resume, thread };
+}
+
+describe.each([false, true])('execution generation isolation (threaded=%s)', (threaded) => {
+ it.each(['Stop', 'timeout'] as const)(
+ '%s then Resume ignores old and legacy callbacks, accepts current callback',
+ async (stop) => {
+ const c = await activeCase(threaded);
+ if (stop === 'Stop') await service().abortRun(c.run.id);
+ else await new AgentEvalExecutionRepo(serverDB, userId).batchMarkTimeout(c.run.id, 1);
+ const stopped = await c.current();
+ expect(stopped?.evalResult?.executionId).not.toBe('old');
+ expect(await c.resume(stopped?.evalResult?.executionId)).toMatchObject({ status: 'started' });
+ const resumed = await c.current();
+ const resumedThread = c.thread ? await attempts().findById(c.thread.id) : undefined;
+ await c.finish('old');
+ await c.finish();
+ expect(await c.current()).toEqual(resumed);
+ if (c.thread) expect(await attempts().findById(c.thread.id)).toEqual(resumedThread);
+ expect(mocks.evaluate).not.toHaveBeenCalled();
+ const hook = mocks.exec.mock.calls[0][0].hooks[0];
+ expect(hook.webhook.body.executionId).toBe(
+ resumedThread?.metadata?.executionId ?? resumed?.evalResult?.executionId,
+ );
+ await hook.handler({ reason: 'done', status: 'done' });
+ expect(mocks.evaluate).toHaveBeenCalledTimes(1);
+ expect((await c.current())?.status).toBe('passed');
+ },
+ );
+
+ it('dispatches the stopped generation through the Resume API before claiming it', async () => {
+ const c = await activeCase(threaded);
+ await service().abortRun(c.run.id);
+ const stopped = await c.current();
+ await service().resumeTrajectory({
+ runId: c.run.id,
+ testCaseId: c.testCase.id,
+ threadId: c.thread?.id,
+ });
+ if (c.thread) {
+ const payload = vi.mocked(AgentEvalRunWorkflow.triggerResumeThreadTrajectory).mock
+ .calls[0][0];
+ expect(payload.expectedExecutionId).toBe(stopped?.evalResult?.executionId);
+ expect(await service().executeResumedThreadTrajectory(payload)).toMatchObject({
+ status: 'started',
+ });
+ } else {
+ const payload = vi.mocked(AgentEvalRunWorkflow.triggerResumeAgentTrajectory).mock.calls[0][0];
+ expect(payload.expectedExecutionId).toBe(stopped?.evalResult?.executionId);
+ expect(await service().executeResumedTrajectory(payload)).toMatchObject({
+ status: 'started',
+ });
+ }
+ const resumed = await c.current();
+ await c.finish('old');
+ expect(await c.current()).toEqual(resumed);
+ });
+
+ it('does not let a Judge already running before Stop overwrite the resumed generation', async () => {
+ const c = await activeCase(threaded);
+ let finishJudge!: (value: typeof passing) => void;
+ let entered!: () => void;
+ const judging = new Promise<void>((resolve) => {
+ entered = resolve;
+ });
+ mocks.evaluate.mockImplementationOnce(() => {
+ entered();
+ return new Promise((resolve) => {
+ finishJudge = resolve;
+ });
+ });
+ const oldCompletion = c.finish('old');
+ await judging;
+ await service().abortRun(c.run.id);
+ const stopped = await c.current();
+ await c.resume(stopped?.evalResult?.executionId);
+ const resumed = await c.current();
+ const resumedThread = c.thread ? await attempts().findById(c.thread.id) : undefined;
+ finishJudge(passing);
+ await oldCompletion;
+ expect(await c.current()).toEqual(resumed);
+ if (c.thread) expect(await attempts().findById(c.thread.id)).toEqual(resumedThread);
+ expect((await runs().findById(c.run.id))?.status).toBe('running');
+ });
+
+ it('claims only one operation for concurrent Resume requests with the same observed generation', async () => {
+ const c = await activeCase(threaded);
+ await new AgentEvalExecutionRepo(serverDB, userId).batchMarkTimeout(c.run.id, 1);
+ const stopped = await c.current();
+ const results = await Promise.all([
+ c.resume(stopped?.evalResult?.executionId),
+ c.resume(stopped?.evalResult?.executionId),
+ ]);
+ expect(results.map((r) => r.status).sort()).toEqual(['cancelled', 'started']);
+ expect(mocks.exec).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('case and run boundary guards', () => {
+ it('seeds Rerun topics so a legacy callback cannot target the new pending case', async () => {
+ const c = await activeCase(false);
+ await service().abortRun(c.run.id);
+ await service().retrySingleCase(c.run.id, c.testCase.id);
+ const fresh = await c.current();
+ expect(fresh?.topicId).not.toBe(c.topic.id);
+ expect(fresh?.evalResult?.executionId).toEqual(expect.any(String));
+ await c.finish('old');
+ await c.finish();
+ await service().recordTrajectoryCompletion({ ...c.callback(), topicId: undefined });
+ expect(await c.current()).toEqual(fresh);
+ expect(mocks.evaluate).not.toHaveBeenCalled();
+ });
+
+ it('rejects a stale finalizer both while resumed execution is active and after it finishes', async () => {
+ const c = await activeCase(false);
+ await new AgentEvalExecutionRepo(serverDB, userId).batchMarkTimeout(c.run.id, 1);
+ const oldRun = await runs().findById(c.run.id);
+ const stopped = await c.current();
+ await c.resume(stopped?.evalResult?.executionId);
+ const stale = () =>
+ runs().finalize(
+ c.run.id,
+ {
+ metrics: {
+ averageScore: 0,
+ failedCases: 0,
+ passRate: 0,
+ passedCases: 0,
+ timeoutCases: 1,
+ totalCases: 1,
+ },
+ status: 'failed',
+ },
+ { startedAt: oldRun?.startedAt },
+ );
+ expect(await stale()).toBeUndefined();
+ await mocks.exec.mock.calls[0][0].hooks[0].handler({ reason: 'done', status: 'done' });
+ expect(await stale()).toBeUndefined();
+ expect(
+ await runs().update(c.run.id, { metrics: oldRun?.metrics }, { startedAt: oldRun?.startedAt }),
+ ).toBeUndefined();
+ const currentRun = await runs().findById(c.run.id);
+ expect(
+ await runs().finalize(
+ c.run.id,
+ { status: 'completed' },
+ { startedAt: currentRun?.startedAt },
+ ),
+ ).toMatchObject({ status: 'completed' });
+ });
+
+ it('cannot overwrite Resume with timeout telemetry delayed during operation interruption', async () => {
+ const c = await activeCase(false);
+ mocks.interrupt.mockImplementationOnce(async () => {
+ const stopped = await c.current();
+ await c.resume(stopped?.evalResult?.executionId);
+ return true;
+ });
+ await service().checkAndHandleRunTimeout({
+ config: { timeout: 1 },
+ id: c.run.id,
+ startedAt: new Date(0),
+ });
+ expect(await c.current()).toMatchObject({
+ evalResult: { operationId: 'new-operation' },
+ status: 'running',
+ });
+ expect((await c.current())?.evalResult).not.toHaveProperty('completionReason');
+ expect((await runs().findById(c.run.id))?.status).toBe('running');
+ });
+
+ it('keeps a completion delivered before execAgent returns when binding the operation again', async () => {
+ const c = await activeCase(false);
+ await new AgentEvalExecutionRepo(serverDB, userId).batchMarkTimeout(c.run.id, 1);
+ mocks.exec.mockImplementationOnce(async (params) => {
+ await params.onOperationCreated('early-operation');
+ await params.hooks[0].handler({ reason: 'done', status: 'done' });
+ return { operationId: 'early-operation' };
+ });
+ await c.resume((await c.current())?.evalResult?.executionId);
+ expect(await c.current()).toMatchObject({
+ evalResult: { operationId: 'early-operation' },
+ passed: true,
+ status: 'passed',
+ });
+ });
+
+ it.each(['changed', 'retired'] as const)(
+ 'rejects %s cases on the Resume API before changing evidence or dispatching',
+ async (reason) => {
+ const c = await activeCase(false);
+ await service().abortRun(c.run.id);
+ if (reason === 'changed')
+ await serverDB
+ .update(agentEvalDatasets)
+ .set({ metadata: { release: 'new' } })
+ .where(eq(agentEvalDatasets.id, c.dataset.id));
+ else
+ await serverDB
+ .update(agentEvalTestCases)
+ .set({ metadata: { retired: true } })
+ .where(eq(agentEvalTestCases.id, c.testCase.id));
+ const before = await c.current();
+ await expect(
+ service().resumeTrajectory({ runId: c.run.id, testCaseId: c.testCase.id }),
+ ).rejects.toBeInstanceOf(EvalResumeConflictError);
+ expect(await c.current()).toEqual(before);
+ expect(AgentEvalRunWorkflow.triggerResumeAgentTrajectory).not.toHaveBeenCalled();
+ expect(mocks.exec).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/judge.test.ts b/apps/server/src/services/agentEvalRun/__tests__/judge.test.ts
new file mode 100644
index 00000000000..6eac117a0b3
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/judge.test.ts
@@ -0,0 +1,339 @@
+import { evaluate } from '@lobechat/eval-rubric';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createEvalRunDeps } from '../deps';
+import {
+ attemptReply,
+ buildEvalModeRubric,
+ buildJudgeEvidence,
+ createJudgeMatchContext,
+ resolveEvalJudge,
+} from '../judge';
+import { cleanupDB, serverDB, userId } from './_setup';
+
+const generateObject = vi.fn();
+const initModelRuntimeForRequest = vi.fn();
+vi.mock('@/server/modules/AgentRuntime/llmRelay/oneShot', () => ({
+ initModelRuntimeForRequest: (...args: unknown[]) => initModelRuntimeForRequest(...args),
+}));
+
+beforeEach(async () => {
+ await cleanupDB();
+ generateObject.mockReset();
+ initModelRuntimeForRequest.mockReset();
+ initModelRuntimeForRequest.mockResolvedValue({ generateObject });
+});
+
+describe('eval judge', () => {
+ it('uses the judge prompt the eval UI stores as the rubric criteria', () => {
+ const rubric = buildEvalModeRubric('llm-rubric', { judgePrompt: 'Must cite the post URLs.' });
+
+ expect(rubric.type).toBe('llm-rubric');
+ expect((rubric.config as any).criteria).toBe('Must cite the post URLs.');
+ });
+
+ it('keeps explicit criteria over the judge prompt', () => {
+ const rubric = buildEvalModeRubric('llm-rubric', {
+ criteria: 'Explicit criteria',
+ judgePrompt: 'Prompt',
+ });
+
+ expect((rubric.config as any).criteria).toBe('Explicit criteria');
+ });
+
+ it('uses the explicit run judge ahead of inherited case and dataset defaults', async () => {
+ const deps = createEvalRunDeps(serverDB, userId);
+
+ await expect(
+ resolveEvalJudge(deps, {
+ evalConfigs: [
+ { judgePrompt: 'Case rules' },
+ { model: 'deepseek-v4.1-flash', provider: 'openrouter' },
+ ],
+ runConfig: { judgeModel: 'gpt-4.1-mini', judgeProvider: 'openai' },
+ }),
+ ).resolves.toEqual({ model: 'gpt-4.1-mini', override: true, provider: 'openai' });
+
+ await expect(
+ resolveEvalJudge(deps, {
+ runConfig: { judgeModel: 'gpt-4.1-mini', judgeProvider: 'openai' },
+ }),
+ ).resolves.toEqual({ model: 'gpt-4.1-mini', override: true, provider: 'openai' });
+ });
+
+ it('uses benchmark defaults only when the run has no explicit judge', async () => {
+ const deps = createEvalRunDeps(serverDB, userId);
+ const benchmarkMetadata = { judge: { model: 'claude-haiku-5.5', provider: 'anthropic' } };
+
+ await expect(
+ resolveEvalJudge(deps, {
+ benchmarkMetadata,
+ evalConfigs: [{ judgePrompt: 'Case rules' }],
+ runConfig: { judgeModel: 'gpt-4.1-mini', judgeProvider: 'openai' },
+ }),
+ ).resolves.toEqual({ model: 'gpt-4.1-mini', override: true, provider: 'openai' });
+
+ await expect(
+ resolveEvalJudge(deps, {
+ benchmarkMetadata,
+ evalConfigs: [{ model: 'deepseek-v4.1-flash', provider: 'openrouter' }],
+ }),
+ ).resolves.toEqual({ model: 'deepseek-v4.1-flash', provider: 'openrouter' });
+
+ // A malformed `judge` is ignored rather than breaking grading.
+ await expect(
+ resolveEvalJudge(deps, {
+ benchmarkMetadata: { judge: 'claude' },
+ runConfig: { judgeModel: 'gpt-4.1-mini', judgeProvider: 'openai' },
+ }),
+ ).resolves.toEqual({ model: 'gpt-4.1-mini', override: true, provider: 'openai' });
+ });
+
+ it('falls back to a default judge when nothing is configured', async () => {
+ const judge = await resolveEvalJudge(createEvalRunDeps(serverDB, userId), {});
+
+ expect(judge.model).toBeTruthy();
+ expect(judge.provider).toBeTruthy();
+ });
+
+ it('starts the judge runtime on the first LLM rubric and passes the judge model', async () => {
+ const deps = createEvalRunDeps(serverDB, userId);
+ const context = createJudgeMatchContext(deps, { model: 'judge-model', provider: 'openrouter' });
+ generateObject.mockResolvedValue({ reason: 'ok', score: 1 });
+
+ expect(initModelRuntimeForRequest).not.toHaveBeenCalled();
+ await context.generateObject!({ messages: [], model: '', schema: {} });
+ await context.generateObject!({ messages: [], model: '', schema: {} });
+
+ expect(initModelRuntimeForRequest).toHaveBeenCalledTimes(1);
+ expect(initModelRuntimeForRequest).toHaveBeenCalledWith(
+ serverDB,
+ userId,
+ 'openrouter',
+ expect.anything(),
+ );
+ expect(generateObject).toHaveBeenCalledWith(
+ expect.objectContaining({ model: 'judge-model' }),
+ expect.anything(),
+ );
+ expect(context.judgeModel).toBe('judge-model');
+ });
+});
+
+describe('actual judge request', () => {
+ it('overrides an inherited matcher model/provider and records what was requested', async () => {
+ const deps = createEvalRunDeps(serverDB, userId);
+ const judge = await resolveEvalJudge(deps, {
+ evalConfigs: [{ model: 'inherited-model', provider: 'inherited-provider' }],
+ runConfig: { judgeModel: 'chosen-model', judgeProvider: 'chosen-provider' },
+ });
+ const context = createJudgeMatchContext(deps, judge);
+ generateObject.mockResolvedValue({ reason: 'Correct', score: 1 });
+ await evaluate(
+ {
+ actual: '42',
+ rubrics: [
+ buildEvalModeRubric('llm-rubric', {
+ criteria: 'Answer correctly',
+ model: 'inherited-model',
+ provider: 'inherited-provider',
+ }),
+ ],
+ testCase: { input: 'What is 6 times 7?' },
+ },
+ { matchContext: context },
+ );
+ expect(generateObject).toHaveBeenCalledWith(
+ expect.objectContaining({ model: 'chosen-model' }),
+ expect.anything(),
+ );
+ expect(initModelRuntimeForRequest).toHaveBeenCalledWith(
+ serverDB,
+ userId,
+ 'chosen-provider',
+ expect.anything(),
+ );
+ expect(context.judgeRequests).toEqual([{ model: 'chosen-model', provider: 'chosen-provider' }]);
+ });
+
+ it('preserves rubric-specific defaults when the run did not choose a judge', async () => {
+ const context = createJudgeMatchContext(createEvalRunDeps(serverDB, userId), {
+ model: 'default',
+ provider: 'default-provider',
+ });
+ generateObject.mockResolvedValue({ score: 1, reason: 'ok' });
+ await context.generateObject!({
+ model: 'rubric-model',
+ provider: 'rubric-provider',
+ messages: [],
+ schema: {},
+ });
+ expect(initModelRuntimeForRequest).toHaveBeenCalledWith(
+ serverDB,
+ userId,
+ 'rubric-provider',
+ expect.anything(),
+ );
+ expect(context.judgeRequests).toEqual([{ model: 'rubric-model', provider: 'rubric-provider' }]);
+ });
+});
+
+describe('attemptReply', () => {
+ it('grades the whole reply, not only the closing line after a last tool call', () => {
+ // #130: the email came first, then a preference save and a one-line "Done".
+ const reply = attemptReply({
+ messages: [
+ { content: 'Draft a reply to this customer', id: 'm1', role: 'user' },
+ { content: 'Subject: Your order #AM-2026-88431 ...', id: 'm2', role: 'assistant' },
+ { content: '', id: 'm3', role: 'assistant' },
+ { content: 'Preference saved', id: 'm4', role: 'tool' },
+ { content: 'Done β€” the preference is saved.', id: 'm5', role: 'assistant' },
+ ],
+ });
+
+ expect(reply).toBe('Subject: Your order #AM-2026-88431 ...\n\nDone β€” the preference is saved.');
+ });
+
+ it('leaves out the replies restored from the case history', () => {
+ const reply = attemptReply({
+ historyTailMessageId: 'h2',
+ messages: [
+ { content: 'Prepare the order', id: 'h1', role: 'user' },
+ { content: 'Prepared, not submitted.', id: 'h2', role: 'assistant' },
+ { content: 'Confirm and submit the order.', id: 'm1', role: 'user' },
+ { content: 'Submitted.', id: 'm2', role: 'assistant' },
+ ],
+ });
+
+ expect(reply).toBe('Submitted.');
+ });
+});
+
+describe('buildJudgeEvidence', () => {
+ const memoryCall = (id: string, apiName: string, content: string) => ({
+ content,
+ id,
+ plugin: { apiName, arguments: '{"title":"Workout habits"}', identifier: 'lobe-user-memory' },
+ role: 'tool',
+ });
+
+ it('lists the attempt tool calls and the Memory it left behind', () => {
+ const evidence = buildJudgeEvidence({
+ memorySnapshot: {
+ attemptId: 'run_1_tpc_1',
+ entries: [
+ {
+ capturedAt: '2026-10-21T10:00:00.000Z',
+ id: 'evm_1',
+ layer: 'preference',
+ payload: {},
+ source: 'agent',
+ summary: 'Trains in the morning, 15-20 reps, about 45 minutes',
+ title: 'Workout habits',
+ },
+ ],
+ fixtureHash: 'empty',
+ },
+ messages: [
+ { content: 'Remember my workout habits', id: 'm1', role: 'user' },
+ memoryCall('m2', 'addPreferenceMemory', 'Saved preference'),
+ { content: 'Saved.', id: 'm3', role: 'assistant' },
+ ],
+ });
+
+ expect(evidence).toContain('1. lobe-user-memory.addPreferenceMemory(');
+ expect(evidence).toContain('-> Saved preference');
+ expect(evidence).toContain('Memory at the end of the attempt (1 entries');
+ expect(evidence).toContain('[preference, agent, 2026-10-21] Workout habits');
+ });
+
+ it('shows long tool results up to the per-call cap and marks what it cut', () => {
+ const evidence = buildJudgeEvidence({
+ messages: [memoryCall('m1', 'searchUserMemory', 'x'.repeat(10_000))],
+ });
+
+ expect(evidence).toContain('Tool calls, in order (1):');
+ expect(evidence).toContain(`${'x'.repeat(6000)}… [4000 more characters not shown]`);
+ });
+
+ it('shares the evidence budget across many calls instead of dropping them', () => {
+ const calls = Array.from({ length: 120 }, (_, i) =>
+ memoryCall(`m${i}`, 'searchUserMemory', 'y'.repeat(5000)),
+ );
+
+ const evidence = buildJudgeEvidence({ messages: calls });
+
+ expect(evidence).toContain('120. lobe-user-memory.searchUserMemory(');
+ // 160k budget / 120 calls, minus the argument allowance, caps each result
+ // well under its 5000 characters, and the cut is marked on every call.
+ expect(evidence.length).toBeLessThan(200_000);
+ expect(evidence.match(/more characters not shown/g)).toHaveLength(120);
+ });
+
+ it('shows the whole document an agent wrote when the evidence budget has room', () => {
+ // A finished report artifact: the rule about its body (footnote markers,
+ // charts) can only be checked if the judge sees past the stylesheet.
+ const html = `<style>${'a{}'.repeat(1500)}</style><body>Report body [^1]</body>`;
+ const evidence = buildJudgeEvidence({
+ messages: [
+ {
+ content: 'artifact_001 created',
+ id: 'm1',
+ plugin: {
+ apiName: 'create_artifact',
+ arguments: JSON.stringify({ content: html }),
+ identifier: 'artifact-eval-mcp',
+ },
+ role: 'tool',
+ },
+ memoryCall('m2', 'searchUserMemory', 'ok'),
+ ],
+ });
+
+ expect(evidence).toContain('Report body [^1]');
+ expect(evidence).not.toContain('more characters not shown');
+ });
+
+ it('still caps long arguments when many calls share the budget', () => {
+ const calls = Array.from({ length: 40 }, (_, i) => ({
+ content: 'z'.repeat(6000),
+ id: `m${i}`,
+ plugin: {
+ apiName: 'replaceDocumentContent',
+ arguments: 'w'.repeat(20_000),
+ identifier: 'lobe-agent-documents',
+ },
+ role: 'tool',
+ }));
+
+ const evidence = buildJudgeEvidence({ messages: calls });
+
+ expect(evidence.length).toBeLessThan(200_000);
+ });
+
+ it('lists how many calls beyond the cap are not shown', () => {
+ const calls = Array.from({ length: 160 }, (_, i) =>
+ memoryCall(`m${i}`, 'searchUserMemory', 'ok'),
+ );
+
+ const evidence = buildJudgeEvidence({ messages: calls });
+
+ expect(evidence).toContain('150. lobe-user-memory.searchUserMemory(');
+ expect(evidence).not.toContain('151. lobe-user-memory');
+ expect(evidence).toContain('… 10 more tool calls not shown.');
+ });
+
+ it('leaves out tool calls restored from the case history', () => {
+ const evidence = buildJudgeEvidence({
+ historyTailMessageId: 'h2',
+ messages: [
+ memoryCall('h1', 'searchUserMemory', 'old result'),
+ { content: 'Earlier answer', id: 'h2', role: 'assistant' },
+ { content: 'New question', id: 'm1', role: 'user' },
+ { content: 'Answer', id: 'm2', role: 'assistant' },
+ ],
+ });
+
+ expect(evidence).toBe('Tool calls: none.');
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/localCompletion.test.ts b/apps/server/src/services/agentEvalRun/__tests__/localCompletion.test.ts
new file mode 100644
index 00000000000..d900018fc36
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/localCompletion.test.ts
@@ -0,0 +1,81 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentEvalBenchmarkModel, AgentEvalRunModel } from '@/database/models/agentEval';
+import { agentEvalDatasets, agentEvalTestCases } from '@/database/schemas';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+
+import { cleanupDB, serverDB, userId } from './_setup';
+
+const mockExecAgent = vi.fn();
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(function () {
+ return { execAgent: mockExecAgent };
+ }),
+}));
+
+const triggerFinalizeRun = vi.fn();
+vi.mock('@/server/workflows/agentEvalRun', () => ({
+ AgentEvalRunWorkflow: {
+ triggerFinalizeRun: (...args: unknown[]) => triggerFinalizeRun(...args),
+ triggerRunThreadTrajectory: vi.fn(),
+ },
+}));
+
+vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return { interruptOperation: vi.fn().mockResolvedValue(true) };
+ }),
+}));
+
+beforeEach(async () => {
+ await cleanupDB();
+ mockExecAgent.mockReset();
+ triggerFinalizeRun.mockReset();
+});
+
+const createSingleCaseRun = async () => {
+ const benchmark = await new AgentEvalBenchmarkModel(serverDB, userId).create({
+ identifier: 'bench',
+ isSystem: false,
+ name: 'Bench',
+ rubrics: [],
+ });
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({ benchmarkId: benchmark.id, identifier: 'ds', name: 'Dataset', userId })
+ .returning();
+ const [testCase] = await serverDB
+ .insert(agentEvalTestCases)
+ .values({ content: { input: 'Hello' }, datasetId: dataset.id, sortOrder: 0, userId })
+ .returning();
+
+ const service = new AgentEvalRunService(serverDB, userId);
+ const run = await service.createRun({ datasetId: dataset.id });
+ // startRun records the case total the completion check counts against.
+ await new AgentEvalRunModel(serverDB, userId).update(run.id, {
+ metrics: { averageScore: 0, failedCases: 0, passRate: 0, passedCases: 0, totalCases: 1 },
+ status: 'running',
+ });
+ return { dataset, run, service, testCase };
+};
+
+describe('in-process trajectory completion', () => {
+ it('finalizes the run once the last case completes', async () => {
+ const { dataset, run, service, testCase } = await createSingleCaseRun();
+ mockExecAgent.mockResolvedValue({ operationId: 'op-1' });
+
+ await service.executeTrajectory({
+ run: { datasetId: dataset.id, targetAgentId: null },
+ runId: run.id,
+ testCase: { content: { input: 'Hello' }, sortOrder: 0 },
+ testCaseId: testCase.id,
+ });
+
+ const hook = mockExecAgent.mock.calls[0][0].hooks.find(
+ (item: { id: string }) => item.id === 'eval-trajectory-complete',
+ );
+ await hook.handler({ reason: 'done', status: 'done' });
+
+ expect(triggerFinalizeRun).toHaveBeenCalledWith({ runId: run.id, userId });
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/multiThreadRetry.test.ts b/apps/server/src/services/agentEvalRun/__tests__/multiThreadRetry.test.ts
new file mode 100644
index 00000000000..0de64709895
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/multiThreadRetry.test.ts
@@ -0,0 +1,141 @@
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentEvalRunTopics, threads } from '@/database/schemas';
+import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';
+
+import { createEvalRunDeps } from '../deps';
+import { executeMultiThreadTrajectory } from '../thread';
+import { cleanupDB, serverDB, setupEvalChain, userId } from './_setup';
+
+vi.mock('@/server/workflows/agentEvalRun', () => ({
+ AgentEvalRunWorkflow: { triggerRunThreadTrajectory: vi.fn() },
+}));
+vi.mock('@/server/services/aiAgent', () => ({ AiAgentService: vi.fn() }));
+
+beforeEach(async () => {
+ vi.restoreAllMocks();
+ vi.mocked(AgentEvalRunWorkflow.triggerRunThreadTrajectory).mockReset();
+ await cleanupDB();
+});
+
+async function setup(k = 2) {
+ const chain = await setupEvalChain({ totalCases: 1 });
+ const deps = createEvalRunDeps(serverDB, userId);
+ await deps.runModel.update(chain.run.id, { status: 'running' });
+ await deps.runTopicModel.updateByRunAndTopic(chain.run.id, chain.topic.id, { status: 'pending' });
+ const params = {
+ k,
+ run: chain.run,
+ runId: chain.run.id,
+ testCaseId: chain.testCase.id,
+ };
+ const execute = () => executeMultiThreadTrajectory(deps, params);
+ const attempts = () => serverDB.select().from(threads).where(eq(threads.topicId, chain.topic.id));
+ return { ...chain, attempts, deps, execute };
+}
+
+describe('pass@k workflow dispatch recovery', () => {
+ it('retries the missing dispatch using its original attempt without repeating a claimed sibling', async () => {
+ const chain = await setup();
+ const trigger = vi.mocked(AgentEvalRunWorkflow.triggerRunThreadTrajectory);
+ const failure = new Error('dispatch unavailable');
+ let claimedThreadId: string | undefined;
+ let missingThreadId: string | undefined;
+ trigger.mockImplementation(async (payload) => {
+ if (!claimedThreadId) {
+ claimedThreadId = payload.threadId;
+ expect(
+ await chain.deps.executionRepo.claimExecution({
+ ...payload,
+ executionId: 'claimed-sibling',
+ expectedExecutionId: payload.executionId,
+ }),
+ ).toBeDefined();
+ } else {
+ missingThreadId = payload.threadId;
+ throw failure;
+ }
+ return undefined as any;
+ });
+ await expect(chain.execute()).rejects.toBe(failure);
+ const original = await chain.attempts();
+ expect(original).toHaveLength(2);
+ trigger.mockReset().mockResolvedValue(undefined as any);
+
+ const retried = await chain.execute();
+
+ expect(retried?.threadIds.toSorted()).toEqual(original.map((row) => row.id).toSorted());
+ expect(trigger).toHaveBeenCalledTimes(1);
+ expect(trigger).toHaveBeenCalledWith(expect.objectContaining({ threadId: missingThreadId }));
+ expect((await chain.attempts()).map((row) => row.id).toSorted()).toEqual(
+ original.map((row) => row.id).toSorted(),
+ );
+ });
+
+ it('rolls back allocated attempts if binding them to the parent fails, then retries cleanly', async () => {
+ const chain = await setup();
+ const originalTransaction = serverDB.transaction.bind(serverDB);
+ const failure = new Error('binding unavailable');
+ vi.spyOn(serverDB, 'transaction').mockImplementationOnce(((work: any) =>
+ originalTransaction((tx) =>
+ work(
+ new Proxy(tx, {
+ get(target, property) {
+ if (property === 'update')
+ return (table: unknown) => {
+ if (table === agentEvalRunTopics) throw failure;
+ return target.update(table as any);
+ };
+ const value = Reflect.get(target, property);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ }),
+ ),
+ )) as any);
+
+ await expect(chain.execute()).rejects.toBe(failure);
+ expect(await chain.attempts()).toEqual([]);
+ expect(
+ await chain.deps.runTopicModel.findByRunAndTestCase(chain.run.id, chain.testCase.id),
+ ).toMatchObject({ status: 'pending', evalResult: null });
+
+ await chain.execute();
+ expect(await chain.attempts()).toHaveLength(2);
+ expect(AgentEvalRunWorkflow.triggerRunThreadTrajectory).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not dispatch or recreate attempts when Stop wins before the retry', async () => {
+ const chain = await setup();
+ const trigger = vi.mocked(AgentEvalRunWorkflow.triggerRunThreadTrajectory);
+ trigger.mockRejectedValue(new Error('dispatch unavailable'));
+ await expect(chain.execute()).rejects.toThrow('dispatch unavailable');
+ const originalIds = (await chain.attempts()).map((row) => row.id).toSorted();
+ await chain.deps.executionRepo.batchMarkAborted(chain.run.id);
+ trigger.mockClear();
+
+ expect(await chain.execute()).toBeUndefined();
+ expect(trigger).not.toHaveBeenCalled();
+ expect((await chain.attempts()).map((row) => row.id).toSorted()).toEqual(originalIds);
+ });
+
+ it('shares one persisted set across concurrent retries and permits only one execution claim', async () => {
+ const chain = await setup();
+ const trigger = vi.mocked(AgentEvalRunWorkflow.triggerRunThreadTrajectory);
+ trigger.mockResolvedValue(undefined as any);
+ const results = await Promise.all([chain.execute(), chain.execute()]);
+ expect(results[0]?.threadIds.toSorted()).toEqual(results[1]?.threadIds.toSorted());
+ expect(await chain.attempts()).toHaveLength(2);
+ const payload = trigger.mock.calls[0][0];
+ const claims = await Promise.all(
+ ['first', 'duplicate'].map((executionId) =>
+ chain.deps.executionRepo.claimExecution({
+ ...payload,
+ executionId,
+ expectedExecutionId: payload.executionId,
+ }),
+ ),
+ );
+ expect(claims.filter(Boolean)).toHaveLength(1);
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/multiThreadTrigger.test.ts b/apps/server/src/services/agentEvalRun/__tests__/multiThreadTrigger.test.ts
index b750af772b4..3eadb95879f 100644
--- a/apps/server/src/services/agentEvalRun/__tests__/multiThreadTrigger.test.ts
+++ b/apps/server/src/services/agentEvalRun/__tests__/multiThreadTrigger.test.ts
@@ -12,13 +12,19 @@ vi.mock('@/server/workflows/agentEvalRun', () => ({
vi.mock('@/server/services/aiAgent', () => ({ AiAgentService: vi.fn() }));
const createDeps = () => {
- let next = 0;
return {
+ executionRepo: {
+ prepareThreadExecutions: vi.fn().mockImplementation(async ({ k }) => ({
+ pendingThreads: Array.from({ length: k }, (_, i) => ({
+ executionId: `queued-generation-${i}`,
+ threadId: `thread-${i}`,
+ })),
+ threadIds: Array.from({ length: k }, (_, i) => `thread-${i}`),
+ })),
+ },
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',
};
diff --git a/apps/server/src/services/agentEvalRun/__tests__/subAgentEvidence.test.ts b/apps/server/src/services/agentEvalRun/__tests__/subAgentEvidence.test.ts
new file mode 100644
index 00000000000..f35cd4ad459
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/subAgentEvidence.test.ts
@@ -0,0 +1,112 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { MessageModel } from '@/database/models/message';
+import { messagePlugins, messages, threads } from '@/database/schemas';
+
+import { buildJudgeEvidence } from '../judge';
+import { withSubAgentMessages } from '../subAgentEvidence';
+import { cleanupDB, serverDB, setupEvalChain, userId } from './_setup';
+
+const toolMessage = async (params: {
+ apiName: string;
+ content: string;
+ identifier: string;
+ threadId?: string;
+ topicId: string;
+}) => {
+ const [message] = await serverDB
+ .insert(messages)
+ .values({
+ content: params.content,
+ role: 'tool',
+ threadId: params.threadId,
+ topicId: params.topicId,
+ userId,
+ })
+ .returning();
+ await serverDB.insert(messagePlugins).values({
+ apiName: params.apiName,
+ arguments: '{}',
+ id: message.id,
+ identifier: params.identifier,
+ toolCallId: `call_${message.id}`,
+ userId,
+ });
+ return message;
+};
+
+const isolationThread = async (topicId: string, sourceMessageId: string, title: string) => {
+ const [thread] = await serverDB
+ .insert(threads)
+ .values({ sourceMessageId, title, topicId, type: 'isolation', userId })
+ .returning();
+ return thread;
+};
+
+describe('withSubAgentMessages', () => {
+ beforeEach(cleanupDB);
+ afterEach(cleanupDB);
+
+ it("lays a sub-agent's tool calls, nested ones too, after the call that started it", async () => {
+ const { topic } = await setupEvalChain({});
+ const deps = { db: serverDB, messageModel: new MessageModel(serverDB, userId), userId };
+ const spawn = await toolMessage({
+ apiName: 'callSubAgent',
+ content: 'Sub-agent summary: posted the release note.',
+ identifier: 'lobe-agent',
+ topicId: topic.id,
+ });
+ const subAgent = await isolationThread(topic.id, spawn.id, 'Release poster');
+ const nestedSpawn = await toolMessage({
+ apiName: 'callSubAgent',
+ content: 'Nested summary.',
+ identifier: 'lobe-agent',
+ threadId: subAgent.id,
+ topicId: topic.id,
+ });
+ await toolMessage({
+ apiName: 'postMessage',
+ content: '{"ok":true}',
+ identifier: 'slack-mcp',
+ threadId: subAgent.id,
+ topicId: topic.id,
+ });
+ const nested = await isolationThread(topic.id, nestedSpawn.id, 'Checker');
+ await toolMessage({
+ apiName: 'readChannel',
+ content: '{"messages":1}',
+ identifier: 'slack-mcp',
+ threadId: nested.id,
+ topicId: topic.id,
+ });
+
+ const attempt = await deps.messageModel.query({ topicId: topic.id });
+ // The attempt's own list never sees the sub-agent's work.
+ expect(attempt.map((message) => message.id)).toEqual([spawn.id]);
+
+ const evidence = buildJudgeEvidence({
+ messages: await withSubAgentMessages(deps, { messages: attempt, topicId: topic.id }),
+ });
+
+ expect(evidence).toContain('[sub-agent: …] was made by a sub-agent the agent started');
+ const lines = evidence.split('\n').filter((line) => /^\d+\. /.test(line));
+ expect(lines).toEqual([
+ expect.stringMatching(/^1\. lobe-agent\.callSubAgent\(/),
+ expect.stringMatching(/^2\. \[sub-agent: Release poster\] lobe-agent\.callSubAgent\(/),
+ expect.stringMatching(/^3\. \[sub-agent: Checker\] slack-mcp\.readChannel\(/),
+ expect.stringMatching(/^4\. \[sub-agent: Release poster\] slack-mcp\.postMessage\(/),
+ ]);
+ });
+
+ it('leaves an attempt without sub-agents as it was', async () => {
+ const { topic } = await setupEvalChain({});
+ const deps = { db: serverDB, messageModel: new MessageModel(serverDB, userId), userId };
+ await toolMessage({ apiName: 'search', content: '[]', identifier: 'web', topicId: topic.id });
+ const attempt = await deps.messageModel.query({ topicId: topic.id });
+
+ expect(await withSubAgentMessages(deps, { messages: attempt, topicId: topic.id })).toBe(
+ attempt,
+ );
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/trajectoryMethods.test.ts b/apps/server/src/services/agentEvalRun/__tests__/trajectoryMethods.test.ts
index 8fa605b6511..06fc41b9ce2 100644
--- a/apps/server/src/services/agentEvalRun/__tests__/trajectoryMethods.test.ts
+++ b/apps/server/src/services/agentEvalRun/__tests__/trajectoryMethods.test.ts
@@ -1,6 +1,6 @@
import type { EvalCaseEnvironment, ImportedMessage } from '@lobechat/types';
import { eq } from 'drizzle-orm';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '@/database/core/getTestDB';
import { AgentEvalBenchmarkModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';
@@ -58,6 +58,10 @@ beforeEach(async () => {
mockExecAgent.mockReset();
});
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
/**
* Helper: create benchmark β†’ dataset β†’ testCase β†’ run (minimal chain for loadTrajectoryData tests)
*/
@@ -168,19 +172,23 @@ describe('AgentEvalRunService', () => {
}
});
- it('should load the complete environment from the test case', async () => {
- const environment = {
- toolForwarding: {
- memory: { endpoint: 'https://mock.test/tool-calls' },
- },
- };
- const { run, testCase } = await setupTrajectoryChain({ environment });
-
+ it('refuses legacy unbound forwarding', async () => {
+ const { run, testCase } = await setupTrajectoryChain();
+ await serverDB
+ .update(agentEvalTestCases)
+ .set({
+ content: {
+ input: 'test',
+ environment: {
+ toolForwarding: { memory: { endpoint: 'https://old.test/exec' } },
+ },
+ },
+ })
+ .where(eq(agentEvalTestCases.id, testCase.id));
const service = new AgentEvalRunService(serverDB, userId);
- const data = await service.loadTrajectoryData(run.id, testCase.id);
-
- expect('error' in data).toBe(false);
- if (!('error' in data)) expect(data.environment).toEqual(environment);
+ await expect(service.loadTrajectoryData(run.id, testCase.id)).rejects.toThrow(
+ 'Bind these mock services',
+ );
});
it('should return error when run not found', async () => {
@@ -234,10 +242,10 @@ describe('AgentEvalRunService', () => {
expect(runTopic).toBeDefined();
expect(runTopic?.topicId).toBe(result.topicId);
- // Verify operationId was stored in evalResult
+ // Verify operationId was stored in evalResult, bound to this execution
expect(runTopic?.evalResult).toMatchObject({
+ executionId: expect.any(String),
operationId: 'op-123',
- rubricScores: [],
});
// Verify execAgent was called with correct params
@@ -250,7 +258,13 @@ describe('AgentEvalRunService', () => {
id: 'eval-trajectory-complete',
type: 'onComplete',
webhook: {
- body: { runId: run.id, testCaseId: testCase.id, userId },
+ body: {
+ executionId: runTopic?.evalResult?.executionId,
+ runId: run.id,
+ testCaseId: testCase.id,
+ topicId: result.topicId,
+ userId,
+ },
delivery: 'qstash',
url: '/api/workflows/agent-eval-run/on-trajectory-complete',
},
@@ -283,30 +297,19 @@ describe('AgentEvalRunService', () => {
);
});
- it('should derive tool forwarding from the case environment', async () => {
+ it('rejects an unbound mock before starting an attempt', async () => {
const { run, testCase } = await setupTrajectoryChain();
- const environment = {
- toolForwarding: {
- memory: { endpoint: 'https://mock.test/tool-calls' },
- },
- };
-
- mockExecAgent.mockResolvedValue({ operationId: 'op-789' });
-
const service = new AgentEvalRunService(serverDB, userId);
- await service.executeTrajectory({
- run: { datasetId: run.datasetId, targetAgentId: null },
- runId: run.id,
- testCase: { content: { input: 'What is 6*7?' }, sortOrder: testCase.sortOrder },
- testCaseId: testCase.id,
- environment,
- });
-
- expect(mockExecAgent).toHaveBeenCalledWith(
- expect.objectContaining({
- evalRuntime: { toolForwarding: environment.toolForwarding },
+ await expect(
+ service.executeTrajectory({
+ run: { datasetId: run.datasetId, targetAgentId: null },
+ runId: run.id,
+ testCase: { content: { input: 'Question' } },
+ testCaseId: testCase.id,
+ environment: { toolForwarding: { memory: { endpoint: 'https://old.test/exec' } } },
}),
- );
+ ).rejects.toThrow('Bind these mock services');
+ expect(mockExecAgent).not.toHaveBeenCalled();
});
it('should pass the dataset case id through evalRuntime', async () => {
@@ -327,7 +330,18 @@ describe('AgentEvalRunService', () => {
});
expect(mockExecAgent).toHaveBeenCalledWith(
- expect.objectContaining({ evalRuntime: { caseId: 'case-42' } }),
+ expect.objectContaining({
+ appContext: expect.objectContaining({ suppressSignal: true }),
+ evalRuntime: {
+ attemptId: expect.any(String),
+ caseId: 'case-42',
+ memory: {
+ fixtureHash: expect.any(String),
+ runId: expect.any(String),
+ topicId: expect.any(String),
+ },
+ },
+ }),
);
});
diff --git a/apps/server/src/services/agentEvalRun/__tests__/trajectoryPayload.test.ts b/apps/server/src/services/agentEvalRun/__tests__/trajectoryPayload.test.ts
new file mode 100644
index 00000000000..37722917029
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/__tests__/trajectoryPayload.test.ts
@@ -0,0 +1,197 @@
+import type { EvalCaseEnvironment } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentEvalEnvironmentModel, AgentEvalRunModel } from '@/database/models/agentEval';
+import { ConnectorModel } from '@/database/models/connector';
+import { agentEvalDatasets, agentEvalRuns, agentEvalTestCases } from '@/database/schemas';
+import { AgentEvalRunService } from '@/server/services/agentEvalRun';
+import { serializeStepResult } from '@/server/workflows/testing/stepContext';
+
+import { getEvalContextParams } from '../utils';
+import { cleanupDB, serverDB, userId } from './_setup';
+
+const { listRawTools, gateKeeper } = vi.hoisted(() => ({
+ listRawTools: vi.fn(),
+ gateKeeper: {
+ decrypt: async (ciphertext: string) => ({ plaintext: ciphertext.replace(/^sealed:/, '') }),
+ encrypt: async (plaintext: string) => `sealed:${plaintext}`,
+ },
+}));
+vi.mock('@/server/services/mcp', () => ({ mcpService: { listRawTools } }));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: async () => gateKeeper },
+}));
+vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({
+ AgentRuntimeService: class {
+ interruptOperation = vi.fn();
+ },
+}));
+vi.mock('@/server/workflows/agentEvalRun', () => ({ AgentEvalRunWorkflow: {} }));
+
+beforeEach(async () => {
+ await cleanupDB();
+ listRawTools.mockReset().mockResolvedValue([{ name: 'read', inputSchema: { type: 'object' } }]);
+});
+
+const byteLength = (value: unknown) => Buffer.byteLength(JSON.stringify(value));
+const fixture = async () => {
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({
+ evalConfig: { envPrompt: 'Dataset instructions' },
+ identifier: 'payload',
+ name: 'Payload',
+ userId,
+ })
+ .returning();
+ const connector = await ConnectorModel.forEvaluation(
+ serverDB,
+ userId,
+ dataset.id,
+ undefined,
+ gateKeeper,
+ ).create({
+ credentials: JSON.stringify({ type: 'bearer', token: 'synthetic-secret-never-in-checkpoint' }),
+ identifier: 'eval-private',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://private.example/mcp',
+ name: 'Management name',
+ sourceType: 'custom',
+ status: 'disconnected',
+ });
+ const config: EvalCaseEnvironment = {
+ agent: { plugins: ['notion'], systemRole: 'Persona' },
+ connectorBindings: { notion: { connectorId: connector.id, transport: 'mcp' } },
+ envPrompt: 'Case instructions',
+ mock: { services: ['notion'] },
+ sessionDate: '2026-11-04',
+ timezone: 'UTC',
+ toolManifests: {
+ notion: {
+ api: [
+ {
+ name: 'read',
+ description: 'Original contract detail. '.repeat(2600),
+ parameters: { type: 'object', properties: { query: { type: 'string' } } },
+ },
+ ],
+ identifier: 'notion',
+ meta: { description: 'Original API', title: 'Notion' },
+ type: 'mcp',
+ },
+ },
+ };
+ const environment = await new AgentEvalEnvironmentModel(serverDB, userId).create({
+ config,
+ name: 'Shared',
+ });
+ const [testCase] = await serverDB
+ .insert(agentEvalTestCases)
+ .values({
+ content: {
+ input: 'Read data',
+ expected: 'Expected answer',
+ messages: [{ role: 'user', content: 'History' }],
+ },
+ datasetId: dataset.id,
+ environmentId: environment.id,
+ metadata: { caseId: 'native-case' },
+ sortOrder: 1,
+ userId,
+ })
+ .returning();
+ const service = new AgentEvalRunService(serverDB, userId);
+ const run = await service.createRun({
+ config: {
+ k: 3,
+ maxSteps: 24,
+ model: 'fixture',
+ provider: 'fixture',
+ chatConfig: { reasoning_effort: 'high' },
+ },
+ datasetId: dataset.id,
+ });
+ return { config, dataset, run, service, testCase };
+};
+
+describe('Trajectory checkpoint payload', () => {
+ it('keeps one case payload unchanged when 49 unrelated frozen contracts are added', async () => {
+ const { run, service, testCase } = await fixture();
+ const before = await service.loadTrajectoryData(run.id, testCase.id);
+ if ('error' in before) throw new Error(before.error);
+ const current = run.config!.connectorSnapshots![testCase.id];
+ const connectorSnapshots = {
+ [testCase.id]: current,
+ ...Object.fromEntries(
+ Array.from({ length: 49 }, (_, index) => [`unrelated-${index}`, current]),
+ ),
+ };
+ await serverDB
+ .update(agentEvalRuns)
+ .set({ config: { ...run.config, connectorSnapshots } })
+ .where(eq(agentEvalRuns.id, run.id));
+ const after = await service.loadTrajectoryData(run.id, testCase.id);
+ if ('error' in after) throw new Error(after.error);
+ expect(byteLength(after)).toBe(byteLength(before));
+ expect(Object.keys(after.run.config!.connectorSnapshots!)).toEqual([testCase.id]);
+ expect(after.testCase.content).not.toHaveProperty('environment');
+ expect(after.testCase.content).toEqual(before.testCase.content);
+ expect(JSON.stringify(after)).not.toMatch(/unrelated-|synthetic-secret|private\.example/);
+ const stored = await new AgentEvalRunModel(serverDB, userId).findById(run.id);
+ expect(Object.keys(stored!.config!.connectorSnapshots!)).toHaveLength(50);
+ const oldPayload = {
+ ...after,
+ run: stored,
+ testCase: {
+ ...after.testCase,
+ content: { ...after.testCase.content, environment: after.environment },
+ },
+ };
+ expect(byteLength(oldPayload)).toBeGreaterThan(byteLength(after) * 20);
+ });
+
+ it('preserves frozen aliases, fingerprints, Dataset scope, execution settings and context across JSON checkpoints', async () => {
+ const { config, dataset, run, service, testCase } = await fixture();
+ const loaded = await service.loadTrajectoryData(run.id, testCase.id);
+ if ('error' in loaded) throw new Error(loaded.error);
+ const restored = serializeStepResult(loaded);
+ expect(restored.environment).toEqual(config);
+ expect(restored.run.config).toEqual(run.config);
+ const snapshot = restored.run.config!.connectorSnapshots![testCase.id].notion;
+ expect(snapshot.datasetId).toBe(dataset.id);
+ expect(snapshot.fingerprint).toMatch(/^[a-f\d]{64}$/);
+ expect(snapshot.manifest).toEqual(config.toolManifests!.notion);
+ expect(restored.testCase).toMatchObject({
+ id: testCase.id,
+ metadata: { caseId: 'native-case' },
+ sortOrder: 1,
+ });
+ const context = (data: typeof loaded) =>
+ getEvalContextParams(
+ data.envPrompt,
+ data.environment,
+ 'native-case',
+ undefined,
+ 'attempt',
+ data.run.config!.connectorSnapshots![testCase.id],
+ );
+ expect(context(restored)).toEqual(context(loaded));
+ });
+
+ it('rejects a different Dataset case even when both belong to the same owner', async () => {
+ const { run, service } = await fixture();
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({ identifier: 'other', name: 'Other', userId })
+ .returning();
+ const [testCase] = await serverDB
+ .insert(agentEvalTestCases)
+ .values({ content: { input: 'Other' }, datasetId: dataset.id, userId })
+ .returning();
+ expect(await service.loadTrajectoryData(run.id, testCase.id)).toEqual({
+ error: 'Test case not found',
+ });
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/aggregate.test.ts b/apps/server/src/services/agentEvalRun/aggregate.test.ts
new file mode 100644
index 00000000000..d40afeb1700
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/aggregate.test.ts
@@ -0,0 +1,134 @@
+import type { EvalThreadResult } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { evaluateAndFinalizeRun } from './aggregate';
+
+const passing = (id: string): EvalThreadResult => ({
+ passed: true,
+ status: 'passed',
+ threadId: id,
+});
+const topic = (threads: EvalThreadResult[]) => ({
+ evalResult: { cost: 0.03, passAllK: false, passAtK: true, threads },
+ passed: true,
+ runId: 'run',
+ score: 1,
+ status: 'passed',
+ topicId: 'topic',
+});
+
+describe('complete sample quality metrics', () => {
+ it.each(['error', 'timeout', 'judge_error', 'external'] as const)(
+ 'excludes historical passed rows containing a %s attempt',
+ async (status) => {
+ const metrics = await evaluateAndFinalizeRun({
+ run: { config: { k: 3 }, id: 'run' },
+ runTopics: [topic([passing('1'), passing('2'), { passed: false, status, threadId: '3' }])],
+ });
+ expect(metrics.passedCases).toBe(0);
+ expect(metrics.failedCases).toBe(0);
+ expect(metrics.passAllAt).toBeUndefined();
+ expect(metrics.passAnyAt).toBeUndefined();
+ expect(metrics.passAllK).toBeUndefined();
+ expect(metrics.passAtK).toBeUndefined();
+ expect(metrics.totalCost).toBe(0.03);
+ const countKey = {
+ error: 'errorCases',
+ timeout: 'timeoutCases',
+ judge_error: 'judgeErrorCases',
+ external: 'externalCases',
+ }[status];
+ expect(metrics[countKey]).toBe(1);
+ },
+ );
+
+ it('recognizes legacy no-output failures without reclassifying step caps', async () => {
+ for (const error of [
+ 'No assistant output',
+ 'Reached the step limit (20) without a final answer',
+ ]) {
+ const metrics = await evaluateAndFinalizeRun({
+ run: { config: { k: 3 }, id: 'run' },
+ runTopics: [
+ topic([
+ passing('1'),
+ passing('2'),
+ { error, passed: false, status: 'failed', threadId: '3' },
+ ]),
+ ],
+ });
+ expect(metrics.errorCases).toBe(error === 'No assistant output' ? 1 : 0);
+ expect(metrics.passAllAt?.['3']).toBe(error === 'No assistant output' ? undefined : 0);
+ }
+ });
+
+ it('does not publish complete pass estimates for missing attempts or mixed valid/error cases', async () => {
+ for (const runTopics of [
+ [topic([passing('1'), passing('2')])],
+ [
+ topic([passing('1'), passing('2'), passing('3')]),
+ { ...topic([]), status: 'error', topicId: 'other' },
+ ],
+ ]) {
+ const metrics = await evaluateAndFinalizeRun({
+ run: { config: { k: 3 }, id: 'run' },
+ runTopics,
+ });
+ expect(metrics.passAllAt).toBeUndefined();
+ expect(metrics.errorCases).toBe(1);
+ expect(metrics.failedCases).toBe(0);
+ }
+ });
+
+ it('retains the combinatorial estimate for complete valid attempts', async () => {
+ const metrics = await evaluateAndFinalizeRun({
+ run: { config: { k: 4 }, id: 'run' },
+ runTopics: [
+ topic([
+ passing('1'),
+ passing('2'),
+ passing('3'),
+ { passed: false, status: 'failed', threadId: '4' },
+ ]),
+ ],
+ });
+ expect(metrics.passAllAt?.['3']).toBe(0.25);
+ expect(metrics.passAnyAt?.['3']).toBe(1);
+ expect(metrics.errorCases).toBe(0);
+ });
+});
+
+describe('historical grading evidence', () => {
+ it.each([null, undefined])(
+ 'requires a boolean verdict for pass@1, even with a terminal status (passed=%s)',
+ async (passed) => {
+ for (const status of ['passed', 'failed']) {
+ const metrics = await evaluateAndFinalizeRun({
+ run: { id: 'run' },
+ runTopics: [{ passed, runId: 'run', status, topicId: 'topic' }],
+ });
+ expect(metrics).toMatchObject({ errorCases: 1, failedCases: 0, passedCases: 0 });
+ expect(metrics.passAllAt).toBeUndefined();
+ }
+ },
+ );
+
+ it.each([false, true])(
+ 'honors legacy judge errorPhase on a passed row (threaded=%s)',
+ async (threaded) => {
+ const metrics = await evaluateAndFinalizeRun({
+ run: { config: { k: threaded ? 2 : 1 }, id: 'run' },
+ runTopics: [
+ {
+ ...topic([]),
+ evalResult: threaded
+ ? { threads: [passing('1'), { ...passing('2'), errorPhase: 'judge' }] }
+ : { errorPhase: 'judge' },
+ },
+ ],
+ });
+ expect(metrics).toMatchObject({ failedCases: 0, judgeErrorCases: 1, passedCases: 0 });
+ expect(metrics.passAllAt).toBeUndefined();
+ },
+ );
+});
diff --git a/apps/server/src/services/agentEvalRun/aggregate.ts b/apps/server/src/services/agentEvalRun/aggregate.ts
index 7d9c4fd2824..5b7207ae8a2 100644
--- a/apps/server/src/services/agentEvalRun/aggregate.ts
+++ b/apps/server/src/services/agentEvalRun/aggregate.ts
@@ -1,6 +1,14 @@
import type { EvalRunConfig, EvalRunMetrics, EvalRunTopicResult } from '@lobechat/types';
const roundCost = (v: number): number => Math.round(v * 1e6) / 1e6;
+
+/** Binomial coefficient C(n, r); 0 when r is out of range. */
+const choose = (n: number, r: number): number => {
+ if (r < 0 || r > n) return 0;
+ let result = 1;
+ for (let i = 1; i <= r; i++) result = (result * (n - r + i)) / i;
+ return result;
+};
export async function evaluateAndFinalizeRun(params: {
/**
* Dataset case count. For external runs (Topics created on demand) this is
@@ -35,6 +43,9 @@ export async function evaluateAndFinalizeRun(params: {
let errorCases = 0;
let externalCases = 0;
let timeoutCases = 0;
+ // Attempts that ran but the judge could not grade: neither failed nor
+ // scored. The run's grading is incomplete while any remain.
+ let judgeErrorCases = 0;
let totalScore = 0;
// Sum of per-case averages (for per-case display)
let sumCost = 0;
@@ -51,6 +62,11 @@ export async function evaluateAndFinalizeRun(params: {
// pass@k / pass^k counters (only meaningful when k > 1)
let passAtKCount = 0;
let passAllKCount = 0;
+ // pass^j / pass@j for every j ≀ k, estimated without bias from each case's
+ // passed attempts (Ο„-bench's pass^k, the Codex paper's pass@k), so runs of
+ // different attempt counts compare on the same j.
+ const passAllAtSum = Array.from({ length: k + 1 }, () => 0);
+ const passAnyAtSum = Array.from({ length: k + 1 }, () => 0);
for (const runTopic of runTopics) {
const existingResult = runTopic.evalResult;
@@ -67,36 +83,57 @@ export async function evaluateAndFinalizeRun(params: {
actualTotalTokens += existingResult?.totalTokens ?? existingResult?.tokens ?? 0;
actualTotalDuration += existingResult?.totalDuration ?? existingResult?.duration ?? 0;
- // Count by status
- if (runTopic.status === 'passed') {
+ // Older stored rows may say "passed" despite an errored attempt. Rebuild
+ // eligibility from the evidence, never trust that historical summary alone.
+ const threads = existingResult?.threads;
+ let status = runTopic.status;
+ if (
+ threads?.some((t) => t.status === 'error' || t.error === 'No assistant output') ||
+ existingResult?.error === 'No assistant output'
+ )
+ status = 'error';
+ else if (threads?.some((t) => t.status === 'timeout')) status = 'timeout';
+ else if (
+ existingResult?.errorPhase === 'judge' ||
+ threads?.some((t) => t.status === 'judge_error' || t.errorPhase === 'judge')
+ )
+ status = 'judge_error';
+ else if (threads?.some((t) => t.status === 'external')) status = 'external';
+ else if (
+ (status === 'passed' || status === 'failed') &&
+ (typeof runTopic.passed !== 'boolean' ||
+ (k > 1 && (!threads || threads.length !== k)) ||
+ threads?.some(
+ (t) =>
+ typeof t.passed !== 'boolean' ||
+ (t.status && !['passed', 'failed', 'completed'].includes(t.status)),
+ ))
+ )
+ status = 'error';
+
+ // Count by effective status. Invalid attempts are never model failures.
+ if (status === 'passed') {
passedCases++;
- } else if (runTopic.status === 'failed') {
+ } else if (status === 'failed') {
failedCases++;
- } else if (runTopic.status === 'error') {
+ } else if (status === 'error') {
errorCases++;
- } else if (runTopic.status === 'external') {
+ } else if (status === 'external') {
externalCases++;
- } else if (runTopic.status === 'timeout') {
+ } else if (status === 'timeout') {
timeoutCases++;
+ } else if (status === 'judge_error') {
+ judgeErrorCases++;
}
- // Only accumulate scores for evaluated (non-error, non-timeout, non-external) cases
- if (
- runTopic.status !== 'error' &&
- runTopic.status !== 'timeout' &&
- runTopic.status !== 'external' &&
- runTopic.score != null
- ) {
+ // Only accumulate scores for judged (passed/failed) cases
+ const judged = status === 'passed' || status === 'failed';
+ if (judged && runTopic.score != null) {
totalScore += runTopic.score;
}
- // Accumulate per-rubric scores from existing evalResult (exclude error/timeout/external cases)
- if (
- runTopic.status !== 'error' &&
- runTopic.status !== 'timeout' &&
- runTopic.status !== 'external' &&
- existingResult?.rubricScores
- ) {
+ // Accumulate per-rubric scores from judged cases only
+ if (judged && existingResult?.rubricScores) {
for (const rs of existingResult.rubricScores) {
if (!rubricScoreAcc[rs.rubricId]) {
rubricScoreAcc[rs.rubricId] = { count: 0, sum: 0 };
@@ -106,8 +143,25 @@ export async function evaluateAndFinalizeRun(params: {
}
}
- // pass@k / pass^k: derive from thread results when k > 1
- if (k > 1 && existingResult?.threads && existingResult.threads.length > 0) {
+ // Only complete judged samples contribute to quality estimates.
+ if (judged) {
+ const threads = existingResult?.threads;
+ const n = threads && threads.length > 0 ? threads.length : 1;
+ const c =
+ threads && threads.length > 0
+ ? threads.filter((t) => t.passed === true).length
+ : status === 'passed'
+ ? 1
+ : 0;
+ for (let j = 1; j <= Math.min(k, n); j++) {
+ passAllAtSum[j] += choose(c, j) / choose(n, j);
+ passAnyAtSum[j] += 1 - choose(n - c, j) / choose(n, j);
+ }
+ }
+
+ // pass@k / pass^k: derive from thread results when k > 1. A case with an
+ // unjudged thread has unknown pass@k and pass^k, so it counts for neither.
+ if (k > 1 && judged && existingResult?.threads && existingResult.threads.length > 0) {
const anyThreadPassed = existingResult.threads.some((t) => t.passed === true);
const allThreadsPassed = existingResult.threads.every((t) => t.passed === true);
if (anyThreadPassed) passAtKCount++;
@@ -136,6 +190,7 @@ export async function evaluateAndFinalizeRun(params: {
errorCases,
externalCases: externalCases || undefined,
failedCases,
+ judgeErrorCases: judgeErrorCases || undefined,
llmCalls: sumLlmCalls || undefined,
passRate: totalCases > 0 ? passedCases / totalCases : 0,
passedCases,
@@ -158,8 +213,18 @@ export async function evaluateAndFinalizeRun(params: {
totalTokens: actualTotalTokens || undefined,
};
+ const complete = totalCases > 0 && evaluatedCases === totalCases;
+ if (complete) {
+ metrics.passAllAt = Object.fromEntries(
+ passAllAtSum.slice(1).map((sum, index) => [String(index + 1), sum / totalCases]),
+ );
+ metrics.passAnyAt = Object.fromEntries(
+ passAnyAtSum.slice(1).map((sum, index) => [String(index + 1), sum / totalCases]),
+ );
+ }
+
// Add pass@k / pass^k only when k > 1
- if (k > 1) {
+ if (k > 1 && complete) {
metrics.passAtK = totalCases > 0 ? passAtKCount / totalCases : 0;
metrics.passAllK = totalCases > 0 ? passAllKCount / totalCases : 0;
}
diff --git a/apps/server/src/services/agentEvalRun/caseAgent.ts b/apps/server/src/services/agentEvalRun/caseAgent.ts
new file mode 100644
index 00000000000..627d99ede03
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/caseAgent.ts
@@ -0,0 +1,181 @@
+import { DEFAULT_AGENT_CONFIG } from '@lobechat/const';
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { EvalCaseEnvironment, EvalRunConfig } from '@lobechat/types';
+import { getActivePluginIds } from '@lobechat/types';
+import { and, eq, sql } from 'drizzle-orm';
+
+import { AgentModel } from '@/database/models/agent';
+import { agents } from '@/database/schemas';
+
+import type { EvalRunDeps } from './types';
+
+/**
+ * A model-only run's contender settings, passed to `execAgent` as its chatConfig
+ * override. The runtime otherwise drops reasoning-effort fields from the Agent's
+ * chatConfig in favour of the account's saved per-model defaults; as an override
+ * the contender's choices win, so a run uses the settings it records.
+ */
+export const contenderChatConfigOf = (run?: { config?: unknown } | null) =>
+ (run?.config as EvalRunConfig | null | undefined)?.chatConfig ?? undefined;
+
+/**
+ * Per-case hidden Agents.
+ *
+ * A case that brings its own Agent setup (`environment.agent`), or any case of
+ * a run that picks a model instead of an Agent (`config.model`), runs on a
+ * `virtual` Agent created for that (run, case) pair. Virtual Agents stay out
+ * of the Agent list and recents, the eval topic already stays out of the chat
+ * sidebar (`trigger = 'eval'`), and the topic's `agent_id` records which Agent
+ * answered β€” the same shape the Goal supervisor uses.
+ *
+ * The slug is derived from the run and case ids, so a retried case reuses its
+ * Agent and deleting a run can find every Agent it created.
+ */
+
+export interface CaseAgentRun {
+ config?: EvalRunConfig | null;
+ id: string;
+ targetAgentId?: string | null;
+}
+
+interface CaseAgentTestCase {
+ content: { environment?: EvalCaseEnvironment };
+ id: string;
+ sortOrder: number | null;
+}
+
+type BaseAgentConfig = Awaited<ReturnType<EvalRunDeps['agentService']['getAgentConfigById']>>;
+
+export const CASE_AGENT_MODEL_REQUIRED =
+ 'This run needs a model: choose a target Agent or set config.model and config.provider';
+
+const caseAgentSlugPrefix = (runId: string) => `eval-${runId}-`;
+
+export const caseAgentSlug = (runId: string, testCaseId: string) =>
+ `${caseAgentSlugPrefix(runId)}${testCaseId}`;
+
+export const needsCaseAgent = (run: CaseAgentRun, environment?: EvalCaseEnvironment) =>
+ !!run.config?.model || !!environment?.agent;
+
+/**
+ * Loads what every case Agent of this batch inherits: the run's target Agent
+ * (resolved with its defaults, so later edits to that Agent do not leak into a
+ * running benchmark), or nothing when the run only picks a model.
+ */
+export const loadCaseAgentBase = async (
+ deps: EvalRunDeps,
+ run: CaseAgentRun,
+ testCases: CaseAgentTestCase[],
+): Promise<BaseAgentConfig | undefined> => {
+ if (!run.targetAgentId) return undefined;
+ if (!testCases.some((testCase) => needsCaseAgent(run, testCase.content.environment))) {
+ return undefined;
+ }
+ return deps.agentService.getAgentConfigById(run.targetAgentId);
+};
+
+const buildCaseAgent = (
+ run: CaseAgentRun,
+ testCase: CaseAgentTestCase,
+ base: BaseAgentConfig | undefined,
+) => {
+ const caseAgent = testCase.content.environment?.agent;
+ const model = run.config?.model ?? base?.model;
+ const provider = run.config?.provider ?? base?.provider;
+ if (!model || !provider) throw new Error(CASE_AGENT_MODEL_REQUIRED);
+
+ // A model-only run's contender settings override the target Agent's (or the
+ // product default) for every case, so two runs of one model with different
+ // settings compare the settings, not the cases.
+ const baseChatConfig = {
+ ...(base?.chatConfig ?? DEFAULT_AGENT_CONFIG.chatConfig),
+ ...run.config?.chatConfig,
+ };
+ const chatConfig = caseAgent?.memory
+ ? { ...baseChatConfig, memory: { ...baseChatConfig.memory, ...caseAgent.memory } }
+ : baseChatConfig;
+
+ return {
+ chatConfig,
+ fewShots: base?.fewShots,
+ model,
+ params: { ...(base?.params ?? DEFAULT_AGENT_CONFIG.params), ...run.config?.params },
+ plugins: caseAgent?.plugins ?? (base ? getActivePluginIds(base.plugins) : []),
+ provider,
+ // Name and title reach the prompt (`<agent_identity>`), so the Agent carries
+ // only what the case or the target Agent declares; the eval label lives in
+ // the description, which the model never sees.
+ description: `Lobe Bench attempt agent for case ${(testCase.sortOrder ?? 0) + 1}`,
+ name: caseAgent?.name ?? base?.name ?? null,
+ slug: caseAgentSlug(run.id, testCase.id),
+ systemRole: caseAgent?.systemRole ?? base?.systemRole ?? '',
+ title: caseAgent?.title ?? base?.title ?? null,
+ virtual: true,
+ };
+};
+
+/**
+ * Returns the Agent each case's topic belongs to, creating the hidden case
+ * Agents that do not exist yet. Runs inside the caller's transaction so a
+ * failed topic insert leaves no stray Agents behind.
+ */
+export const ensureCaseAgents = async (
+ tx: LobeChatDatabase,
+ deps: EvalRunDeps,
+ run: CaseAgentRun,
+ testCases: CaseAgentTestCase[],
+ base: BaseAgentConfig | undefined,
+): Promise<Map<string, string | null>> => {
+ const agentModel = new AgentModel(tx, deps.userId, deps.workspaceId);
+ const agentIds = new Map<string, string | null>();
+
+ for (const testCase of testCases) {
+ if (!needsCaseAgent(run, testCase.content.environment)) {
+ agentIds.set(testCase.id, run.targetAgentId ?? null);
+ continue;
+ }
+
+ const existingId = await agentModel.resolveIdBySlug(caseAgentSlug(run.id, testCase.id));
+ if (existingId) {
+ agentIds.set(testCase.id, existingId);
+ continue;
+ }
+
+ const created = await agentModel.create(buildCaseAgent(run, testCase, base));
+ agentIds.set(testCase.id, created.id);
+ }
+
+ return agentIds;
+};
+
+/**
+ * The Agent a trajectory runs on is the one its topic belongs to: the case's
+ * hidden Agent, or the run's target Agent for runs created before case Agents.
+ */
+export const resolveTopicAgentId = async (
+ deps: EvalRunDeps,
+ topicId: string,
+ fallbackAgentId?: string | null,
+): Promise<string | undefined> => {
+ const topic = await deps.topicModel.findById(topicId);
+ return topic?.agentId ?? fallbackAgentId ?? undefined;
+};
+
+/** Deletes the hidden Agents a run created (their topics cascade with them). */
+export const deleteCaseAgents = async (deps: EvalRunDeps, runId: string) => {
+ const rows = await deps.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(
+ and(
+ eq(agents.userId, deps.userId),
+ eq(agents.virtual, true),
+ sql`starts_with(${agents.slug}, ${caseAgentSlugPrefix(runId)})`,
+ ),
+ );
+ if (rows.length === 0) return;
+
+ await new AgentModel(deps.db, deps.userId, deps.workspaceId).batchDelete(
+ rows.map((row) => row.id),
+ );
+};
diff --git a/apps/server/src/services/agentEvalRun/caseCompatibility.test.ts b/apps/server/src/services/agentEvalRun/caseCompatibility.test.ts
new file mode 100644
index 00000000000..e37862abc9f
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/caseCompatibility.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { assertRunCaseCompatibility, EvalCaseCompatibilityError } from './caseCompatibility';
+import type { EvalRunDeps } from './types';
+
+const depsFor = (metadata?: Record<string, unknown>) =>
+ ({
+ datasetModel: { findById: vi.fn().mockResolvedValue({ metadata }) },
+ }) as unknown as Pick<EvalRunDeps, 'datasetModel'>;
+
+describe('assertRunCaseCompatibility', () => {
+ it('allows unversioned Eval Lab runs and matching Release/presentation versions', async () => {
+ await expect(
+ assertRunCaseCompatibility(depsFor(), { datasetId: 'lab' }),
+ ).resolves.toBeUndefined();
+ await expect(
+ assertRunCaseCompatibility(
+ depsFor({ release: 'v1', presentation: 'realism-v1' }),
+ { config: { caseVersion: 'v1+realism-v1' }, datasetId: 'bench' },
+ [{ testCase: { metadata: {} }, testCaseId: 'case' }],
+ ),
+ ).resolves.toBeUndefined();
+ });
+
+ it.each([
+ ['v1', { release: 'v2' }],
+ ['v1+realism-v1', { release: 'v1', presentation: 'realism-v2' }],
+ [undefined, { release: 'v1' }],
+ ['v1', undefined],
+ ] as const)(
+ 'rejects incompatible stored version %s and current metadata %o',
+ async (caseVersion, metadata) => {
+ await expect(
+ assertRunCaseCompatibility(depsFor(metadata), {
+ config: { caseVersion },
+ datasetId: 'bench',
+ }),
+ ).rejects.toThrow(EvalCaseCompatibilityError);
+ },
+ );
+
+ it('rejects retired or unavailable targets even when versions match', async () => {
+ for (const testCase of [null, { metadata: { retired: true } }]) {
+ await expect(
+ assertRunCaseCompatibility(
+ depsFor({ release: 'v1' }),
+ { config: { caseVersion: 'v1' }, datasetId: 'bench' },
+ [{ testCase, testCaseId: 'old-case' }],
+ ),
+ ).rejects.toThrow('retired or missing case');
+ }
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/caseCompatibility.ts b/apps/server/src/services/agentEvalRun/caseCompatibility.ts
new file mode 100644
index 00000000000..e2ffc578002
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/caseCompatibility.ts
@@ -0,0 +1,38 @@
+import { evalCaseVersionOf } from '@lobechat/types';
+
+import { isRetiredEvalTestCase } from '@/database/models/agentEval/testCase';
+
+import type { EvalRunDeps } from './types';
+
+export class EvalCaseCompatibilityError extends Error {
+ constructor(message: string) {
+ super(`${message}. Create a new experiment with the current dataset instead.`);
+ this.name = 'EvalCaseCompatibilityError';
+ }
+}
+
+interface CaseTarget {
+ testCase?: { metadata?: Record<string, unknown> | null } | null;
+ testCaseId: string;
+}
+
+/**
+ * Prevent known incompatible retries from rewriting historical evidence. This
+ * compares the recorded Release/presentation, not a complete environment snapshot.
+ */
+export const assertRunCaseCompatibility = async (
+ deps: Pick<EvalRunDeps, 'datasetModel'>,
+ run: { config?: { caseVersion?: string } | null; datasetId: string },
+ targets: CaseTarget[] = [],
+) => {
+ const dataset = await deps.datasetModel.findById(run.datasetId);
+ if (!dataset) throw new EvalCaseCompatibilityError('The run dataset is no longer available');
+
+ if (run.config?.caseVersion !== evalCaseVersionOf(dataset.metadata)) {
+ throw new EvalCaseCompatibilityError('The dataset case version has changed since this run');
+ }
+
+ if (targets.some((target) => !target.testCase || isRetiredEvalTestCase(target.testCase))) {
+ throw new EvalCaseCompatibilityError('The requested cases include a retired or missing case');
+ }
+};
diff --git a/apps/server/src/services/agentEvalRun/caseEnvironment.test.ts b/apps/server/src/services/agentEvalRun/caseEnvironment.test.ts
new file mode 100644
index 00000000000..bd6f02823a3
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/caseEnvironment.test.ts
@@ -0,0 +1,70 @@
+import { evalToolManifestSchema, redactEnvironmentConnections } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { mergeCaseEnvironment } from './caseEnvironment';
+
+const contract = (identifier: string, description = 'Original read') => ({
+ identifier,
+ meta: { title: identifier },
+ api: [{ name: 'read', description, parameters: { type: 'object' } }],
+});
+
+describe('frozen environment tool contracts', () => {
+ it('a case overrides one contract without dropping the other inherited tools', () => {
+ const shared = { toolManifests: { notion: contract('notion'), gmail: contract('gmail') } };
+ const own = { toolManifests: { notion: contract('notion', 'Case-specific read') } };
+ expect(mergeCaseEnvironment(shared, own)?.toolManifests).toEqual({
+ notion: own.toolManifests.notion,
+ gmail: shared.toolManifests.gmail,
+ });
+ });
+
+ it('rejects ambiguous routing names and execution configuration in a model-facing contract', () => {
+ expect(evalToolManifestSchema.safeParse(contract('notion____other')).success).toBe(false);
+ expect(
+ evalToolManifestSchema.safeParse({
+ ...contract('notion'),
+ api: [{ ...contract('notion').api[0], name: 'read____other' }],
+ }).success,
+ ).toBe(false);
+ expect(
+ evalToolManifestSchema.safeParse({
+ ...contract('notion'),
+ mcpParams: { url: 'https://mock.invalid' },
+ }).success,
+ ).toBe(false);
+ expect(evalToolManifestSchema.safeParse(contract('notion')).success).toBe(true);
+ });
+});
+
+describe('connections stored in a shared Environment', () => {
+ const shared = {
+ connections: {
+ gmail: { credentials: 'sealed-secret', name: 'Gmail', url: 'https://mock.test/mcp/a/gmail' },
+ },
+ mock: { services: ['gmail', 'slack'] },
+ };
+
+ it('come from the shared Environment only, never from a case', () => {
+ const merged = mergeCaseEnvironment(shared, {
+ connections: { gmail: { credentials: 'case-secret', url: 'https://evil.test/mcp/a/gmail' } },
+ mock: { services: ['gmail'] },
+ });
+ expect(merged?.connections).toEqual(shared.connections);
+ expect(merged?.mock?.services).toEqual(['gmail']);
+ expect(
+ mergeCaseEnvironment(undefined, {
+ connections: { gmail: { url: 'https://evil.test/mcp/a/gmail' } },
+ })?.connections,
+ ).toBeUndefined();
+ });
+
+ it('leave the server without their credentials', () => {
+ const redacted = redactEnvironmentConnections(shared);
+ expect(redacted.connections).toEqual({
+ gmail: { hasCredentials: true, name: 'Gmail', url: 'https://mock.test/mcp/a/gmail' },
+ });
+ expect(JSON.stringify(redacted)).not.toContain('sealed-secret');
+ expect(shared.connections.gmail.credentials).toBe('sealed-secret');
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/caseEnvironment.ts b/apps/server/src/services/agentEvalRun/caseEnvironment.ts
new file mode 100644
index 00000000000..5efaa63c01c
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/caseEnvironment.ts
@@ -0,0 +1,82 @@
+import type { EvalCaseEnvironment } from '@lobechat/types';
+
+import type { EvalRunDeps } from './types';
+
+/**
+ * A case's environment is its shared environment row (`environmentId`) with
+ * the case's own `content.environment` laid over it: a case tweaks a field
+ * (another clock, one more tool) without copying the rest. Cases without an
+ * environment row keep working on their own `content.environment`.
+ */
+export const mergeCaseEnvironment = (
+ shared: EvalCaseEnvironment | null | undefined,
+ rawOwn: EvalCaseEnvironment | null | undefined,
+): EvalCaseEnvironment | undefined => {
+ // Stored connections belong to the shared Environment row alone: a case's own
+ // settings can narrow which services it uses, never bring their own endpoint.
+ const { connections: _ignored, ...ownSettings } = rawOwn ?? {};
+ const own = rawOwn ? ownSettings : rawOwn;
+ if (!shared) return own ?? undefined;
+ if (!own) return shared;
+ return {
+ ...shared,
+ ...own,
+ ...(shared.agent || own.agent
+ ? {
+ agent: {
+ ...shared.agent,
+ ...own.agent,
+ ...(shared.agent?.memory || own.agent?.memory
+ ? { memory: { ...shared.agent?.memory, ...own.agent?.memory } }
+ : {}),
+ },
+ }
+ : {}),
+ ...(shared.mock || own.mock
+ ? { mock: { services: own.mock?.services ?? shared.mock?.services ?? [] } }
+ : {}),
+ ...(shared.toolManifests || own.toolManifests
+ ? { toolManifests: { ...shared.toolManifests, ...own.toolManifests } }
+ : {}),
+ ...(shared.toolForwarding || own.toolForwarding
+ ? { toolForwarding: { ...shared.toolForwarding, ...own.toolForwarding } }
+ : {}),
+ };
+};
+
+interface CaseWithEnvironment {
+ content: { environment?: EvalCaseEnvironment };
+ environmentId?: string | null;
+}
+
+/**
+ * Returns the cases with `content.environment` resolved against their shared
+ * environments (one batch read). Every eval stage that reads a case
+ * environment goes through this, so the rest of the chain never knows whether
+ * the environment was shared or the case's own.
+ */
+export async function withResolvedEnvironments<T extends CaseWithEnvironment>(
+ deps: EvalRunDeps,
+ testCases: T[],
+): Promise<T[]> {
+ const ids = testCases.map((testCase) => testCase.environmentId).filter(Boolean) as string[];
+ if (ids.length === 0) return testCases;
+ const rows = await deps.environmentModel.findByIds(ids);
+ const byId = new Map(rows.map((row) => [row.id, row.config]));
+ return testCases.map((testCase) => {
+ const shared = testCase.environmentId ? byId.get(testCase.environmentId) : undefined;
+ if (!shared) return testCase;
+ return {
+ ...testCase,
+ content: {
+ ...testCase.content,
+ environment: mergeCaseEnvironment(shared, testCase.content.environment),
+ },
+ };
+ });
+}
+
+export const withResolvedEnvironment = async <T extends CaseWithEnvironment>(
+ deps: EvalRunDeps,
+ testCase: T,
+): Promise<T> => (await withResolvedEnvironments(deps, [testCase]))[0];
diff --git a/apps/server/src/services/agentEvalRun/caseFromTopic.ts b/apps/server/src/services/agentEvalRun/caseFromTopic.ts
new file mode 100644
index 00000000000..6b8f8a9357d
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/caseFromTopic.ts
@@ -0,0 +1,211 @@
+import { getActivePluginIds } from '@lobechat/types';
+
+import { initModelRuntimeForRequest } from '@/server/modules/AgentRuntime/llmRelay/oneShot';
+
+import { resolveEvalJudge } from './judge';
+import type { EvalRunDeps } from './types';
+import { log } from './utils';
+
+/**
+ * A case drafted from one of the account's conversations.
+ *
+ * The conversation's last request is the case input, the messages before it
+ * replay as context, the Agent that answered (persona, tools, model) is kept
+ * as the case's own Agent setup, and the judge model drafts the Must / Must
+ * not rules from what happened. Nothing is saved here: the draft goes back to
+ * the UI, where the author edits the rules and saves the case.
+ */
+
+export interface TopicCaseDraft {
+ agent?: {
+ model?: string;
+ name?: string | null;
+ plugins: string[];
+ provider?: string;
+ systemRole?: string;
+ title?: string | null;
+ };
+ /** The reply the conversation recorded; kept as provenance, never as the expected answer. */
+ answer?: string;
+ input: string;
+ messages: Array<{ content: string; createdAt?: string; role: 'assistant' | 'user' }>;
+ rules: string[];
+ /** Why no rules were drafted, when the judge call failed; the author writes them. */
+ rulesError?: string;
+ sessionDate?: string;
+ title: string;
+ /** Connectors the recorded answer called, so the author knows what the case depends on. */
+ toolsUsed: string[];
+}
+
+export const TOPIC_NOT_FOUND = 'Topic not found';
+export const TOPIC_HAS_NO_REQUEST = 'The conversation has no user message to test';
+
+const MAX_PROMPT_CHARS = 4000;
+
+const text = (content: unknown): string => (typeof content === 'string' ? content : '');
+
+const clip = (value: string, max: number) =>
+ value.length > max ? `${value.slice(0, max)}…` : value;
+
+const RULES_SCHEMA: Record<string, unknown> = {
+ additionalProperties: false,
+ properties: {
+ rules: {
+ description: 'Three to seven rules, each one line starting with "Must:" or "Must not:"',
+ items: { type: 'string' },
+ type: 'array',
+ },
+ },
+ required: ['rules'],
+ type: 'object',
+};
+
+const DRAFT_SYSTEM_ROLE = [
+ 'You write the grading rules of an evaluation case for an AI agent.',
+ 'From the conversation, write 3 to 7 rules that a correct answer to the final request must meet. Each rule is one line starting with "Must:" or "Must not:".',
+ 'Rules cover the actions a correct answer takes (which tools it calls, what it changes), the content it has to deliver, and what it must not do. Every rule must be checkable from the reply and the tool calls.',
+ 'Do not grade style or tone, do not quote or reward the recorded answer, and do not invent facts the conversation does not contain.',
+ 'Respond with a JSON object: {"rules": ["Must: …", "Must not: …"]}.',
+].join('\n');
+
+const normalizeRule = (rule: string) => {
+ const line = rule.trim().replace(/^[-*β€’]\s*/, '');
+ if (!line) return '';
+ if (/^must(?:\s+not)?\s*[::]/i.test(line)) return line;
+ return `Must: ${line}`;
+};
+
+async function draftRulesWithJudge(
+ deps: EvalRunDeps,
+ draft: TopicCaseDraft,
+ benchmarkMetadata?: Record<string, unknown> | null,
+): Promise<string[]> {
+ const judge = await resolveEvalJudge(deps, { benchmarkMetadata });
+ const runtime = await initModelRuntimeForRequest(deps.db, deps.userId, judge.provider, {
+ workspaceId: deps.workspaceId,
+ });
+ const sections = [
+ draft.agent?.systemRole && `[Agent persona]\n${clip(draft.agent.systemRole, 2000)}`,
+ draft.agent?.plugins.length && `[Agent tools]\n${draft.agent.plugins.join(', ')}`,
+ draft.messages.length > 0 &&
+ `[Earlier conversation]\n${clip(
+ draft.messages.map((m) => `${m.role}: ${m.content}`).join('\n'),
+ MAX_PROMPT_CHARS,
+ )}`,
+ `[Final request]\n${clip(draft.input, MAX_PROMPT_CHARS)}`,
+ draft.answer && `[Recorded answer]\n${clip(draft.answer, MAX_PROMPT_CHARS)}`,
+ draft.toolsUsed.length > 0 &&
+ `[Tools the recorded answer called]\n${draft.toolsUsed.join(', ')}`,
+ ].filter(Boolean);
+
+ const result = await (runtime as any).generateObject(
+ {
+ messages: [
+ { content: DRAFT_SYSTEM_ROLE, role: 'system' },
+ { content: sections.join('\n\n'), role: 'user' },
+ ],
+ model: judge.model,
+ schema: { name: 'case_rules', schema: RULES_SCHEMA },
+ },
+ { metadata: { trigger: 'eval-judge' } },
+ );
+ const rules = Array.isArray(result?.rules) ? (result.rules as unknown[]) : [];
+ return rules
+ .filter((rule): rule is string => typeof rule === 'string')
+ .map(normalizeRule)
+ .filter(Boolean);
+}
+
+export async function draftCaseFromTopic(
+ deps: EvalRunDeps,
+ topicId: string,
+ options: {
+ /** The benchmark whose Settings judge drafts the rules; the system default without one. */
+ benchmarkId?: string;
+ draftRules?: boolean;
+ } = {},
+): Promise<TopicCaseDraft> {
+ const topic = await deps.topicModel.findById(topicId);
+ if (!topic) throw new Error(TOPIC_NOT_FOUND);
+
+ const rows = [...(await deps.messageModel.query({ topicId }))].sort(
+ (a, b) => new Date(a.createdAt ?? 0).getTime() - new Date(b.createdAt ?? 0).getTime(),
+ );
+ let requestIndex = -1;
+ for (let i = rows.length - 1; i >= 0; i--) {
+ if (rows[i].role === 'user' && text(rows[i].content).trim()) {
+ requestIndex = i;
+ break;
+ }
+ }
+ if (requestIndex < 0) throw new Error(TOPIC_HAS_NO_REQUEST);
+
+ const request = rows[requestIndex];
+ const after = rows.slice(requestIndex + 1);
+ const toolsUsed = [
+ ...new Set(
+ after
+ .filter((row) => row.role === 'tool' && row.plugin?.identifier)
+ .map((row) => row.plugin!.identifier as string),
+ ),
+ ];
+ const answer = after.findLast((row) => row.role === 'assistant' && text(row.content).trim());
+
+ let agent: TopicCaseDraft['agent'];
+ if (topic.agentId) {
+ try {
+ const config = await deps.agentService.getAgentConfigById(topic.agentId);
+ if (config) {
+ agent = {
+ model: config.model ?? undefined,
+ name: (config as { name?: string | null }).name ?? null,
+ plugins: getActivePluginIds(config.plugins as any),
+ provider: config.provider ?? undefined,
+ systemRole: config.systemRole ?? undefined,
+ title: config.title ?? null,
+ };
+ }
+ } catch (error) {
+ // The Agent may be gone; the case can still be saved without its setup.
+ log('case from topic %s: agent %s unavailable: %O', topicId, topic.agentId, error);
+ }
+ }
+
+ const input = text(request.content).trim();
+ const draft: TopicCaseDraft = {
+ agent,
+ answer: answer ? text(answer.content).trim() : undefined,
+ input,
+ messages: rows
+ .slice(0, requestIndex)
+ .filter(
+ (row) => (row.role === 'user' || row.role === 'assistant') && text(row.content).trim(),
+ )
+ .map((row) => ({
+ content: text(row.content),
+ createdAt: row.createdAt ? new Date(row.createdAt).toISOString() : undefined,
+ role: row.role as 'assistant' | 'user',
+ })),
+ rules: [],
+ sessionDate: request.createdAt
+ ? new Date(request.createdAt).toISOString().slice(0, 10)
+ : undefined,
+ title: input.replaceAll(/\s+/g, ' ').slice(0, 80),
+ toolsUsed,
+ };
+
+ if (options.draftRules !== false) {
+ try {
+ const benchmark = options.benchmarkId
+ ? await deps.benchmarkModel.findById(options.benchmarkId)
+ : undefined;
+ draft.rules = await draftRulesWithJudge(deps, draft, benchmark?.metadata);
+ } catch (error) {
+ log('case from topic %s: rule draft failed: %O', topicId, error);
+ draft.rulesError = error instanceof Error ? error.message : String(error);
+ }
+ }
+
+ return draft;
+}
diff --git a/apps/server/src/services/agentEvalRun/caseSelection.ts b/apps/server/src/services/agentEvalRun/caseSelection.ts
new file mode 100644
index 00000000000..b883b37fd6b
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/caseSelection.ts
@@ -0,0 +1,37 @@
+import type { EvalCaseSelection } from '@lobechat/types';
+
+interface SelectableCase {
+ id: string;
+ metadata?: { caseId?: unknown } | null;
+}
+
+/** The id a case is selected by: its dataset-native `metadata.caseId`, else its primary key. */
+export const nativeCaseId = (testCase: SelectableCase) =>
+ typeof testCase.metadata?.caseId === 'string' && testCase.metadata.caseId
+ ? testCase.metadata.caseId
+ : testCase.id;
+
+export const CASE_SELECTION_UNKNOWN_IDS = 'Case selection names cases that are not in the dataset';
+
+/**
+ * The cases a run executes: the whole dataset, or the part its
+ * `config.caseSelection` keeps. A selection that names an unknown case is an
+ * error rather than a silent skip, so a run never waits for a case that does
+ * not exist.
+ */
+export const selectCases = <T extends SelectableCase>(
+ testCases: T[],
+ selection: EvalCaseSelection | null | undefined,
+): T[] => {
+ if (!selection || selection.mode === 'all') return testCases;
+ const ids = new Set(selection.caseIds ?? []);
+ const known = new Set(testCases.map(nativeCaseId));
+ for (const id of ids) {
+ if (!known.has(id)) throw new Error(`${CASE_SELECTION_UNKNOWN_IDS}: ${id}`);
+ }
+ return testCases.filter((testCase) =>
+ selection.mode === 'include'
+ ? ids.has(nativeCaseId(testCase))
+ : !ids.has(nativeCaseId(testCase)),
+ );
+};
diff --git a/apps/server/src/services/agentEvalRun/completion.ts b/apps/server/src/services/agentEvalRun/completion.ts
index 72bae7fa8ed..e952a508cf4 100644
--- a/apps/server/src/services/agentEvalRun/completion.ts
+++ b/apps/server/src/services/agentEvalRun/completion.ts
@@ -1,4 +1,4 @@
-import { evaluate } from '@lobechat/eval-rubric';
+import { evaluate, type EvaluateResult } from '@lobechat/eval-rubric';
import type {
EvalBenchmarkRubric,
EvalRunMetrics,
@@ -6,12 +6,34 @@ import type {
RubricType,
} from '@lobechat/types';
+import { EVAL_HISTORY_TAIL_METADATA_KEY } from './constants';
+import { classifyEmptyAnswer } from './emptyAnswer';
+import {
+ attemptReply,
+ buildEvalModeRubric,
+ buildJudgeEvidence,
+ createJudgeMatchContext,
+ resolveEvalJudge,
+} from './judge';
+import {
+ GRADING_CONTEXT_MISSING,
+ JUDGE_ERROR_STATUS,
+ judgeDiagnostics,
+ judgeFailureMessage,
+ readJudgeError,
+} from './judgeError';
+import { runProgressOf } from './progress';
+import { refillQueuedCases } from './queue';
+import { withSubAgentMessages } from './subAgentEvidence';
+import { snapshotTrialMemory } from './trialMemory';
import type { EvalRunDeps } from './types';
import { roundCost } from './utils';
export async function recordTrajectoryCompletion(
deps: EvalRunDeps,
params: {
+ executionId?: string;
+ topicId?: string;
runId: string;
status?: string;
telemetry: {
@@ -32,10 +54,17 @@ export async function recordTrajectoryCompletion(
// Write runtime telemetry to RunTopic
const runTopic = await deps.runTopicModel.findByRunAndTestCase(runId, testCaseId);
+ if (
+ runTopic &&
+ ((params.topicId && params.topicId !== runTopic.topicId) ||
+ runTopic.evalResult?.executionId !== params.executionId)
+ ) {
+ return { allDone: false, completedCount: 0 };
+ }
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'];
+ const terminalStates = ['passed', 'failed', 'error', 'timeout', 'external', JUDGE_ERROR_STATUS];
if (runTopic.status && terminalStates.includes(runTopic.status)) {
// Fall through to progress tracking below without modifying this topic
} else {
@@ -52,13 +81,13 @@ export async function recordTrajectoryCompletion(
toolCalls: telemetry.toolCalls,
};
- await deps.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {
+ await writeCompletion(deps, runTopic, {
evalResult: evalResultWithTelemetry,
});
if (status === 'error') {
// Short-circuit: execution error β€” skip evaluation, write error directly
- await deps.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {
+ await writeCompletion(deps, runTopic, {
evalResult: {
...evalResultWithTelemetry,
error:
@@ -71,12 +100,30 @@ export async function recordTrajectoryCompletion(
status: 'error',
});
} else {
- // Per-case evaluation: immediately evaluate this case against rubrics
+ // The attempt is over: record what its Memory holds. (An errored
+ // attempt is snapshotted when it completes after a resume.)
+ const memorySnapshot = await snapshotTrialMemory(deps, {
+ runId,
+ testCaseId,
+ topicId: runTopic.topicId,
+ });
+ const evalResult = memorySnapshot
+ ? { ...evalResultWithTelemetry, memorySnapshot }
+ : evalResultWithTelemetry;
+ if (memorySnapshot) {
+ await writeCompletion(deps, runTopic, {
+ evalResult,
+ });
+ }
+
+ // Per-case evaluation: immediately evaluate this case against rubrics.
+ // A judge that throws before `evaluateCase` can record it (judge
+ // resolution, message lookup) is still a judge failure, not a verdict.
try {
- await evaluateCase(deps, runId, { ...runTopic, evalResult: evalResultWithTelemetry });
- } catch (e) {
- // Evaluation failure should not block telemetry or progress tracking
- console.error(e);
+ await evaluateCase(deps, runId, { ...runTopic, evalResult });
+ } catch (error) {
+ console.error(error);
+ await writeTopicJudgeError(deps, runTopic, evalResult, judgeFailureMessage(error));
}
}
}
@@ -84,99 +131,30 @@ export async function recordTrajectoryCompletion(
// Get run to read totalCases
const run = await deps.runModel.findById(runId);
- if (!run) return { allDone: false, completedCount: 0 };
+ if (!run || run.status === 'aborted') 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;
- }
- }
+ const progress = runProgressOf(allTopics);
+ const completedCount = progress.completedCases ?? 0;
// 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,
- },
- });
+ await deps.runModel.updateProgress(
+ runId,
+ { ...(run.metrics as EvalRunMetrics), ...progress },
+ { startedAt: run.startedAt },
+ );
- return { allDone: completedCount >= totalCases, completedCount };
+ const allDone = completedCount >= totalCases;
+ // A case ended: a run with a concurrency limit starts its next waiting case.
+ if (!allDone) await refillQueuedCases(deps, runId, run.config);
+ return { allDone, completedCount };
}
-async function evaluateCase(
+export async function evaluateCase(
deps: EvalRunDeps,
runId: string,
runTopic: {
@@ -190,8 +168,19 @@ async function evaluateCase(
const run = await deps.runModel.findById(runId);
if (!run) return;
+ // The run exists, so its case has a row to report on: a missing dataset or
+ // test case is a grading problem, recorded as such instead of leaving the
+ // case `running` forever.
const dataset = await deps.datasetModel.findById(run.datasetId);
- if (!dataset) return;
+ if (!dataset) {
+ await writeTopicJudgeError(
+ deps,
+ runTopic,
+ runTopic.evalResult,
+ GRADING_CONTEXT_MISSING.dataset,
+ );
+ return;
+ }
const benchmark = dataset.benchmarkId
? await deps.benchmarkModel.findById(dataset.benchmarkId)
@@ -205,20 +194,31 @@ async function evaluateCase(
const assistantMessages = messages.filter((m: { role: string }) => m.role === 'assistant');
const lastAssistantMsg = assistantMessages.at(-1);
- const existingResult = runTopic.evalResult;
+ const existingResult = { ...runTopic.evalResult };
if (!lastAssistantMsg || !lastAssistantMsg.content) {
- await deps.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {
- evalResult: { ...existingResult, error: 'No assistant output', rubricScores: [] },
+ // No final answer: the step cap, or a turn the provider finished with no
+ // text, is the model's failure; anything else stays an error (see classifyEmptyAnswer).
+ const { error, status } = classifyEmptyAnswer({
+ completionReason: existingResult?.completionReason as string | undefined,
+ lastAssistantMessage: lastAssistantMsg,
+ stepCap: run.config?.maxSteps as number | undefined,
+ steps: existingResult?.steps as number | undefined,
+ });
+ await writeCompletion(deps, runTopic, {
+ evalResult: { ...existingResult, error, rubricScores: [] },
passed: false,
score: 0,
- status: 'error',
+ status,
});
return;
}
const testCase = runTopic.testCase;
- if (!testCase) return;
+ if (!testCase) {
+ await writeTopicJudgeError(deps, runTopic, existingResult, GRADING_CONTEXT_MISSING.testCase);
+ return;
+ }
// Resolve rubrics: TestCase evalMode > Dataset evalMode > Benchmark rubrics
const evalMode = (testCase.evalMode ?? dataset.evalMode) as RubricType | null | undefined;
@@ -226,7 +226,7 @@ async function evaluateCase(
// ── External eval mode: agent finished, hand off to external scorer ──
if (evalMode === 'external') {
- await deps.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {
+ await writeCompletion(deps, runTopic, {
evalResult: { ...existingResult, awaitingExternalEval: true },
status: 'external',
});
@@ -235,42 +235,108 @@ async function evaluateCase(
let effectiveRubrics: EvalBenchmarkRubric[];
if (evalMode) {
- effectiveRubrics = [
- {
- config: (evalConfig ?? {}) as unknown as EvalBenchmarkRubric['config'],
- id: `eval-mode-${evalMode}`,
- name: evalMode,
- type: evalMode,
- weight: 1,
- },
- ];
+ effectiveRubrics = [buildEvalModeRubric(evalMode, evalConfig)];
} else {
effectiveRubrics = benchmarkRubrics ?? [];
}
- // No rubrics to evaluate against β€” skip evaluation entirely
- if (effectiveRubrics.length === 0) return;
+ // No rubrics is the judge's call, not a reason to leave the case running:
+ // `evaluate` grades against `expected` with its default rubric, and reports
+ // a judge error when there is nothing to grade against.
- // Run evaluation
- const result = await evaluate(
- { actual: lastAssistantMsg.content, rubrics: effectiveRubrics, testCase: testCase.content },
- { passThreshold },
- );
+ // Run evaluation. A judge that fails (throws, or reports `judgeError`) is
+ // recorded as `judge_error` with its diagnostics; nothing of the attempt is
+ // lost and a re-judge grades the same trajectory again.
+ let result: EvaluateResult;
+ try {
+ const judge = await resolveEvalJudge(deps, {
+ benchmarkMetadata: benchmark?.metadata,
+ evalConfigs: [testCase.evalConfig, dataset.evalConfig],
+ runConfig: run.config,
+ });
+ const topic = await deps.topicModel.findById(runTopic.topicId);
+ const historyTail = topic?.metadata?.[EVAL_HISTORY_TAIL_METADATA_KEY];
+ const historyTailMessageId = typeof historyTail === 'string' ? historyTail : undefined;
+ const evidence = buildJudgeEvidence({
+ historyTailMessageId,
+ memorySnapshot: runTopic.evalResult?.memorySnapshot,
+ messages: await withSubAgentMessages(deps, { messages, topicId: runTopic.topicId }),
+ });
+ const matchContext = createJudgeMatchContext(deps, judge, evidence);
+ existingResult.judges = matchContext.judgeRequests;
+ const actual = attemptReply({ historyTailMessageId, messages }) || lastAssistantMsg.content;
+ result = await evaluate(
+ { actual, rubrics: effectiveRubrics, testCase: testCase.content },
+ { matchContext, passThreshold },
+ );
+ } catch (error) {
+ await writeTopicJudgeError(deps, runTopic, existingResult, judgeFailureMessage(error));
+ return;
+ }
+ const judgeError = readJudgeError(result);
+ if (judgeError) {
+ await writeTopicJudgeError(deps, runTopic, existingResult, judgeError, result);
+ return;
+ }
const evalResult: EvalRunTopicResult = {
...existingResult,
+ // A verdict replaces any earlier judge failure of this attempt.
+ errorPhase: undefined,
+ judgeError: undefined,
rubricScores: result.rubricResults.map((r) => ({
reason: r.reason,
rubricId: r.rubricId,
score: r.score,
+ ...(r.verdicts && { verdicts: r.verdicts }),
})),
};
// Write results to RunTopic
- await deps.runTopicModel.updateByRunAndTopic(runTopic.runId, runTopic.topicId, {
+ await writeCompletion(deps, runTopic, {
evalResult,
passed: result.passed,
score: result.score,
status: result.passed ? 'passed' : 'failed',
});
}
+
+/**
+ * Record that grading this attempt failed. The attempt's own output,
+ * telemetry and Memory snapshot stay in `evalResult`; score and pass flag are
+ * cleared because there is no verdict to report.
+ */
+async function writeTopicJudgeError(
+ deps: EvalRunDeps,
+ runTopic: { runId: string; topicId: string },
+ existingResult: EvalRunTopicResult | null | undefined,
+ judgeError: string,
+ result?: EvaluateResult,
+) {
+ await writeCompletion(deps, runTopic, {
+ evalResult: {
+ ...existingResult,
+ errorPhase: 'judge',
+ judgeError,
+ rubricScores: judgeDiagnostics(result),
+ },
+ passed: null,
+ score: null,
+ status: JUDGE_ERROR_STATUS,
+ });
+}
+
+const writeCompletion = (
+ deps: EvalRunDeps,
+ topic: {
+ runId: string;
+ topicId: string;
+ status?: string | null;
+ evalResult?: EvalRunTopicResult | null;
+ },
+ value: Parameters<EvalRunDeps['runTopicModel']['updateByRunAndTopic']>[2],
+) =>
+ deps.runTopicModel.updateByRunAndTopic(topic.runId, topic.topicId, value, {
+ executionId: topic.evalResult?.executionId,
+ status: topic.status ?? undefined,
+ });
diff --git a/apps/server/src/services/agentEvalRun/connectorBindings.ts b/apps/server/src/services/agentEvalRun/connectorBindings.ts
new file mode 100644
index 00000000000..44413e899d8
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/connectorBindings.ts
@@ -0,0 +1,146 @@
+import type {
+ EvalCaseEnvironment,
+ EvalConnectorBindings,
+ EvalConnectorSnapshots,
+ EvalRunConfig,
+} from '@lobechat/types';
+
+import {
+ AgentEvalConnectorService,
+ EvalConnectorBindingError,
+} from '@/server/services/agentEvalConnector';
+
+import { withResolvedEnvironments } from './caseEnvironment';
+import { selectCases } from './caseSelection';
+import type { EvalRunDeps } from './types';
+
+export const getCaseConnectorBindings = (
+ environment?: EvalCaseEnvironment,
+): EvalConnectorBindings => {
+ const bindings = environment?.connectorBindings ?? {};
+ const required = new Set([
+ ...(environment?.mock?.services ?? []),
+ ...Object.keys(environment?.toolForwarding ?? {}),
+ ]);
+ const missing = [...required].filter((identifier) => !Object.hasOwn(bindings, identifier));
+ if (missing.length) {
+ throw new EvalConnectorBindingError(
+ `Bind these mock services to MCP connections in the Dataset Environment before running: ${missing.join(', ')}.`,
+ );
+ }
+ // A case may narrow its shared Environment's service list without copying bindings.
+ return environment?.mock || environment?.toolForwarding
+ ? Object.fromEntries(
+ Object.entries(bindings).filter(([identifier]) => required.has(identifier)),
+ )
+ : bindings;
+};
+
+export async function snapshotCaseConnectors(
+ deps: EvalRunDeps,
+ datasetId: string,
+ testCases: Array<{ content: { environment?: EvalCaseEnvironment }; id: string }>,
+) {
+ const snapshots: Record<string, EvalConnectorSnapshots> = {};
+ const service = new AgentEvalConnectorService(deps.db, deps.userId, datasetId, deps.workspaceId);
+ const casesWithBindings = testCases
+ .map((testCase) => ({
+ bindings: getCaseConnectorBindings(testCase.content.environment),
+ contracts: testCase.content.environment?.toolManifests,
+ id: testCase.id,
+ }))
+ .filter(({ bindings }) => Object.keys(bindings).length > 0);
+ for (const { bindings, contracts } of casesWithBindings) {
+ if (Object.keys(bindings).some((id) => !contracts?.[id])) {
+ throw new EvalConnectorBindingError(
+ 'Add the original tool contracts to the Dataset Environment before running.',
+ );
+ }
+ }
+ await service.checkBindingGroups(
+ casesWithBindings.map(({ bindings }) => bindings),
+ casesWithBindings.map(({ contracts }) => contracts),
+ );
+ const resolved = new Map<string, Promise<{ snapshots: EvalConnectorSnapshots }>>();
+ for (const { bindings, contracts, id } of casesWithBindings) {
+ const cacheKey = JSON.stringify([
+ Object.entries(bindings).sort(([a], [b]) => a.localeCompare(b)),
+ contracts,
+ ]);
+ let resolution = resolved.get(cacheKey);
+ if (!resolution) {
+ resolution = service.resolveBindings(bindings, undefined, contracts);
+ resolved.set(cacheKey, resolution);
+ }
+ snapshots[id] = (await resolution).snapshots;
+ }
+ return Object.keys(snapshots).length ? snapshots : undefined;
+}
+
+/** Validate the immutable target before changing evidence or starting a new attempt. */
+export async function assertCaseConnectorBindings(
+ deps: EvalRunDeps,
+ datasetId: string | undefined,
+ environment: EvalCaseEnvironment | undefined,
+ expected: EvalConnectorSnapshots | undefined,
+ checkConnection = false,
+) {
+ const bindings = getCaseConnectorBindings(environment);
+ if (!Object.keys(bindings).length && !Object.keys(expected ?? {}).length) return;
+ if (!expected || !datasetId) {
+ throw new EvalConnectorBindingError(
+ 'This run has no frozen mock connection bindings. Configure its Environment and create a new experiment.',
+ );
+ }
+ const service = new AgentEvalConnectorService(deps.db, deps.userId, datasetId, deps.workspaceId);
+ await service.resolveBindings(bindings, expected, environment?.toolManifests);
+ if (checkConnection) {
+ await service.checkBindings(bindings);
+ await service.resolveBindings(bindings, expected, environment?.toolManifests);
+ }
+}
+
+export async function assertRunConnectorBindings(
+ deps: EvalRunDeps,
+ run: { config?: EvalRunConfig | null; datasetId: string },
+ caseIds?: string[],
+) {
+ const allCases = await deps.testCaseModel.findByDatasetId(run.datasetId);
+ const selected = caseIds
+ ? allCases.filter((testCase) => caseIds.includes(testCase.id))
+ : run.config?.executionMode === 'external'
+ ? allCases
+ : selectCases(allCases, run.config?.caseSelection);
+ const testCases = await withResolvedEnvironments(deps, selected);
+ const checked = new Set<string>();
+ const checks: Array<{
+ bindings: EvalConnectorBindings;
+ environment: EvalCaseEnvironment | undefined;
+ expected: EvalConnectorSnapshots | undefined;
+ }> = [];
+ for (const testCase of testCases) {
+ const environment = testCase.content.environment;
+ const expected = run.config?.connectorSnapshots?.[testCase.id];
+ const bindings = getCaseConnectorBindings(environment);
+ const key = JSON.stringify([bindings, expected]);
+ if (checked.has(key)) continue;
+ checked.add(key);
+ await assertCaseConnectorBindings(deps, run.datasetId, environment, expected);
+ checks.push({ bindings, environment, expected });
+ }
+ const service = new AgentEvalConnectorService(
+ deps.db,
+ deps.userId,
+ run.datasetId,
+ deps.workspaceId,
+ );
+ await service.checkBindingGroups(
+ checks.map(({ bindings }) => bindings),
+ checks.map(({ environment }) => environment?.toolManifests),
+ );
+ // Discovery can change tool schemas. Every original alias and frozen contract
+ // must still match after synchronization, even when its probe was shared.
+ for (const { environment, expected } of checks) {
+ await assertCaseConnectorBindings(deps, run.datasetId, environment, expected);
+ }
+}
diff --git a/apps/server/src/services/agentEvalRun/constants.ts b/apps/server/src/services/agentEvalRun/constants.ts
index a6fa23038e7..c9a4d2ce2b6 100644
--- a/apps/server/src/services/agentEvalRun/constants.ts
+++ b/apps/server/src/services/agentEvalRun/constants.ts
@@ -3,3 +3,8 @@ 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;
+/** Cap on concurrent workflow triggers while starting the claimed cases of one dispatch. */
+export const QUEUED_TRIGGER_CONCURRENCY = 5;
+
+/** Evaluation infrastructure cannot be replaced by a mock connection. */
+export const EVAL_INFRASTRUCTURE_TOOLS = ['lobe-activator', 'lobe-agent', 'lobe-user-memory'];
diff --git a/apps/server/src/services/agentEvalRun/createRun.ts b/apps/server/src/services/agentEvalRun/createRun.ts
index ac8f5d94fb8..70ec5bc24c1 100644
--- a/apps/server/src/services/agentEvalRun/createRun.ts
+++ b/apps/server/src/services/agentEvalRun/createRun.ts
@@ -1,23 +1,33 @@
import { idGenerator } from '@lobechat/database';
import type {
+ EvalCaseEnvironment,
EvalRunAgentSnapshot,
+ EvalRunConfig,
EvalRunInputConfig,
ImportedMessage,
ToolIntervention,
} from '@lobechat/types';
-import { getActivePluginIds } from '@lobechat/types';
+import { evalCaseVersionOf, 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 type { CaseAgentRun } from './caseAgent';
+import { ensureCaseAgents, loadCaseAgentBase } from './caseAgent';
+import { withResolvedEnvironments } from './caseEnvironment';
+import { selectCases } from './caseSelection';
+import { snapshotCaseConnectors } from './connectorBindings';
import { EVAL_HISTORY_TAIL_METADATA_KEY } from './constants';
+import { createEvalRunDeps } from './deps';
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';
+export const RUN_DATASET_NOT_FOUND = 'Dataset not found';
+export const RUN_EMPTY_SELECTION = 'Select at least one test case';
/** Stable JSON stringify: sorts object keys recursively, drops undefined. */
const stableStringify = (value: unknown): string => {
@@ -75,7 +85,14 @@ export async function createRun(
targetAgentId = parent.targetAgentId ?? undefined;
datasetId = parent.datasetId;
- inputConfig = (parent.config as EvalRunInputConfig | undefined) ?? undefined;
+ const {
+ connectorSnapshots: _parentBindings,
+ agentSnapshot: _parentAgent,
+ caseVersion: _parentVersion,
+ executionMode: _parentMode,
+ ...parentInput
+ } = parent.config ?? {};
+ inputConfig = parentInput;
}
// External execution is driven case-by-case through `runExecuteCase`, which
@@ -98,13 +115,23 @@ export async function createRun(
// 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 };
+ // The version of the cases the run is made on: a leaderboard counts only runs on
+ // the dataset's current version, since cases are edited in place.
+ const datasetRow = await deps.datasetModel.findById(datasetId);
+ if (!datasetRow) throw new Error(RUN_DATASET_NOT_FOUND);
+ const caseVersion = evalCaseVersionOf(datasetRow.metadata);
+ const config: EvalRunConfig = {
+ ...inputConfig,
+ agentSnapshot,
+ ...(caseVersion && { caseVersion }),
+ 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).
+ // β€” the agent snapshot and case version are excluded since they are
+ // captured server-side on every create).
const matchesExisting = (existing: {
config?: unknown;
datasetId: string;
@@ -114,6 +141,8 @@ export async function createRun(
}) => {
const {
agentSnapshot: _existingSnapshot,
+ connectorSnapshots: _existingBindings,
+ caseVersion: _existingCaseVersion,
executionMode: existingMode,
...existingConfig
} = (existing.config ?? {}) as Record<string, unknown>;
@@ -135,16 +164,37 @@ export async function createRun(
}
}
+ // The run's cases: the dataset, narrowed by `config.caseSelection` when an
+ // internal run picks some of them (an external worker applies the selection
+ // itself). Their mock connectors must be installed in this account before
+ // any of their Agents exists; checked before the run row so a missing or
+ // unreachable mock leaves no run behind.
+ const datasetCases = await withResolvedEnvironments(
+ deps,
+ await deps.testCaseModel.findByDatasetId(datasetId),
+ );
+ const testCases = isExternal ? datasetCases : selectCases(datasetCases, config?.caseSelection);
+ if (!isExternal && testCases.length === 0) throw new Error(RUN_EMPTY_SELECTION);
+ config.connectorSnapshots = await snapshotCaseConnectors(deps, datasetId, testCases);
+
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',
+ // An idempotent retry must only see a run once all its case setup exists.
+ // Keep every model used by that setup on the same transaction connection.
+ return await deps.db.transaction(async (tx) => {
+ const txDeps = createEvalRunDeps(tx, deps.userId, deps.workspaceId);
+ const run = await txDeps.runModel.create({
+ ...restParams,
+ datasetId,
+ targetAgentId,
+ config,
+ // External runs start claimable; internal runs wait for `startRun`.
+ status: isExternal ? 'pending' : 'idle',
+ });
+
+ if (!isExternal) await createRunTopics(txDeps, run, testCases);
+ if (params.experimentId) await txDeps.experimentModel.touch(params.experimentId);
+ return run;
});
} catch (error) {
// Race-safe idempotency: a concurrent create with the same caller id won
@@ -160,35 +210,29 @@ export async function createRun(
}
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(
+/**
+ * Creates each case's topic, restored history and pending RunTopic. The topic
+ * belongs to the Agent the case runs on: its hidden case Agent when the case
+ * brings its own setup or the run picks a model, otherwise the target Agent.
+ */
+export async function createRunTopics(
deps: EvalRunDeps,
- runId: string,
- targetAgentId: string | null | undefined,
- testCases: Array<{
- content: { input: string; messages?: ImportedMessage[] };
+ run: CaseAgentRun,
+ rawTestCases: Array<{
+ content: { environment?: EvalCaseEnvironment; input: string; messages?: ImportedMessage[] };
+ environmentId?: string | null;
id: string;
sortOrder: number | null;
}>,
) {
+ const runId = run.id;
+ const testCases = await withResolvedEnvironments(deps, rawTestCases);
+ const caseAgentBase = await loadCaseAgentBase(deps, run, testCases);
+
return deps.db.transaction(async (tx) => {
+ const agentIds = await ensureCaseAgents(tx, deps, run, testCases, caseAgentBase);
const preparedCases = testCases.map((testCase) => ({
testCase,
topicId: idGenerator('topics'),
@@ -196,7 +240,7 @@ export function createRunTopics(
await tx.insert(topics).values(
preparedCases.map(({ testCase, topicId }) => ({
- agentId: targetAgentId ?? null,
+ agentId: agentIds.get(testCase.id) ?? null,
id: topicId,
title: `[${(testCase.sortOrder ?? 0) + 1}] ${testCase.content.input.slice(0, 50) || 'Topic'}...`,
trigger: 'eval' as const,
@@ -247,7 +291,7 @@ export function createRunTopics(
};
});
- const messageRows = preparedMessages.map(({ createdAt, id, message, updatedAt }, index) => ({
+ const messageRows = preparedMessages.map(({ createdAt, id, message, updatedAt }) => ({
agentId: null,
content: message.content,
createdAt: new Date(createdAt),
@@ -341,6 +385,7 @@ export function createRunTopics(
await tx.insert(agentEvalRunTopics).values(
preparedCases.map(({ testCase, topicId }) => ({
+ evalResult: { executionId: crypto.randomUUID() },
runId,
status: 'pending' as const,
testCaseId: testCase.id,
diff --git a/apps/server/src/services/agentEvalRun/deps.ts b/apps/server/src/services/agentEvalRun/deps.ts
index c54074343ce..94f22b6ea5f 100644
--- a/apps/server/src/services/agentEvalRun/deps.ts
+++ b/apps/server/src/services/agentEvalRun/deps.ts
@@ -3,6 +3,7 @@ import type { LobeChatDatabase } from '@lobechat/database';
import {
AgentEvalBenchmarkModel,
AgentEvalDatasetModel,
+ AgentEvalEnvironmentModel,
AgentEvalExperimentModel,
AgentEvalRunModel,
AgentEvalRunTopicModel,
@@ -11,6 +12,7 @@ import {
import { MessageModel } from '@/database/models/message';
import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
+import { AgentEvalExecutionRepo } from '@/database/repositories/agentEvalExecution';
import { AgentService } from '@/server/services/agent';
import type { EvalRunDeps } from './types';
@@ -29,6 +31,7 @@ export const createEvalRunDeps = (
const runModel = new AgentEvalRunModel(db, userId, workspaceId);
const benchmarkModel = new AgentEvalBenchmarkModel(db, userId, workspaceId);
const datasetModel = new AgentEvalDatasetModel(db, userId, workspaceId);
+ const environmentModel = new AgentEvalEnvironmentModel(db, userId, workspaceId);
const experimentModel = new AgentEvalExperimentModel(db, userId, workspaceId);
const runTopicModel = new AgentEvalRunTopicModel(db, userId, workspaceId);
const testCaseModel = new AgentEvalTestCaseModel(db, userId, workspaceId);
@@ -42,7 +45,9 @@ export const createEvalRunDeps = (
benchmarkModel,
datasetModel,
db,
+ environmentModel,
experimentModel,
+ executionRepo: new AgentEvalExecutionRepo(db, userId, workspaceId),
messageModel,
runModel,
runTopicModel,
diff --git a/apps/server/src/services/agentEvalRun/emptyAnswer.ts b/apps/server/src/services/agentEvalRun/emptyAnswer.ts
new file mode 100644
index 00000000000..7b31555a5a5
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/emptyAnswer.ts
@@ -0,0 +1,54 @@
+/** Error text of an attempt the model ended without saying anything. */
+export const ENDED_WITHOUT_ANSWER = 'Ended without a final answer';
+
+/** Error text of an attempt with no usable assistant turn: it never got an answer from the provider. */
+export const NO_ASSISTANT_OUTPUT = 'No assistant output';
+
+/**
+ * An attempt graded before an empty answer from a normally finished turn
+ * counted as a failure: grading it again applies the current reading
+ * (`classifyEmptyAnswer`), which keeps a real provider error an error.
+ */
+export const isRegradableEmptyAnswer = (attempt?: { error?: unknown; status?: unknown } | null) =>
+ attempt?.status === 'error' && attempt.error === NO_ASSISTANT_OUTPUT;
+
+/** Completion reasons that mean the execution itself broke, not that the model stopped. */
+const BROKEN_COMPLETIONS = new Set(['aborted', 'error', 'interrupted']);
+
+/**
+ * How an attempt whose last assistant message has no text is graded.
+ *
+ * - It ran into its step cap: the model kept calling tools instead of
+ * answering, a failure.
+ * - The provider finished the turn normally (the message carries no error and
+ * the execution was not broken) but the model left no text, for example a
+ * tool call it announced and never sent: the model's outcome, a failure. A
+ * rerun meets the same model and usually the same result, so it is not held
+ * back as unverified.
+ * - Otherwise (no assistant message, a provider error on it, a broken
+ * execution) it stays an infrastructure error.
+ */
+export const classifyEmptyAnswer = ({
+ completionReason,
+ lastAssistantMessage,
+ stepCap,
+ steps,
+}: {
+ completionReason?: string;
+ lastAssistantMessage?: { error?: unknown } | null;
+ stepCap?: number;
+ steps?: number;
+}): { error: string; status: 'error' | 'failed' } => {
+ if (stepCap && (steps ?? 0) >= stepCap)
+ return {
+ error: `Reached the step limit (${stepCap}) without a final answer`,
+ status: 'failed',
+ };
+ if (
+ lastAssistantMessage &&
+ !lastAssistantMessage.error &&
+ !BROKEN_COMPLETIONS.has(completionReason ?? '')
+ )
+ return { error: ENDED_WITHOUT_ANSWER, status: 'failed' };
+ return { error: NO_ASSISTANT_OUTPUT, status: 'error' };
+};
diff --git a/apps/server/src/services/agentEvalRun/evalMemory.schema.ts b/apps/server/src/services/agentEvalRun/evalMemory.schema.ts
new file mode 100644
index 00000000000..b209882f07a
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/evalMemory.schema.ts
@@ -0,0 +1,75 @@
+import {
+ ActivityMemoryItemSchema,
+ AddIdentityActionSchema,
+ ContextMemoryItemSchema,
+ ExperienceMemoryItemSchema,
+ PreferenceMemoryItemSchema,
+} from '@lobechat/memory-user-memory/schemas';
+import type { EvalMemoryFixture } from '@lobechat/types';
+import { z } from 'zod';
+
+const nativeEvalMemoryFixtureSchema = z
+ .object({
+ activities: z.array(ActivityMemoryItemSchema.strict()).max(50).optional(),
+ contexts: z.array(ContextMemoryItemSchema.strict()).max(50).optional(),
+ experiences: z.array(ExperienceMemoryItemSchema.strict()).max(50).optional(),
+ identities: z.array(AddIdentityActionSchema).max(50).optional(),
+ persona: z
+ .object({ narrative: z.string().max(50_000), tagline: z.string().max(2000).optional() })
+ .strict()
+ .optional(),
+ preferences: z.array(PreferenceMemoryItemSchema.strict()).max(50).optional(),
+ seededAt: z.string().datetime({ offset: true }).optional(),
+ })
+ .strict()
+ .superRefine((fixture, ctx) => {
+ const count = Object.values(fixture).reduce(
+ (total, value) => total + (Array.isArray(value) ? value.length : 0),
+ 0,
+ );
+ if (count > 50 || JSON.stringify(fixture).length > 200_000) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'Memory fixture exceeds 50 entries or 200000 characters',
+ });
+ }
+ // Account message references cannot be rebound to a new namespace.
+ const checkSources = (value: unknown, path: (string | number)[]) => {
+ if (Array.isArray(value)) {
+ value.forEach((item, index) => checkSources(item, [...path, index]));
+ } else if (value && typeof value === 'object') {
+ for (const [key, item] of Object.entries(value)) {
+ if (
+ (key === 'sourceId' || key === 'sourceIds') &&
+ item != null &&
+ (Array.isArray(item) ? item.length > 0 : item !== '')
+ ) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'Memory fixtures cannot reference account source messages',
+ path: [...path, key],
+ });
+ }
+ checkSources(item, [...path, key]);
+ }
+ }
+ };
+ checkSources(fixture, []);
+ });
+
+/**
+ * Keep the shared transport type independent of the Memory schema package
+ * (which itself imports @lobechat/types), and validate every nested native
+ * input here. The transform's output is the precise native schema type used
+ * by the seed service; invalid transport input never reaches execution.
+ */
+export const evalMemoryFixtureSchema = z.custom<EvalMemoryFixture>().transform((fixture, ctx) => {
+ const result = nativeEvalMemoryFixtureSchema.safeParse(fixture);
+ if (!result.success) {
+ for (const issue of result.error.issues) {
+ ctx.addIssue({ code: 'custom', message: issue.message, path: issue.path });
+ }
+ return z.NEVER;
+ }
+ return result.data;
+});
diff --git a/apps/server/src/services/agentEvalRun/index.surface.test.ts b/apps/server/src/services/agentEvalRun/index.surface.test.ts
index 6e1ad131578..ebb2bf3a330 100644
--- a/apps/server/src/services/agentEvalRun/index.surface.test.ts
+++ b/apps/server/src/services/agentEvalRun/index.surface.test.ts
@@ -28,6 +28,7 @@ describe('agent eval run service public surface', () => {
'claimRun',
'createRun',
'deleteRun',
+ 'dispatchQueuedCases',
'executeMultiThreadTrajectory',
'executeResumedThreadTrajectory',
'executeResumedTrajectory',
@@ -40,6 +41,7 @@ describe('agent eval run service public surface', () => {
'loadTrajectoryData',
'recordThreadCompletion',
'recordTrajectoryCompletion',
+ 'rerunUnverifiedCases',
'resumeTrajectory',
'retryErrorCases',
'retrySingleCase',
diff --git a/apps/server/src/services/agentEvalRun/index.ts b/apps/server/src/services/agentEvalRun/index.ts
index 4efcb892704..5105fcf4657 100644
--- a/apps/server/src/services/agentEvalRun/index.ts
+++ b/apps/server/src/services/agentEvalRun/index.ts
@@ -4,8 +4,12 @@ import type { AgentEvalRunModel } from '@/database/models/agentEval';
import { evaluateAndFinalizeRun } from './aggregate';
import { recordTrajectoryCompletion } from './completion';
+import { assertRunConnectorBindings } from './connectorBindings';
import { createRun } from './createRun';
import { createEvalRunDeps } from './deps';
+import { dispatchQueuedCases } from './queue';
+import { rejudgeRun } from './rejudge';
+import { rerunUnverifiedCases } from './rerun';
import { executeResumedThreadTrajectory, executeResumedTrajectory } from './resumeExecution';
import { canResumeTrajectory, getResumableCases, resumeTrajectory } from './resumeTarget';
import {
@@ -45,6 +49,10 @@ export class AgentEvalRunService {
this.runModel = this.deps.runModel;
}
+ assertConnectorBindings(...args: StageArgs<typeof assertRunConnectorBindings>) {
+ return assertRunConnectorBindings(this.deps, ...args);
+ }
+
createRun(...args: StageArgs<typeof createRun>) {
return createRun(this.deps, ...args);
}
@@ -53,6 +61,10 @@ export class AgentEvalRunService {
return deleteRun(this.deps, ...args);
}
+ dispatchQueuedCases(...args: StageArgs<typeof dispatchQueuedCases>) {
+ return dispatchQueuedCases(this.deps, ...args);
+ }
+
abortRun(...args: StageArgs<typeof abortRun>) {
return abortRun(this.deps, ...args);
}
@@ -65,6 +77,18 @@ export class AgentEvalRunService {
return retrySingleCase(this.deps, ...args);
}
+ rerunUnverifiedCases(...args: StageArgs<typeof rerunUnverifiedCases>) {
+ return rerunUnverifiedCases(this.deps, ...args);
+ }
+
+ /**
+ * Grade a finished run again with the current judge setup, reusing its
+ * recorded trajectories (no model runs again).
+ */
+ rejudgeRun(...args: StageArgs<typeof rejudgeRun>) {
+ return rejudgeRun(this.deps, ...args);
+ }
+
canResumeTrajectory(...args: StageArgs<typeof canResumeTrajectory>) {
return canResumeTrajectory(this.deps, ...args);
}
diff --git a/apps/server/src/services/agentEvalRun/judge.ts b/apps/server/src/services/agentEvalRun/judge.ts
new file mode 100644
index 00000000000..7c98cc04920
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/judge.ts
@@ -0,0 +1,292 @@
+import type { MatchContext } from '@lobechat/eval-rubric';
+import type {
+ EvalBenchmarkRubric,
+ EvalConfig,
+ EvalMemorySnapshot,
+ EvalRunConfig,
+ RubricType,
+ UserSystemAgentConfig,
+} from '@lobechat/types';
+
+import { UserModel } from '@/database/models/user';
+import { initModelRuntimeForRequest } from '@/server/modules/AgentRuntime/llmRelay/oneShot';
+
+import { resolveSystemAgentModelConfig } from '../systemAgent/modelConfig';
+import type { EvalRunDeps } from './types';
+
+/**
+ * LLM judge for eval grading.
+ *
+ * `llm-rubric` (and the other LLM matchers) only score when `evaluate()` gets a
+ * `matchContext`; without one every case scored 0 with "LLM judge not
+ * available". An explicit run judge overrides inherited case, dataset and
+ * benchmark defaults, including model/provider settings inside a rubric.
+ * Without an override, the case, dataset, benchmark and user defaults apply.
+ */
+
+export interface EvalJudge {
+ model: string;
+ /** An explicit run choice must also override the matcher's payload. */
+ override?: boolean;
+ provider: string;
+}
+
+/** `agent_eval_benchmarks.metadata.judge`: the benchmark's default judge model. */
+const benchmarkJudge = (metadata?: Record<string, unknown> | null): Partial<EvalJudge> => {
+ const judge = metadata?.judge;
+ if (!judge || typeof judge !== 'object') return {};
+ const { model, provider } = judge as Partial<EvalJudge>;
+ return typeof model === 'string' && typeof provider === 'string' ? { model, provider } : {};
+};
+
+export const resolveEvalJudge = async (
+ deps: EvalRunDeps,
+ params: {
+ /** The benchmark's metadata; its `judge` is the default between the eval configs and the run. */
+ benchmarkMetadata?: Record<string, unknown> | null;
+ evalConfigs?: (EvalConfig | null | undefined)[];
+ runConfig?: EvalRunConfig | null;
+ },
+): Promise<EvalJudge> => {
+ if (params.runConfig?.judgeModel && params.runConfig.judgeProvider) {
+ return {
+ model: params.runConfig.judgeModel,
+ override: true,
+ provider: params.runConfig.judgeProvider,
+ };
+ }
+ const configured = params.evalConfigs?.find((config) => config?.model && config?.provider);
+ const fromBenchmark = benchmarkJudge(params.benchmarkMetadata);
+ const override = {
+ model: (configured?.model as string | undefined) || fromBenchmark.model,
+ provider: (configured?.provider as string | undefined) || fromBenchmark.provider,
+ };
+ if (override.model && override.provider) {
+ return resolveSystemAgentModelConfig({ override, taskKey: 'topic' });
+ }
+
+ const settings = await new UserModel(deps.db, deps.userId).getUserSettings();
+ const systemAgent = settings?.systemAgent as Partial<UserSystemAgentConfig> | undefined;
+ return resolveSystemAgentModelConfig({
+ override,
+ taskConfig: systemAgent?.topic,
+ taskKey: 'topic',
+ });
+};
+
+/**
+ * Evidence limits. The judge's context also has to hold the rules, the input
+ * and the reply, so the evidence text is capped: each tool result up to
+ * `MAX_RESULT_CHARS`, shrinking towards `MIN_RESULT_CHARS` when an attempt
+ * made many calls, so the whole section stays under `EVIDENCE_BUDGET_CHARS`
+ * (about 40k tokens). Whatever is cut is marked, so the judge knows a detail
+ * may sit in the part it cannot see instead of calling it absent.
+ */
+const EVIDENCE_BUDGET_CHARS = 160_000;
+const MAX_EVIDENCE_TOOL_CALLS = 150;
+const MAX_ARGS_CHARS = 2000;
+const MAX_RESULT_CHARS = 6000;
+const MIN_RESULT_CHARS = 600;
+const MAX_ERROR_CHARS = 1000;
+const MAX_EVIDENCE_MEMORIES = 60;
+const MAX_MEMORY_TEXT_CHARS = 600;
+
+const clip = (value: unknown, max: number) => {
+ const text = typeof value === 'string' ? value : JSON.stringify(value ?? '');
+ if (text.length <= max) return text;
+ return `${text.slice(0, max)}… [${text.length - max} more characters not shown]`;
+};
+
+interface EvidenceMessage {
+ content?: string | null;
+ id: string;
+ plugin?: { apiName?: string; arguments?: string; identifier?: string } | null;
+ pluginError?: unknown;
+ role: string;
+ /** Set when a sub-agent of the attempt made the call (see `withSubAgentMessages`). */
+ via?: string;
+}
+
+/**
+ * The reply the judge grades: every assistant message of this attempt that has
+ * text, in order. An agent may answer, make one more call (save a preference)
+ * and close with a one-line confirmation; grading only that last line misses
+ * the answer the user read. Messages restored from the case's prior history
+ * are left out, as in the evidence.
+ */
+export const attemptReply = (params: {
+ historyTailMessageId?: string;
+ messages: Array<{ content?: string | null; id: string; role: string }>;
+}): string => {
+ const { historyTailMessageId, messages } = params;
+ const tailIndex = historyTailMessageId
+ ? messages.findIndex((message) => message.id === historyTailMessageId)
+ : -1;
+ return (tailIndex >= 0 ? messages.slice(tailIndex + 1) : messages)
+ .filter((message) => message.role === 'assistant' && message.content?.trim())
+ .map((message) => message.content!.trim())
+ .join('\n\n');
+};
+
+const textLength = (value: unknown) =>
+ (typeof value === 'string' ? value : JSON.stringify(value ?? '')).length;
+
+/**
+ * The evidence budget the capped calls leave unused, given to the longest cut
+ * arguments first. Those are usually what the agent wrote (a document, a report
+ * artifact), and a rule about their body cannot be checked from the first
+ * `MAX_ARGS_CHARS` characters, which are often only the stylesheet.
+ */
+const longArgumentAllowance = (calls: EvidenceMessage[], resultChars: number) => {
+ let spare =
+ EVIDENCE_BUDGET_CHARS -
+ calls.reduce(
+ (sum, message) =>
+ sum +
+ Math.min(textLength(message.plugin?.arguments), MAX_ARGS_CHARS) +
+ Math.min(textLength(message.pluginError ?? message.content), resultChars),
+ 0,
+ );
+ const allowance = new Map<EvidenceMessage, number>();
+ const cut = calls
+ .filter((message) => textLength(message.plugin?.arguments) > MAX_ARGS_CHARS)
+ .sort((a, b) => textLength(b.plugin?.arguments) - textLength(a.plugin?.arguments));
+ for (const message of cut) {
+ if (spare <= 0) break;
+ const extra = Math.min(textLength(message.plugin?.arguments) - MAX_ARGS_CHARS, spare);
+ allowance.set(message, MAX_ARGS_CHARS + extra);
+ spare -= extra;
+ }
+ return allowance;
+};
+
+/**
+ * What the judge needs beyond the final reply to grade criteria about actions:
+ * this attempt's tool calls with their results, and the Memory the attempt
+ * left behind. Messages restored from the case's prior history are left out,
+ * so the judge only sees what the agent did in this attempt.
+ */
+export const buildJudgeEvidence = (params: {
+ historyTailMessageId?: string;
+ memorySnapshot?: EvalMemorySnapshot;
+ messages: EvidenceMessage[];
+}): string => {
+ const { historyTailMessageId, memorySnapshot, messages } = params;
+ const tailIndex = historyTailMessageId
+ ? messages.findIndex((message) => message.id === historyTailMessageId)
+ : -1;
+ const attempt = tailIndex >= 0 ? messages.slice(tailIndex + 1) : messages;
+
+ const toolCalls = attempt.filter((message) => message.role === 'tool' && message.plugin);
+ const shown = toolCalls.slice(0, MAX_EVIDENCE_TOOL_CALLS);
+ const resultChars = Math.max(
+ MIN_RESULT_CHARS,
+ Math.min(
+ MAX_RESULT_CHARS,
+ Math.floor(EVIDENCE_BUDGET_CHARS / Math.max(1, shown.length)) - MAX_ARGS_CHARS,
+ ),
+ );
+ const argsChars = longArgumentAllowance(shown, resultChars);
+ const sections = [
+ toolCalls.length === 0
+ ? 'Tool calls: none.'
+ : [
+ toolCalls.some((message) => message.via)
+ ? `Tool calls, in order (${toolCalls.length}); a call marked [sub-agent: …] was made by a sub-agent the agent started, as part of this attempt:`
+ : `Tool calls, in order (${toolCalls.length}):`,
+ ...shown.map((message, index) => {
+ const { apiName, arguments: args, identifier } = message.plugin!;
+ const outcome = message.pluginError
+ ? `error: ${clip(message.pluginError, MAX_ERROR_CHARS)}`
+ : clip(message.content, resultChars);
+ const via = message.via ? `[sub-agent: ${clip(message.via, 80)}] ` : '';
+ return `${index + 1}. ${via}${identifier}.${apiName}(${clip(args, argsChars.get(message) ?? MAX_ARGS_CHARS)}) -> ${outcome}`;
+ }),
+ ...(toolCalls.length > shown.length
+ ? [`… ${toolCalls.length - shown.length} more tool calls not shown.`]
+ : []),
+ ].join('\n'),
+ ];
+
+ if (memorySnapshot) {
+ const rows = memorySnapshot.entries ?? [];
+ sections.push(
+ [
+ `Memory at the end of the attempt (${rows.length} entries; "fixture" ones existed before it started, "agent" ones were written during it):`,
+ ...rows.slice(0, MAX_EVIDENCE_MEMORIES).map((row) => {
+ const captured = row.capturedAt ? row.capturedAt.slice(0, 10) : '';
+ const removed = row.removedReason ? ', removed' : '';
+ return `- [${row.layer}, ${row.source}${captured ? `, ${captured}` : ''}${removed}] ${clip(row.title ?? '', 120)}: ${clip(row.summary ?? row.details ?? '', MAX_MEMORY_TEXT_CHARS)}`;
+ }),
+ ...(rows.length > MAX_EVIDENCE_MEMORIES
+ ? [`… ${rows.length - MAX_EVIDENCE_MEMORIES} more entries not shown.`]
+ : []),
+ ].join('\n'),
+ );
+ }
+
+ return sections.join('\n\n');
+};
+
+/** Builds the judge context; the model runtime starts on the first LLM rubric only. */
+export const createJudgeMatchContext = (
+ deps: EvalRunDeps,
+ judge: EvalJudge,
+ evidence?: string,
+): MatchContext & { judgeRequests: Array<{ model: string; provider: string }> } => {
+ const runtimes = new Map<string, ReturnType<typeof initModelRuntimeForRequest>>();
+ const judgeRequests: Array<{ model: string; provider: string }> = [];
+
+ return {
+ generateObject: async (payload) => {
+ const model = judge.override ? judge.model : payload.model || judge.model;
+ const provider = judge.override ? judge.provider : payload.provider || judge.provider;
+ if (
+ !judgeRequests.some((request) => request.model === model && request.provider === provider)
+ ) {
+ judgeRequests.push({ model, provider });
+ }
+ let runtime = runtimes.get(provider);
+ if (!runtime) {
+ runtime = initModelRuntimeForRequest(deps.db, deps.userId, provider, {
+ workspaceId: deps.workspaceId,
+ });
+ runtimes.set(provider, runtime);
+ }
+ return ((await runtime) as any).generateObject(
+ {
+ messages: payload.messages as any[],
+ model,
+ schema: { name: 'judge_score', schema: payload.schema },
+ },
+ { metadata: { trigger: 'eval-judge' } },
+ );
+ },
+ judgeEvidence: evidence,
+ judgeModel: judge.model,
+ judgeRequests,
+ };
+};
+
+/**
+ * The rubric an `evalMode` grades with. The eval UI stores the judge
+ * instructions as `judgePrompt`, while the LLM matchers read `criteria`, so
+ * the prompt users wrote was never used; map it across.
+ */
+export const buildEvalModeRubric = (
+ evalMode: RubricType,
+ evalConfig?: EvalConfig | null,
+): EvalBenchmarkRubric => {
+ const config = { ...evalConfig } as Record<string, unknown>;
+ if (!config.criteria && typeof config.judgePrompt === 'string') {
+ config.criteria = config.judgePrompt;
+ }
+
+ return {
+ config: config as unknown as EvalBenchmarkRubric['config'],
+ id: `eval-mode-${evalMode}`,
+ name: evalMode,
+ type: evalMode,
+ weight: 1,
+ };
+};
diff --git a/apps/server/src/services/agentEvalRun/judgeError.ts b/apps/server/src/services/agentEvalRun/judgeError.ts
new file mode 100644
index 00000000000..f28485b68d3
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/judgeError.ts
@@ -0,0 +1,54 @@
+import type { EvaluateResult } from '@lobechat/eval-rubric';
+import type { EvalRubricScore } from '@lobechat/types';
+
+/**
+ * A judge failure is not a verdict. When the judge model, its configuration
+ * or its answer parsing fails, the attempt keeps everything it produced
+ * (reply, tool calls, Memory snapshot, cost) and takes this status instead of
+ * `failed`: no score, no pass flag, counted apart in the metrics, and the only
+ * way out is a re-judge of the same trajectory. Retry and resume never touch
+ * it, so a judge outage can never cause a candidate to run again.
+ */
+export const JUDGE_ERROR_STATUS = 'judge_error' as const;
+
+/** Statuses whose attempt has a recorded trajectory the judge can grade again. */
+export const REJUDGEABLE_STATUSES: ReadonlySet<string> = new Set([
+ 'passed',
+ 'failed',
+ JUDGE_ERROR_STATUS,
+]);
+
+/**
+ * The rubric package reports a judge failure as `judgeError` on the evaluate
+ * result and on the rubric result it happened in; a real zero score has none.
+ */
+export const readJudgeError = (result: EvaluateResult): string | undefined => {
+ if (result.judgeError) return result.judgeError;
+ return result.rubricResults.find((rubric) => rubric.judgeError)?.judgeError;
+};
+
+/** Stored when the attempt exists but what it should be graded against does not. */
+export const GRADING_CONTEXT_MISSING = {
+ dataset: 'Grading context missing: dataset',
+ run: 'Grading context missing: run',
+ testCase: 'Grading context missing: test case',
+} as const;
+
+/** The message stored for a judge that threw instead of answering. */
+export const judgeFailureMessage = (error: unknown) =>
+ `Judge failed: ${error instanceof Error && error.message ? error.message : String(error)}`;
+
+/**
+ * What the judge did manage to say, kept for diagnosis. Scores of rubrics
+ * that failed are not scores, so they are dropped; a rubric that graded
+ * before another one failed keeps its reason.
+ */
+export const judgeDiagnostics = (result?: EvaluateResult): EvalRubricScore[] =>
+ (result?.rubricResults ?? [])
+ .filter((rubric) => !rubric.judgeError)
+ .map((rubric) => ({
+ reason: rubric.reason,
+ rubricId: rubric.rubricId,
+ score: rubric.score,
+ ...(rubric.verdicts && { verdicts: rubric.verdicts }),
+ }));
diff --git a/apps/server/src/services/agentEvalRun/progress.ts b/apps/server/src/services/agentEvalRun/progress.ts
new file mode 100644
index 00000000000..7d3c4dbe614
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/progress.ts
@@ -0,0 +1,104 @@
+import type { EvalRunMetrics } from '@lobechat/types';
+
+import { JUDGE_ERROR_STATUS } from './judgeError';
+import { roundCost } from './utils';
+
+interface ProgressTopic {
+ evalResult?: unknown;
+ status?: string | null;
+}
+
+/**
+ * A run's live progress from its RunTopics as they are now: cases finished and
+ * their verdicts, with the cost, tokens and steps they took. Written as cases
+ * end, and when a run (re)starts, so cases kept from before count at once.
+ */
+/** Live progress: the counts always, the totals once a case has reported them. */
+export type RunProgress = Partial<EvalRunMetrics> &
+ Pick<EvalRunMetrics, 'failedCases' | 'passedCases'> & {
+ completedCases: number;
+ errorCases: number;
+ timeoutCases: number;
+ };
+
+export const runProgressOf = (allTopics: ProgressTopic[]): RunProgress => {
+ const finished = (t: ProgressTopic) => {
+ const r = t.evalResult as Record<string, unknown> | null | undefined;
+ return !!r && 'completionReason' in r;
+ };
+ const completedCount = allTopics.filter(
+ (t) => finished(t) || 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;
+ const judgeErrorCases = allTopics.filter((t) => t.status === JUDGE_ERROR_STATUS).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;
+ }
+ }
+
+ return {
+ completedCases: completedCount,
+ cost: sumCost ? roundCost(sumCost) : undefined,
+ errorCases,
+ externalCases: externalCasesTraj || undefined,
+ failedCases,
+ judgeErrorCases: judgeErrorCases || undefined,
+ 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,
+ };
+};
diff --git a/apps/server/src/services/agentEvalRun/queue.ts b/apps/server/src/services/agentEvalRun/queue.ts
new file mode 100644
index 00000000000..8b707185b93
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/queue.ts
@@ -0,0 +1,76 @@
+import type { EvalRunConfig } from '@lobechat/types';
+import pMap from 'p-map';
+
+import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';
+
+import { QUEUED_TRIGGER_CONCURRENCY } from './constants';
+import type { EvalRunDeps } from './types';
+
+/**
+ * The number of cases an internal run executes at once, when it sets one. An
+ * external run's worker paces itself, so the limit only queues internal runs.
+ */
+export const queuedConcurrencyOf = (config?: EvalRunConfig | null): number | undefined => {
+ if (config?.executionMode === 'external') return undefined;
+ const limit = Math.floor(config?.maxConcurrency ?? 0);
+ return limit >= 1 ? limit : undefined;
+};
+
+/**
+ * Start the waiting cases of a run with a concurrency limit, as many as it has
+ * free slots. Called when the run starts and whenever one of its cases ends.
+ *
+ * @returns the cases started, or `undefined` when the run has no limit (every
+ * case is started by the paginated fan-out instead)
+ */
+export async function dispatchQueuedCases(
+ deps: EvalRunDeps,
+ runId: string,
+ config?: EvalRunConfig | null,
+): Promise<string[] | undefined> {
+ const runConfig =
+ config === undefined ? (await deps.runModel.findSummaryById(runId))?.config : config;
+ const limit = queuedConcurrencyOf(runConfig);
+ if (!limit) return undefined;
+
+ const claimed = await deps.executionRepo.claimQueuedCases(runId, limit);
+ const failed: string[] = [];
+ await pMap(
+ claimed,
+ async (testCaseId) => {
+ try {
+ await AgentEvalRunWorkflow.triggerExecuteTestCase({
+ runId,
+ testCaseId,
+ userId: deps.userId,
+ });
+ } catch (error) {
+ console.error('[agentEvalRun] failed to start queued case', runId, testCaseId, error);
+ failed.push(testCaseId);
+ }
+ },
+ { concurrency: QUEUED_TRIGGER_CONCURRENCY },
+ );
+ // A slot whose start never left must not stay taken until it goes stale.
+ await deps.executionRepo.releaseQueuedCases(runId, failed);
+ // With nothing started, no case will end to refill the queue: fail so the
+ // caller's durable step retries the dispatch instead of leaving the run idle.
+ if (claimed.length > 0 && failed.length === claimed.length) {
+ throw new Error(`Could not start any queued case of run ${runId}`);
+ }
+ return claimed.filter((id) => !failed.includes(id));
+}
+
+/** Refill free slots after a case ends; a failure here must not undo recording the case. */
+export async function refillQueuedCases(
+ deps: EvalRunDeps,
+ runId: string,
+ config?: EvalRunConfig | null,
+) {
+ if (config !== undefined && !queuedConcurrencyOf(config)) return;
+ try {
+ await dispatchQueuedCases(deps, runId, config);
+ } catch (error) {
+ console.error('[agentEvalRun] failed to refill queued cases', runId, error);
+ }
+}
diff --git a/apps/server/src/services/agentEvalRun/rejudge.ts b/apps/server/src/services/agentEvalRun/rejudge.ts
new file mode 100644
index 00000000000..9ae2f99000c
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/rejudge.ts
@@ -0,0 +1,79 @@
+import pMap from 'p-map';
+
+import { evaluateAndFinalizeRun } from './aggregate';
+import { assertRunCaseCompatibility } from './caseCompatibility';
+import { evaluateCase } from './completion';
+import { isRegradableEmptyAnswer } from './emptyAnswer';
+import { REJUDGEABLE_STATUSES } from './judgeError';
+import { rejudgeTopicThreads } from './thread';
+import type { EvalRunDeps } from './types';
+
+const REJUDGE_CONCURRENCY = 4;
+
+export interface RejudgeRunResult {
+ failedCases: number;
+ /** Cases still without a verdict after this re-judge: the judge failed again. */
+ judgeErrorCases: number;
+ passedCases: number;
+ /** Cases graded again. */
+ rejudged: number;
+}
+
+/**
+ * Grades a finished run again with the dataset's current judge setup (eval
+ * mode, rules, judge model, evidence) from the trajectories it recorded: no
+ * model answers again, only the judge runs. Cases with a verdict and cases
+ * whose judge failed (`judge_error`) are graded again, and so are attempts
+ * once held as errors for an empty answer; other cases that never ran to an
+ * answer (errors, timeouts, external) are left as they are, and the run's
+ * metrics are rebuilt from the new verdicts.
+ */
+export async function rejudgeRun(deps: EvalRunDeps, runId: string): Promise<RejudgeRunResult> {
+ const run = await deps.runModel.findById(runId);
+ if (!run) throw new Error('Run not found');
+ if (run.status === 'running' || run.status === 'pending') {
+ throw new Error(`Cannot re-judge a ${run.status} run`);
+ }
+
+ const runTopics = await deps.runTopicModel.findByRunId(runId);
+ // Also cases held as errors only for attempts that ended with no answer,
+ // which the current reading may grade as failures.
+ const targets = runTopics.filter(
+ (runTopic) =>
+ REJUDGEABLE_STATUSES.has(runTopic.status ?? '') ||
+ (runTopic.status === 'error' &&
+ (runTopic.evalResult?.threads?.some(isRegradableEmptyAnswer) ||
+ isRegradableEmptyAnswer({ error: runTopic.evalResult?.error, status: runTopic.status }))),
+ );
+ await assertRunCaseCompatibility(deps, run, targets);
+
+ await pMap(
+ targets,
+ async (runTopic) => {
+ if (runTopic.evalResult?.threads?.length) {
+ await rejudgeTopicThreads(deps, {
+ runId,
+ testCaseId: runTopic.testCaseId,
+ topicId: runTopic.topicId,
+ });
+ } else {
+ await evaluateCase(deps, runId, runTopic);
+ }
+ },
+ { concurrency: REJUDGE_CONCURRENCY },
+ );
+
+ const fresh = await deps.runTopicModel.findByRunId(runId);
+ const metrics = await evaluateAndFinalizeRun({ run, runTopics: fresh });
+ await deps.runModel.update(runId, {
+ // The wall-clock duration belongs to the original execution.
+ metrics: { ...metrics, duration: run.metrics?.duration ?? metrics.duration },
+ });
+
+ return {
+ failedCases: metrics.failedCases,
+ judgeErrorCases: metrics.judgeErrorCases ?? 0,
+ passedCases: metrics.passedCases,
+ rejudged: targets.length,
+ };
+}
diff --git a/apps/server/src/services/agentEvalRun/rerun.ts b/apps/server/src/services/agentEvalRun/rerun.ts
new file mode 100644
index 00000000000..6e8e6918f35
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/rerun.ts
@@ -0,0 +1,94 @@
+import type { EvalRunMetrics } from '@lobechat/types';
+
+import { assertRunCaseCompatibility } from './caseCompatibility';
+import { assertRunConnectorBindings } from './connectorBindings';
+import { createRunTopics } from './createRun';
+import { runProgressOf } from './progress';
+import type { EvalRunDeps } from './types';
+
+/**
+ * Attempt statuses that are not a verdict: the model never answered (error,
+ * timeout) or the judge could not grade the answer (judge_error).
+ */
+export const UNVERIFIED_STATUSES: ReadonlySet<string> = new Set([
+ 'error',
+ 'judge_error',
+ 'timeout',
+]);
+
+interface RerunCandidate {
+ evalResult?: {
+ error?: string | null;
+ threads?: Array<{ status?: string | null; error?: string | null }> | null;
+ } | null;
+ status?: string | null;
+}
+
+/**
+ * A case runs again when the case itself, or any of its k attempts, has no
+ * verdict. The whole case runs again (every attempt), so its pass^k reading
+ * rests on one fresh sample instead of a patchwork of old and new attempts.
+ */
+export const needsRerun = (topic: RerunCandidate) =>
+ UNVERIFIED_STATUSES.has(topic.status ?? '') ||
+ topic.evalResult?.error === 'No assistant output' ||
+ (topic.evalResult?.threads ?? []).some(
+ (thread) =>
+ UNVERIFIED_STATUSES.has(thread.status ?? '') || thread.error === 'No assistant output',
+ );
+
+/**
+ * Runs again every case of a finished run that has an attempt without a
+ * verdict, with the run's own settings. Lobe Bench's one answer to errors,
+ * timeouts and judge failures alike: the model answers
+ * again and the judge grades as part of the normal execution; nothing is
+ * re-graded in place. Old Topics stay for audit, as with `retryErrorCases`;
+ * only the RunTopic rows are replaced and the run goes back to `pending` for
+ * the workflow to pick up.
+ */
+export async function rerunUnverifiedCases(
+ deps: EvalRunDeps,
+ runId: string,
+): Promise<{ rerunCount: number }> {
+ const run = await deps.runModel.findById(runId);
+ if (!run) throw new Error('Run not found');
+ if (run.status === 'running' || run.status === 'pending') {
+ throw new Error(`Cannot rerun a ${run.status} run`);
+ }
+
+ const runTopics = await deps.runTopicModel.findByRunId(runId);
+ const targets = runTopics.filter((runTopic) => needsRerun(runTopic));
+ await assertRunCaseCompatibility(deps, run, targets);
+ await assertRunConnectorBindings(
+ deps,
+ run,
+ targets.map((target) => target.testCaseId),
+ );
+ if (targets.length === 0) return { rerunCount: 0 };
+
+ for (const target of targets) {
+ await deps.runTopicModel.deleteByRunAndTestCase(runId, target.testCaseId);
+ }
+ await createRunTopics(
+ deps,
+ run,
+ targets.map((target) => ({
+ content: target.testCase?.content ?? { input: '' },
+ environmentId: target.testCase?.environmentId ?? null,
+ id: target.testCaseId,
+ sortOrder: target.testCase?.sortOrder ?? null,
+ })),
+ );
+ // Progress from the cases kept, so the run never reads 0 done while it waits to restart.
+ const kept = await deps.runTopicModel.findByRunId(runId);
+ await deps.runModel.update(runId, {
+ metrics: {
+ ...(run.metrics as EvalRunMetrics),
+ ...runProgressOf(kept),
+ totalCases: run.metrics?.totalCases ?? kept.length,
+ },
+ status: 'pending',
+ });
+
+ return { rerunCount: targets.length };
+}
diff --git a/apps/server/src/services/agentEvalRun/resumeExecution.ts b/apps/server/src/services/agentEvalRun/resumeExecution.ts
index 89243bb625e..a04587b9e4c 100644
--- a/apps/server/src/services/agentEvalRun/resumeExecution.ts
+++ b/apps/server/src/services/agentEvalRun/resumeExecution.ts
@@ -1,4 +1,3 @@
-import type { EvalThreadResult } from '@lobechat/types';
import { RequestTrigger } from '@lobechat/types';
import { AiAgentService } from '@/server/services/aiAgent';
@@ -8,17 +7,16 @@ import {
type ResumeThreadTrajectoryPayload,
} from '@/server/workflows/agentEvalRun';
+import { contenderChatConfigOf } from './caseAgent';
import { recordTrajectoryCompletion } from './completion';
+import { assertCaseConnectorBindings } from './connectorBindings';
import { createEvalRunDeps } from './deps';
import { canResumeTrajectory } from './resumeTarget';
+import { interruptEvalOperations } from './runLifecycle';
import { recordThreadCompletion } from './thread';
+import { prepareTrialMemory } from './trialMemory';
import type { EvalRunDeps } from './types';
-import { getEvalContextParams, log } from './utils';
-
-const resetResumedThreadResult = (thread: EvalThreadResult): EvalThreadResult => ({
- threadId: thread.threadId,
- status: thread.status === 'external' ? 'external' : 'running',
-});
+import { getEvalAttemptId, getEvalContextParams, log } from './utils';
/**
* Resume a timed-out single-agent trajectory (pass@1).
@@ -46,6 +44,24 @@ export async function executeResumedTrajectory(
return { reason: resumeCheck.reason, status: 'cancelled' as const, topicId };
}
+ const run = await deps.runModel.findById(runId);
+ await assertCaseConnectorBindings(
+ deps,
+ run?.datasetId,
+ environment,
+ run?.config?.connectorSnapshots?.[testCaseId],
+ true,
+ );
+
+ // Validate the original fixture before the resume claim can reset prior evidence.
+ const memory = await prepareTrialMemory(deps, {
+ environment,
+ resume: true,
+ runId,
+ testCaseId,
+ topicId,
+ });
+
// Look up the pre-created RunTopic and reset it for resume
log(
'executeResumedTrajectory: run=%s testCase=%s topicId=%s parentMessageId=%s',
@@ -54,10 +70,17 @@ export async function executeResumedTrajectory(
topicId,
parentMessageId,
);
- const runTopic = await deps.runTopicModel.findByRunAndTestCase(runId, testCaseId);
- if (!runTopic) {
- throw new Error(`RunTopic not found for run=${runId} testCase=${testCaseId}`);
- }
+ const executionId = crypto.randomUUID();
+ const claimed = await deps.executionRepo.claimExecution({
+ executionId,
+ expectedExecutionId: params.expectedExecutionId,
+ resume: true,
+ runId,
+ testCaseId,
+ topicId,
+ });
+ if (!claimed) return { reason: 'Resume target changed', status: 'cancelled' as const, topicId };
+ const runTopic = claimed.parent;
// Capture accumulated telemetry from previous runs before clearing evalResult
const prevSteps = runTopic.evalResult?.steps ?? 0;
@@ -66,17 +89,15 @@ export async function executeResumedTrajectory(
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 bindOperation = async (operationId: string) => {
+ const saved = await deps.runTopicModel.mergeExecutionResult(runId, topicId, executionId, {
+ operationId,
+ });
+ if (!saved) {
+ await interruptEvalOperations(deps, [operationId]);
+ throw new Error('Execution is no longer current');
+ }
+ };
const aiAgentService = new AiAgentService(deps.db, deps.userId, {
workspaceId: deps.workspaceId,
@@ -88,43 +109,59 @@ export async function executeResumedTrajectory(
try {
const execResult = await aiAgentService.execAgent({
agentId: targetAgentId,
- appContext,
+ appContext: { ...appContext, suppressSignal: true },
autoStart: true,
+ chatConfigOverride: contenderChatConfigOf(run),
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,
- // `event.llmCalls` is already cumulative: the operation is seeded with
- // `initialLlmCalls: prevLlmCalls`.
- llmCalls: event.llmCalls ?? 0,
- steps: (event.steps ?? 0) + prevSteps,
- toolCalls: (event.toolCalls ?? 0) + prevToolCalls,
- totalTokens: (event.totalTokens ?? 0) + prevTokens,
+ const { allDone } = await recordTrajectoryCompletion(
+ createEvalRunDeps(db, userId, deps.workspaceId),
+ {
+ executionId,
+ topicId,
+ 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,
+ // The seeded operation already reports a cumulative LLM call count.
+ llmCalls: event.llmCalls ?? 0,
+ steps: (event.steps ?? 0) + prevSteps,
+ toolCalls: (event.toolCalls ?? 0) + prevToolCalls,
+ totalTokens: (event.totalTokens ?? 0) + prevTokens,
+ },
+ testCaseId,
},
- testCaseId,
- });
+ );
+ // Queue mode finalizes from the completion webhook; in-process runs
+ // have only this handler, so the run must be finalized here.
+ if (allDone) await AgentEvalRunWorkflow.triggerFinalizeRun({ runId, userId });
},
id: 'eval-trajectory-complete',
type: 'onComplete' as const,
webhook: {
- body: { runId, testCaseId, userId },
+ body: { executionId, runId, testCaseId, topicId, userId },
delivery: 'qstash' as const,
url: webhookUrl,
},
},
],
- ...getEvalContextParams(envPrompt, environment, params.caseId),
+ ...getEvalContextParams(
+ envPrompt,
+ environment,
+ params.caseId,
+ memory,
+ getEvalAttemptId({ runId, topicId }),
+ run?.config?.connectorSnapshots?.[testCaseId],
+ ),
initialLlmCalls: prevLlmCalls,
+ onOperationCreated: bindOperation,
initialStepCount: prevSteps,
maxSteps,
parentMessageId,
@@ -134,9 +171,7 @@ export async function executeResumedTrajectory(
});
if (execResult?.operationId) {
- await deps.runTopicModel.updateByRunAndTopic(runId, topicId, {
- evalResult: { operationId: execResult.operationId, rubricScores: [] },
- });
+ await bindOperation(execResult.operationId);
}
return { status: 'started' as const, topicId };
@@ -149,6 +184,8 @@ export async function executeResumedTrajectory(
// Record error and finalize the run if all test cases are done
const { allDone } = await recordTrajectoryCompletion(deps, {
+ executionId,
+ topicId,
runId,
status: 'error',
telemetry: { completionReason: 'error', errorMessage },
@@ -191,42 +228,59 @@ export async function executeResumedThreadTrajectory(
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}`);
- }
+ // Keep the prior attempt evidence intact if its original fixture is unknown or changed.
+ const run = await deps.runModel.findById(runId);
+ await assertCaseConnectorBindings(
+ deps,
+ run?.datasetId,
+ environment,
+ run?.config?.connectorSnapshots?.[testCaseId],
+ true,
+ );
- 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 }];
+ const memory = await prepareTrialMemory(deps, {
+ environment,
+ resume: true,
+ runId,
+ testCaseId,
+ threadId,
+ topicId,
+ });
+ // Look up the pre-created RunTopic and reset it for resume
+ const executionId = crypto.randomUUID();
+ const claimed = await deps.executionRepo.claimExecution({
+ executionId,
+ expectedExecutionId: params.expectedExecutionId,
+ resume: true,
+ runId,
+ testCaseId,
+ threadId,
+ topicId,
+ });
+ if (!claimed)
+ return { reason: 'Resume target changed', status: 'cancelled' as const, threadId, topicId };
+ const currentThread = claimed.thread;
+ const currentThreadMeta = (currentThread?.metadata ?? {}) as Record<string, unknown>;
// 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 bindOperation = async (operationId: string) => {
+ const saved = await deps.executionRepo.updateThreadMetadata(
+ runId,
+ topicId,
+ threadId,
+ { operationId },
+ { executionId },
+ );
+ if (!saved) {
+ await interruptEvalOperations(deps, [operationId]);
+ throw new Error('Execution is no longer current');
+ }
+ };
const aiAgentService = new AiAgentService(deps.db, deps.userId, {
workspaceId: deps.workspaceId,
@@ -238,44 +292,59 @@ export async function executeResumedThreadTrajectory(
try {
const execResult = await aiAgentService.execAgent({
agentId: targetAgentId,
- appContext,
+ appContext: { ...appContext, suppressSignal: true },
autoStart: true,
+ chatConfigOverride: contenderChatConfigOf(run),
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,
- // `event.llmCalls` is already cumulative: the operation is seeded with
- // `initialLlmCalls: prevLlmCalls`.
- llmCalls: event.llmCalls ?? 0,
- steps: (event.steps ?? 0) + prevSteps,
- toolCalls: (event.toolCalls ?? 0) + prevToolCalls,
- totalTokens: (event.totalTokens ?? 0) + prevTokens,
+ const { allRunDone } = await recordThreadCompletion(
+ createEvalRunDeps(db, userId, deps.workspaceId),
+ {
+ executionId,
+ runId,
+ status: event.status || event.reason || 'done',
+ telemetry: {
+ completionReason: event.reason,
+ cost: (event.cost ?? 0) + prevCost,
+ duration: event.duration,
+ errorMessage: event.errorMessage,
+ // The seeded operation already reports a cumulative LLM call count.
+ llmCalls: event.llmCalls ?? 0,
+ steps: (event.steps ?? 0) + prevSteps,
+ toolCalls: (event.toolCalls ?? 0) + prevToolCalls,
+ totalTokens: (event.totalTokens ?? 0) + prevTokens,
+ },
+ testCaseId,
+ threadId,
+ topicId,
},
- testCaseId,
- threadId,
- topicId,
- });
+ );
+ // Queue mode finalizes from the completion webhook; in-process runs
+ // have only this handler, so the run must be finalized here.
+ if (allRunDone) await AgentEvalRunWorkflow.triggerFinalizeRun({ runId, userId });
},
id: 'eval-thread-complete',
type: 'onComplete' as const,
webhook: {
- body: { runId, testCaseId, threadId, topicId, userId },
+ body: { executionId, runId, testCaseId, threadId, topicId, userId },
delivery: 'qstash' as const,
url: webhookUrl,
},
},
],
- ...getEvalContextParams(envPrompt, environment, caseId),
+ ...getEvalContextParams(
+ envPrompt,
+ environment,
+ caseId,
+ memory,
+ getEvalAttemptId({ runId, threadId, topicId }),
+ run?.config?.connectorSnapshots?.[testCaseId],
+ ),
initialLlmCalls: prevLlmCalls,
+ onOperationCreated: bindOperation,
initialStepCount: prevSteps,
maxSteps,
parentMessageId,
@@ -286,9 +355,7 @@ export async function executeResumedThreadTrajectory(
// Write operationId to thread metadata
if (execResult?.operationId) {
- await deps.threadModel.update(threadId, {
- metadata: { operationId: execResult.operationId, testCaseId } as any,
- });
+ await bindOperation(execResult.operationId);
}
return { status: 'started' as const, threadId, topicId };
@@ -302,6 +369,7 @@ export async function executeResumedThreadTrajectory(
// Record error and finalize the run if all test cases are done
const { allRunDone } = await recordThreadCompletion(deps, {
+ executionId,
runId,
status: 'error',
telemetry: { completionReason: 'error', errorMessage },
diff --git a/apps/server/src/services/agentEvalRun/resumeTarget.ts b/apps/server/src/services/agentEvalRun/resumeTarget.ts
index 438dfbaf44d..76c96821361 100644
--- a/apps/server/src/services/agentEvalRun/resumeTarget.ts
+++ b/apps/server/src/services/agentEvalRun/resumeTarget.ts
@@ -3,12 +3,23 @@ import type { EvalRunTopicResult, EvalThreadResult } from '@lobechat/types';
import pMap from 'p-map';
import type { ThreadModel } from '@/database/models/thread';
+import { EvalConnectorBindingError } from '@/server/services/agentEvalConnector';
+import {
+ AgentEvalMemoryService,
+ EvalMemoryFixtureConflictError,
+} from '@/server/services/agentEvalMemory';
import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';
+import { resolveTopicAgentId } from './caseAgent';
+import { assertRunCaseCompatibility, EvalCaseCompatibilityError } from './caseCompatibility';
+import { withResolvedEnvironment } from './caseEnvironment';
+import { assertCaseConnectorBindings } from './connectorBindings';
import { loadTrajectoryData } from './trajectory';
import type { EvalRunDeps } from './types';
import { getCaseId, log } from './utils';
+export class EvalResumeConflictError extends Error {}
+
const RESUMABLE_THREAD_STATUSES = new Set(['error', 'timeout']);
/** Caps concurrent per-case resume checks (each issues several DB reads). */
const RESUME_CHECK_CONCURRENCY = 5;
@@ -44,6 +55,13 @@ export async function canResumeTrajectory(
const runTopic = await deps.runTopicModel.findByRunAndTestCase(params.runId, params.testCaseId);
if (!runTopic) return { canResume: false, reason: invalidResumeTargetReason };
+ try {
+ await assertRunCaseCompatibility(deps, run, [runTopic]);
+ } catch (error) {
+ if (error instanceof EvalCaseCompatibilityError)
+ return { canResume: false, reason: error.message };
+ throw error;
+ }
log('canResumeTrajectory: runTopic.status=%s topicId=%s', runTopic.status, runTopic.topicId);
@@ -91,17 +109,38 @@ export async function canResumeTrajectory(
}
}
- // 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 };
+ // pass@1 tracks steps on the runTopic; pass@k uses per-thread metadata above.
+ if (k === 1) {
+ 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 };
+ }
}
+ if (!runTopic.testCase) return { canResume: false, reason: invalidResumeTargetReason };
+ const testCase = await withResolvedEnvironment(deps, runTopic.testCase);
+ try {
+ await assertCaseConnectorBindings(
+ deps,
+ run.datasetId,
+ testCase.content.environment,
+ run.config?.connectorSnapshots?.[params.testCaseId],
+ );
+ await new AgentEvalMemoryService(deps.db, deps.userId, deps.workspaceId).assertResumeFixture({
+ fixture: testCase.content.environment?.memory ?? {},
+ ...params,
+ topicId: runTopic.topicId,
+ });
+ } catch (error) {
+ if (
+ error instanceof EvalMemoryFixtureConflictError ||
+ error instanceof EvalConnectorBindingError
+ )
+ return { canResume: false, reason: error.message };
+ throw error;
+ }
return { canResume: true as const };
}
@@ -152,11 +191,12 @@ export async function resumeTrajectory(
const resumeCheck = await canResumeTrajectory(deps, params);
if (!resumeCheck.canResume) {
log('resumeTrajectory: canResume=false reason=%s', resumeCheck.reason);
- throw new Error(resumeCheck.reason);
+ throw new EvalResumeConflictError(resumeCheck.reason);
}
const target = await resolveTrajectoryResumeTarget(deps, params);
- const { caseId, envPrompt, environment, parentMessageId, run, thread, topicId } = target;
+ const { caseId, envPrompt, environment, parentMessageId, run, runTopic, thread, topicId } =
+ target;
log(
'resumeTrajectory: resolved target β€” topicId=%s parentMessageId=%s threadId=%s',
topicId,
@@ -164,16 +204,20 @@ export async function resumeTrajectory(
thread?.id,
);
+ // Resume on the Agent the topic belongs to (a hidden case Agent or the target Agent).
+ const targetAgentId = await resolveTopicAgentId(deps, topicId, run.targetAgentId);
+
if (thread) {
log('resumeTrajectory: triggering resume-thread-trajectory');
await AgentEvalRunWorkflow.triggerResumeThreadTrajectory({
+ expectedExecutionId: runTopic.evalResult?.executionId,
appContext: { threadId: thread.id, topicId },
caseId,
envPrompt,
maxSteps: run.config?.maxSteps,
parentMessageId,
runId: run.id,
- targetAgentId: run.targetAgentId ?? undefined,
+ targetAgentId,
testCaseId: params.testCaseId,
threadId: thread.id,
topicId,
@@ -183,13 +227,14 @@ export async function resumeTrajectory(
} else {
log('resumeTrajectory: triggering resume-agent-trajectory');
await AgentEvalRunWorkflow.triggerResumeAgentTrajectory({
+ expectedExecutionId: runTopic.evalResult?.executionId,
appContext: { topicId },
caseId,
envPrompt,
maxSteps: run.config?.maxSteps,
parentMessageId,
runId: run.id,
- targetAgentId: run.targetAgentId ?? undefined,
+ targetAgentId,
testCaseId: params.testCaseId,
topicId,
environment,
@@ -272,6 +317,18 @@ async function resolveTrajectoryResumeTarget(
const runTopic = await deps.runTopicModel.findByRunAndTestCase(params.runId, params.testCaseId);
if (!runTopic?.topicId) throw new Error('RunTopic topicId is required');
+ try {
+ await new AgentEvalMemoryService(deps.db, deps.userId, deps.workspaceId).assertResumeFixture({
+ fixture: environment?.memory ?? {},
+ ...params,
+ topicId: runTopic.topicId,
+ });
+ } catch (error) {
+ if (error instanceof EvalMemoryFixtureConflictError)
+ throw new EvalResumeConflictError(error.message);
+ throw error;
+ }
+
log(
'resolveTrajectoryResumeTarget: topicId=%s runTopic.status=%s',
runTopic.topicId,
diff --git a/apps/server/src/services/agentEvalRun/runLifecycle.ts b/apps/server/src/services/agentEvalRun/runLifecycle.ts
index 7407a3b3ed3..3beda4619d4 100644
--- a/apps/server/src/services/agentEvalRun/runLifecycle.ts
+++ b/apps/server/src/services/agentEvalRun/runLifecycle.ts
@@ -1,9 +1,15 @@
import type { EvalRunConfig, EvalRunMetrics, EvalRunTopicResult } from '@lobechat/types';
+import { AgentOperationModel } from '@/database/models/agentOperation';
import { AgentRuntimeService } from '@/server/services/agentRuntime/AgentRuntimeService';
import { evaluateAndFinalizeRun } from './aggregate';
+import { deleteCaseAgents } from './caseAgent';
+import { assertRunCaseCompatibility } from './caseCompatibility';
+import { assertRunConnectorBindings } from './connectorBindings';
import { createRunTopics } from './createRun';
+import { runProgressOf } from './progress';
+import { refillQueuedCases } from './queue';
import type { EvalRunDeps } from './types';
export async function deleteRun(deps: EvalRunDeps, id: string) {
@@ -19,33 +25,50 @@ export async function deleteRun(deps: EvalRunDeps, id: string) {
await deps.topicModel.batchDelete(topicIds);
}
+ // 4. Delete the hidden case Agents the run created (with any topics kept
+ // from retries, which cascade with their Agent)
+ await deleteCaseAgents(deps, id);
+
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
- }
- }
+/** Interrupt every still-open operation under an attempt, preserving finished children. */
+export async function interruptEvalOperations(deps: EvalRunDeps, operationIds: string[]) {
+ const runtime = new AgentRuntimeService(deps.db, deps.userId);
+ const operations = new AgentOperationModel(deps.db, deps.userId, deps.workspaceId);
+ const open = new Set([
+ 'pending',
+ 'running',
+ 'waiting_for_async_tool',
+ 'waiting_for_client',
+ 'waiting_for_human',
+ ]);
+ const interrupted = new Set<string>();
+ for (const operationId of new Set(operationIds)) {
+ const tree = await operations.listOperationTree(operationId).catch(() => []);
+ const ids = [operationId, ...tree.filter((op) => open.has(op.status ?? '')).map((op) => op.id)];
+ for (const id of ids) {
+ if (interrupted.has(id)) continue;
+ interrupted.add(id);
+ await runtime.interruptOperation(id).catch(() => undefined);
}
}
+}
- // 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 abortRun(deps: EvalRunDeps, runId: string) {
+ // Close the write gate before interrupting: interruption itself can deliver
+ // completion callbacks. Keep partial results and operation ids for audit.
+ const stoppedTopics = await deps.executionRepo.batchMarkAborted(runId);
+
+ const operationIds: string[] = [];
+ for (const rt of stoppedTopics) {
+ const result = rt.evalResult as EvalRunTopicResult | null;
+ if (result?.operationId) operationIds.push(result.operationId);
+ for (const attempt of result?.threads ?? []) {
+ if (attempt.operationId) operationIds.push(attempt.operationId);
+ }
+ }
+ await interruptEvalOperations(deps, operationIds);
}
export async function retryErrorCases(
@@ -57,12 +80,19 @@ export async function retryErrorCases(
const allTopics = await deps.runTopicModel.findByRunId(runId);
const errorTopics = allTopics.filter((t) => t.status === 'error' || t.status === 'timeout');
+ await assertRunCaseCompatibility(deps, run, errorTopics);
+ await assertRunConnectorBindings(
+ deps,
+ run,
+ errorTopics.map((target) => target.testCaseId),
+ );
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: '' },
+ environmentId: t.testCase?.environmentId ?? null,
id: t.testCaseId,
sortOrder: t.testCase?.sortOrder ?? null,
}));
@@ -74,10 +104,19 @@ export async function retryErrorCases(
// 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' });
+ await createRunTopics(deps, run, errorTestCases);
+
+ // 4. Set run status to pending, with progress from the cases kept
+ const kept = await deps.runTopicModel.findByRunId(runId);
+ await deps.runModel.update(runId, {
+ metrics: {
+ ...(run.metrics as EvalRunMetrics),
+ ...runProgressOf(kept),
+ totalCases: run.metrics?.totalCases ?? kept.length,
+ },
+ startedAt: new Date(Math.max(Date.now(), (run.startedAt?.getTime() ?? 0) + 1)),
+ status: 'pending',
+ });
return { retryCount: errorTopics.length };
}
@@ -93,33 +132,50 @@ export async function retrySingleCase(deps: EvalRunDeps, runId: string, testCase
if (runTopic.status === 'running' || runTopic.status === 'pending') {
throw new Error(`Cannot retry: case is ${runTopic.status}`);
}
+ // The attempt ran; only its grading failed. Re-judge it instead of paying
+ // for the candidate again.
+ if (runTopic.status === 'judge_error') {
+ throw new Error('Cannot retry: the attempt ran but was not judged; re-judge it instead');
+ }
+ await assertRunCaseCompatibility(deps, run, [runTopic]);
+ await assertRunConnectorBindings(deps, run, [testCaseId]);
// 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, [
+ await createRunTopics(deps, run, [
{
content: runTopic.testCase?.content ?? { input: '' },
+ environmentId: runTopic.testCase?.environmentId ?? null,
id: testCaseId,
sortOrder: runTopic.testCase?.sortOrder ?? null,
},
]);
- // 5. Set run status to running
- await deps.runModel.update(runId, { status: 'running' });
+ // 5. Set run status to running, with progress from the cases kept
+ const kept = await deps.runTopicModel.findByRunId(runId);
+ await deps.runModel.update(runId, {
+ metrics: {
+ ...(run.metrics as EvalRunMetrics),
+ ...runProgressOf(kept),
+ totalCases: run.metrics?.totalCases ?? kept.length,
+ },
+ startedAt: new Date(Math.max(Date.now(), (run.startedAt?.getTime() ?? 0) + 1)),
+ status: 'running',
+ });
}
export async function getRunDetails(deps: EvalRunDeps, id: string) {
- let run = await deps.runModel.findById(id);
+ let run = await deps.runModel.findSummaryById(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))!;
+ run = (await deps.runModel.findSummaryById(id))!;
}
}
@@ -192,41 +248,38 @@ export async function checkAndHandleRunTimeout(
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);
+ // Each case is timed from its own start, never from the run's: a retry moves
+ // the run's startedAt (its generation stamp) while untouched cases keep running.
+ // Single SQL: mark running topics where created_at + timeout < NOW() as 'timeout'
+ const timedOutRows = await deps.executionRepo.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
- }
- }
- }
+ const operations = timedOutRows
+ .flatMap((row) => [
+ row.evalResult?.operationId,
+ ...(row.evalResult?.threads ?? []).map((thread) => thread.operationId),
+ ])
+ .filter((id): id is string => !!id);
+ await interruptEvalOperations(deps, operations);
// 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 ?? [],
+ 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,
},
- passed: false,
- score: 0,
- });
+ { executionId: row.evalResult?.executionId, status: 'timeout' },
+ );
}
// Re-aggregate metrics from all RunTopics (including newly timed-out ones)
@@ -251,7 +304,11 @@ export async function checkAndHandleRunTimeout(
? 'failed'
: 'completed';
- await deps.runModel.update(run.id, { metrics, status: runStatus });
+ await deps.runModel.finalize(
+ run.id,
+ { metrics, status: runStatus },
+ { startedAt: run.startedAt },
+ );
} else {
// Some topics still running β†’ update real-time metrics so progress reflects timeouts
const completedCount = allTopics.filter(
@@ -261,17 +318,23 @@ export async function checkAndHandleRunTimeout(
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;
+ const judgeErrorCases = allTopics.filter((t) => t.status === 'judge_error').length;
- await deps.runModel.update(run.id, {
- metrics: {
+ await deps.runModel.updateProgress(
+ run.id,
+ {
...(run.metrics as EvalRunMetrics),
completedCases: completedCount,
errorCases,
failedCases,
+ judgeErrorCases: judgeErrorCases || undefined,
passedCases,
timeoutCases,
},
- });
+ { startedAt: run.startedAt },
+ );
+ // Timed-out cases free their slots for the cases still waiting.
+ await refillQueuedCases(deps, run.id, run.config);
}
return true;
diff --git a/apps/server/src/services/agentEvalRun/subAgentEvidence.ts b/apps/server/src/services/agentEvalRun/subAgentEvidence.ts
new file mode 100644
index 00000000000..2762aec3a8e
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/subAgentEvidence.ts
@@ -0,0 +1,69 @@
+import { ThreadType } from '@lobechat/types';
+import { and, eq } from 'drizzle-orm';
+
+import { threads } from '@/database/schemas';
+import { buildWorkspaceWhere } from '@/database/utils/workspace';
+
+import type { EvalRunDeps } from './types';
+
+/** How deep sub-agents may nest inside one attempt (a sub-agent of a sub-agent …). */
+const MAX_SUB_AGENT_DEPTH = 4;
+
+interface AttemptMessage {
+ id: string;
+ /** Set on a sub-agent's message: the isolation thread it ran in, by title. */
+ via?: string;
+}
+
+/**
+ * An attempt's messages with the messages of the sub-agents it started laid in
+ * after the tool message that started each one, nested sub-agents included.
+ * A sub-agent runs in an isolation thread of the attempt's topic, hanging off
+ * that tool message; the attempt's own message list never contains it, so a
+ * judge reading only that list cannot see what the sub-agent did.
+ */
+export const withSubAgentMessages = async <T extends AttemptMessage>(
+ deps: Pick<EvalRunDeps, 'db' | 'messageModel' | 'userId' | 'workspaceId'>,
+ params: { messages: T[]; topicId: string },
+): Promise<T[]> => {
+ const isolation = await deps.db
+ .select({ id: threads.id, sourceMessageId: threads.sourceMessageId, title: threads.title })
+ .from(threads)
+ .where(
+ and(
+ eq(threads.topicId, params.topicId),
+ eq(threads.type, ThreadType.Isolation),
+ buildWorkspaceWhere({ userId: deps.userId, workspaceId: deps.workspaceId }, threads),
+ ),
+ );
+ if (isolation.length === 0) return params.messages;
+
+ const bySource = new Map<string, typeof isolation>();
+ for (const thread of isolation) {
+ if (!thread.sourceMessageId) continue;
+ bySource.set(thread.sourceMessageId, [...(bySource.get(thread.sourceMessageId) ?? []), thread]);
+ }
+
+ const expand = async (list: T[], depth: number): Promise<T[]> => {
+ const out: T[] = [];
+ for (const message of list) {
+ out.push(message);
+ if (depth >= MAX_SUB_AGENT_DEPTH) continue;
+ for (const thread of bySource.get(message.id) ?? []) {
+ const own = (await deps.messageModel.query({
+ threadId: thread.id,
+ topicId: params.topicId,
+ })) as unknown as T[];
+ const label = thread.title || 'sub-agent';
+ const nested = await expand(
+ own.map((item) => ({ ...item, via: item.via ?? label })),
+ depth + 1,
+ );
+ out.push(...nested);
+ }
+ }
+ return out;
+ };
+
+ return expand(params.messages, 0);
+};
diff --git a/apps/server/src/services/agentEvalRun/thread.ts b/apps/server/src/services/agentEvalRun/thread.ts
index f7b9bd6cb04..be0e3d2d3ad 100644
--- a/apps/server/src/services/agentEvalRun/thread.ts
+++ b/apps/server/src/services/agentEvalRun/thread.ts
@@ -1,7 +1,8 @@
-import { evaluate } from '@lobechat/eval-rubric';
+import { evaluate, type EvaluateResult } from '@lobechat/eval-rubric';
import type {
EvalBenchmarkRubric,
EvalCaseEnvironment,
+ EvalMemorySnapshot,
EvalRunConfig,
EvalRunMetrics,
EvalRunTopicResult,
@@ -15,6 +16,8 @@ import pMap from 'p-map';
import { AiAgentService } from '@/server/services/aiAgent';
import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';
+import { contenderChatConfigOf, resolveTopicAgentId } from './caseAgent';
+import { assertCaseConnectorBindings } from './connectorBindings';
import {
EVAL_AGENT_RUNTIME_QSTASH_RETRIES,
EVAL_AGENT_RUNTIME_QSTASH_RETRY_DELAY,
@@ -22,15 +25,40 @@ import {
THREAD_TRIGGER_CONCURRENCY,
} from './constants';
import { createEvalRunDeps } from './deps';
+import { classifyEmptyAnswer, isRegradableEmptyAnswer } from './emptyAnswer';
+import {
+ attemptReply,
+ buildEvalModeRubric,
+ buildJudgeEvidence,
+ createJudgeMatchContext,
+ resolveEvalJudge,
+} from './judge';
+import {
+ GRADING_CONTEXT_MISSING,
+ JUDGE_ERROR_STATUS,
+ judgeDiagnostics,
+ judgeFailureMessage,
+ readJudgeError,
+} from './judgeError';
+import { refillQueuedCases } from './queue';
+import { interruptEvalOperations } from './runLifecycle';
+import { withSubAgentMessages } from './subAgentEvidence';
+import { prepareTrialMemory, snapshotTrialMemory } from './trialMemory';
import type { EvalRunDeps } from './types';
-import { getCaseId, getEvalContextParams, roundCost } from './utils';
+import { getCaseId, getEvalAttemptId, 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')
+ if (
+ status === 'completed' ||
+ status === 'error' ||
+ status === 'external' ||
+ status === 'timeout' ||
+ status === JUDGE_ERROR_STATUS
+ )
return status;
if (evalResult.passed === true) return 'passed';
@@ -66,44 +94,27 @@ export async function executeMultiThreadTrajectory(
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,
+ const prepared = await deps.executionRepo.prepareThreadExecutions({
+ expectedExecutionId: runTopic.evalResult?.executionId,
+ k,
+ runId,
+ sourceMessageId: typeof historyTailMessageId === 'string' ? historyTailMessageId : undefined,
+ testCaseId,
+ topicId,
});
+ if (!prepared) return;
+ const { pendingThreads, threadIds } = prepared;
- // 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.
+ // Retry only unclaimed attempts from the persisted set. A delivery may have
+ // succeeded even if its response failed; the queued executionId makes the
+ // child's claim idempotent in that case. Attempt every trigger before throwing.
let firstTriggerError: { error: unknown } | undefined;
await pMap(
- threadIds,
- async (threadId) => {
+ pendingThreads,
+ async ({ executionId, threadId }) => {
try {
await AgentEvalRunWorkflow.triggerRunThreadTrajectory({
+ executionId,
runId,
testCaseId,
threadId,
@@ -128,9 +139,11 @@ export async function executeMultiThreadTrajectory(
export async function executeThreadTrajectory(
deps: EvalRunDeps,
params: {
+ executionId?: string;
envPrompt?: string;
run: {
config?: EvalRunConfig | null;
+ datasetId: string;
targetAgentId?: string | null;
};
runId: string;
@@ -146,6 +159,31 @@ export async function executeThreadTrajectory(
},
) {
const { envPrompt, environment, run, runId, testCaseId, threadId, topicId } = params;
+ await assertCaseConnectorBindings(
+ deps,
+ run.datasetId,
+ environment,
+ run.config?.connectorSnapshots?.[testCaseId],
+ );
+ const current = await deps.runTopicModel.findByRunAndTestCase(runId, testCaseId);
+ if (
+ !current ||
+ current.topicId !== topicId ||
+ current.evalResult?.completionReason === 'aborted' ||
+ current.status === 'timeout'
+ ) {
+ return { threadId, topicId };
+ }
+ const executionId = crypto.randomUUID();
+ const claimed = await deps.executionRepo.claimExecution({
+ executionId,
+ expectedExecutionId: params.executionId,
+ runId,
+ testCaseId,
+ threadId,
+ topicId,
+ });
+ if (!claimed) return { threadId, topicId };
const caseId = getCaseId(params.testCase.metadata);
const aiAgentService = new AiAgentService(deps.db, deps.userId, {
@@ -154,45 +192,82 @@ export async function executeThreadTrajectory(
const webhookUrl = '/api/workflows/agent-eval-run/on-thread-complete';
const userId = deps.userId;
const db = deps.db;
+ const bindOperation = async (operationId: string) => {
+ const saved = await deps.executionRepo.updateThreadMetadata(
+ runId,
+ topicId,
+ threadId,
+ { operationId, testCaseId },
+ { executionId },
+ );
+ if (!saved) {
+ await interruptEvalOperations(deps, [operationId]);
+ throw new Error('Execution is no longer current');
+ }
+ };
try {
+ const memory = await prepareTrialMemory(deps, {
+ environment,
+ runId,
+ testCaseId,
+ threadId,
+ topicId,
+ });
const execResult = await aiAgentService.execAgent({
- agentId: run.targetAgentId ?? undefined,
- appContext: { threadId, topicId },
+ agentId: await resolveTopicAgentId(deps, topicId, run.targetAgentId),
+ // Eval dialogue must not feed Agent Signal (feedback, self-iteration, Memory writes).
+ appContext: { suppressSignal: true, threadId, topicId },
autoStart: true,
+ chatConfigOverride: contenderChatConfigOf(run),
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,
+ const { allRunDone } = await recordThreadCompletion(
+ createEvalRunDeps(db, userId, deps.workspaceId),
+ {
+ executionId,
+ 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,
},
- testCaseId,
- threadId,
- topicId,
- });
+ );
+ // Queue mode finalizes from the completion webhook; in-process runs
+ // have only this handler, so the run must be finalized here.
+ if (allRunDone) await AgentEvalRunWorkflow.triggerFinalizeRun({ runId, userId });
},
id: 'eval-thread-complete',
type: 'onComplete' as const,
webhook: {
- body: { runId, testCaseId, threadId, topicId, userId },
+ body: { executionId, runId, testCaseId, threadId, topicId, userId },
delivery: 'qstash' as const,
url: webhookUrl,
},
},
],
- ...getEvalContextParams(envPrompt, environment, caseId),
+ ...getEvalContextParams(
+ envPrompt,
+ environment,
+ caseId,
+ memory,
+ getEvalAttemptId({ runId, threadId, topicId }),
+ run.config?.connectorSnapshots?.[testCaseId],
+ ),
+ onOperationCreated: bindOperation,
maxSteps: run.config?.maxSteps,
prompt: params.testCase.content.input || '',
queueRetries: EVAL_AGENT_RUNTIME_QSTASH_RETRIES,
@@ -200,12 +275,7 @@ export async function executeThreadTrajectory(
userInterventionConfig: { approvalMode: 'headless' },
});
- // Write operationId to thread metadata
- if (execResult?.operationId) {
- await deps.threadModel.update(threadId, {
- metadata: { operationId: execResult.operationId, testCaseId },
- } as any);
- }
+ if (execResult?.operationId) await bindOperation(execResult.operationId);
return { threadId, topicId };
} catch (error) {
@@ -217,8 +287,11 @@ export async function executeThreadTrajectory(
);
// Mark the thread explicitly as error; aggregation and resume-target selection rely on metadata.status.
- await deps.threadModel.update(threadId, {
- metadata: {
+ await deps.executionRepo.updateThreadMetadata(
+ runId,
+ topicId,
+ threadId,
+ {
completedAt: new Date().toISOString(),
error: errorMessage,
passed: false,
@@ -226,9 +299,10 @@ export async function executeThreadTrajectory(
status: 'error',
testCaseId,
},
- } as any);
+ { executionId },
+ );
- return { error: errorMessage, threadId, topicId };
+ return { error: errorMessage, executionId, threadId, topicId };
}
}
@@ -240,6 +314,7 @@ export async function executeThreadTrajectory(
export async function recordThreadCompletion(
deps: EvalRunDeps,
params: {
+ executionId?: string;
runId: string;
status: string;
telemetry: {
@@ -258,29 +333,63 @@ export async function recordThreadCompletion(
},
): Promise<{ allRunDone: boolean; allThreadsDone: boolean }> {
const { runId, testCaseId, threadId, topicId, telemetry, status } = params;
+ const parent = await deps.runTopicModel.findByRunAndTestCase(runId, testCaseId);
+ if (
+ !parent ||
+ parent.topicId !== topicId ||
+ parent.evalResult?.completionReason === 'aborted' ||
+ parent.status === 'timeout'
+ ) {
+ return { allRunDone: false, allThreadsDone: false };
+ }
+
+ const attempt = await deps.threadModel.findById(threadId);
+ if (!attempt || attempt.metadata?.executionId !== params.executionId) {
+ return { allRunDone: false, allThreadsDone: false };
+ }
+ // 1. The attempt is over: record what this thread's Memory holds (an errored
+ // thread is snapshotted once it completes after a resume).
+ const memorySnapshot =
+ status === 'error' || status === 'timeout'
+ ? undefined
+ : await snapshotTrialMemory(deps, { runId, testCaseId, threadId, topicId });
+
+ // 2. Evaluate this thread's messages. A judge that throws before
+ // `evaluateThread` can record it is a judge failure, not a verdict.
+ let evalResult: Record<string, unknown>;
+ try {
+ evalResult = await evaluateThread(deps, {
+ memorySnapshot,
+ runId,
+ status,
+ telemetry,
+ testCaseId,
+ threadId,
+ topicId,
+ });
+ } catch (error) {
+ console.error(error);
+ evalResult = threadJudgeError(threadTelemetry(telemetry), judgeFailureMessage(error));
+ }
- // 1. Evaluate this thread's messages
- const evalResult = await evaluateThread(deps, {
+ // 3. Write eval result to thread.metadata
+ const saved = await deps.executionRepo.updateThreadMetadata(
runId,
- status,
- telemetry,
- testCaseId,
- threadId,
topicId,
- });
-
- // 2. Write eval result to thread.metadata
- await deps.threadModel.update(threadId, {
- metadata: {
+ threadId,
+ {
...evalResult,
+ executionId: params.executionId,
+ ...(memorySnapshot && { memorySnapshot }),
completedAt: new Date().toISOString(),
- // Normalize status into metadata so later aggregation can reconstruct threads[] consistently.
status: getThreadResultStatus(evalResult),
testCaseId,
},
- } as any);
+ { executionId: params.executionId },
+ );
+ if (!saved) return { allRunDone: false, allThreadsDone: false };
- // 3. Check if all K threads for this topic are done
+ // 4. 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) => {
@@ -297,6 +406,7 @@ export async function recordThreadCompletion(
// 4. All K threads done β€” aggregate into RunTopic
await aggregateThreadResults(deps, {
completedThreads: evalThreads,
+ expectedExecutionId: parent.evalResult?.executionId,
runId,
testCaseId,
topicId,
@@ -304,7 +414,7 @@ export async function recordThreadCompletion(
// 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 };
+ if (!run || run.status === 'aborted') return { allRunDone: false, allThreadsDone: true };
const totalCases = run.metrics?.totalCases;
if (!totalCases) return { allRunDone: false, allThreadsDone: true };
@@ -320,6 +430,7 @@ export async function recordThreadCompletion(
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;
+ const judgeErrorCases = allTopics.filter((t) => t.status === JUDGE_ERROR_STATUS).length;
let sumCost = 0;
let sumTokens = 0;
@@ -357,14 +468,16 @@ export async function recordThreadCompletion(
}
}
- await deps.runModel.update(runId, {
- metrics: {
+ await deps.runModel.updateProgress(
+ runId,
+ {
...(run.metrics as EvalRunMetrics),
completedCases: completedCount,
cost: sumCost ? roundCost(sumCost) : undefined,
errorCases,
externalCases: externalCasesRT || undefined,
failedCases,
+ judgeErrorCases: judgeErrorCases || undefined,
llmCalls: sumLlmCalls || undefined,
passedCases,
perCaseCost: sumCost && completedCount ? roundCost(sumCost / completedCount) : undefined,
@@ -388,9 +501,13 @@ export async function recordThreadCompletion(
totalDuration: actualTotalDuration || undefined,
totalTokens: actualTotalTokens || undefined,
},
- });
+ { startedAt: run.startedAt },
+ );
- return { allRunDone: completedCount >= totalCases, allThreadsDone: true };
+ const allRunDone = completedCount >= totalCases;
+ // The case's attempts all ended: a run with a concurrency limit starts its next waiting case.
+ if (!allRunDone) await refillQueuedCases(deps, runId, run.config);
+ return { allRunDone, allThreadsDone: true };
}
/**
@@ -416,22 +533,18 @@ async function evaluateThread(
testCaseId: string;
threadId: string;
topicId: string;
+ /** The thread's isolated Memory as it ended, shown to the LLM judge. */
+ memorySnapshot?: EvalMemorySnapshot;
},
): 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,
- };
+ const { memorySnapshot, runId, status, telemetry, testCaseId, threadId } = params;
- // Error case β€” skip evaluation
- if (status === 'error') {
+ const baseMeta = threadTelemetry(telemetry);
+
+ // Error case β€” skip evaluation. The status is kept so the aggregation and the
+ // UI tell an execution error (provider key, timeout, crash) from a model that
+ // ran and failed the rules.
+ if (status === 'error' || status === 'timeout') {
return {
...baseMeta,
error:
@@ -439,15 +552,17 @@ async function evaluateThread(
errorDetail: telemetry.errorDetail,
passed: false,
score: 0,
+ status,
};
}
- // Load run β†’ dataset β†’ benchmark for rubrics
+ // Load run β†’ dataset β†’ benchmark for rubrics. Missing grading context is a
+ // judge problem: the thread keeps its attempt and is re-judged, not failed.
const run = await deps.runModel.findById(runId);
- if (!run) return { ...baseMeta, error: 'Run not found', passed: false, score: 0 };
+ if (!run) return threadJudgeError(baseMeta, GRADING_CONTEXT_MISSING.run);
const dataset = await deps.datasetModel.findById(run.datasetId);
- if (!dataset) return { ...baseMeta, error: 'Dataset not found', passed: false, score: 0 };
+ if (!dataset) return threadJudgeError(baseMeta, GRADING_CONTEXT_MISSING.dataset);
// A dataset need not belong to a benchmark; such a dataset simply
// contributes no benchmark-level rubrics, and scoring falls back to the
@@ -458,7 +573,7 @@ async function evaluateThread(
: null;
const testCase = await deps.testCaseModel.findById(testCaseId);
- if (!testCase) return { ...baseMeta, error: 'Test case not found', passed: false, score: 0 };
+ if (!testCase) return threadJudgeError(baseMeta, GRADING_CONTEXT_MISSING.testCase);
const passThreshold = (run.config?.passThreshold as number) ?? 0.6;
@@ -468,13 +583,14 @@ async function evaluateThread(
const lastAssistantMsg = assistantMessages.at(-1);
if (!lastAssistantMsg || !lastAssistantMsg.content) {
- return {
- ...baseMeta,
- error: 'No assistant output',
- passed: false,
- rubricScores: [],
- score: 0,
- };
+ // Same reading as the topic path (see classifyEmptyAnswer).
+ const outcome = classifyEmptyAnswer({
+ completionReason: telemetry.completionReason,
+ lastAssistantMessage: lastAssistantMsg,
+ stepCap: run.config?.maxSteps as number | undefined,
+ steps: telemetry.steps,
+ });
+ return { ...baseMeta, ...outcome, passed: false, rubricScores: [], score: 0 };
}
// Resolve rubrics
@@ -494,37 +610,167 @@ async function evaluateThread(
let effectiveRubrics: EvalBenchmarkRubric[];
if (evalMode) {
- effectiveRubrics = [
- {
- config: (evalConfig ?? {}) as unknown as EvalBenchmarkRubric['config'],
- id: `eval-mode-${evalMode}`,
- name: evalMode,
- type: evalMode,
- weight: 1,
- },
- ];
+ effectiveRubrics = [buildEvalModeRubric(evalMode, evalConfig)];
} else {
effectiveRubrics = benchmark?.rubrics ?? [];
}
- // Run evaluation
- const result = await evaluate(
- { actual: lastAssistantMsg.content, rubrics: effectiveRubrics, testCase: testCase.content },
- { passThreshold },
- );
+ // Run evaluation. A judge that fails (throws, or reports `judgeError`)
+ // leaves the thread `judge_error` with its diagnostics; the thread's own
+ // output and telemetry stay, and a re-judge grades it again.
+ let result: EvaluateResult;
+ try {
+ const judge = await resolveEvalJudge(deps, {
+ benchmarkMetadata: benchmark?.metadata,
+ evalConfigs: [testCase.evalConfig, dataset.evalConfig],
+ runConfig: run.config,
+ });
+ const topic = await deps.topicModel.findById(params.topicId);
+ const historyTail = topic?.metadata?.[EVAL_HISTORY_TAIL_METADATA_KEY];
+ const historyTailMessageId = typeof historyTail === 'string' ? historyTail : undefined;
+ const evidence = buildJudgeEvidence({
+ historyTailMessageId,
+ memorySnapshot,
+ messages: await withSubAgentMessages(deps, { messages, topicId: params.topicId }),
+ });
+ const matchContext = createJudgeMatchContext(deps, judge, evidence);
+ baseMeta.judges = matchContext.judgeRequests;
+ const actual = attemptReply({ historyTailMessageId, messages }) || lastAssistantMsg.content;
+ result = await evaluate(
+ { actual, rubrics: effectiveRubrics, testCase: testCase.content },
+ { matchContext, passThreshold },
+ );
+ } catch (error) {
+ // The stored message is replaced by the next re-judge, so the server log
+ // is the only place the first failure's cause survives.
+ console.error(
+ `[eval-judge] Judge failed for run ${params.runId} topic ${params.topicId}:`,
+ error,
+ );
+ return threadJudgeError(baseMeta, judgeFailureMessage(error));
+ }
+ const judgeError = readJudgeError(result);
+ if (judgeError) {
+ console.error(
+ `[eval-judge] Judge reported an error for run ${params.runId} topic ${params.topicId}: ${judgeError}`,
+ );
+ return threadJudgeError(baseMeta, judgeError, result);
+ }
return {
...baseMeta,
+ // A verdict replaces any earlier judge failure of this thread.
+ judgeError: undefined,
passed: result.passed,
rubricScores: result.rubricResults.map((r) => ({
reason: r.reason,
rubricId: r.rubricId,
score: r.score,
+ ...(r.verdicts && { verdicts: r.verdicts }),
})),
score: result.score,
};
}
+const threadTelemetry = (telemetry: {
+ completionReason?: string;
+ cost?: number;
+ duration?: number;
+ llmCalls?: number;
+ steps?: number;
+ toolCalls?: number;
+ totalTokens?: number;
+}): 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,
+});
+
+/** Thread metadata for an attempt whose grading failed: no verdict, diagnostics kept. */
+const threadJudgeError = (
+ baseMeta: Record<string, unknown>,
+ judgeError: string,
+ result?: EvaluateResult,
+): Record<string, unknown> => ({
+ ...baseMeta,
+ judgeError,
+ passed: undefined,
+ rubricScores: judgeDiagnostics(result),
+ score: undefined,
+ status: JUDGE_ERROR_STATUS,
+});
+
+const REJUDGEABLE_THREAD_STATUSES = new Set(['passed', 'failed', JUDGE_ERROR_STATUS]);
+
+/**
+ * Grades every judged thread of a pass@k case again with the current judge
+ * setup, from the messages and Memory snapshot it recorded, then rebuilds the
+ * case's aggregate. Threads without a verdict (errors, timeouts) are kept.
+ */
+export async function rejudgeTopicThreads(
+ deps: EvalRunDeps,
+ params: { runId: string; testCaseId: string; topicId: string },
+): Promise<number> {
+ const { runId, testCaseId, topicId } = params;
+ const parent = await deps.runTopicModel.findByRunAndTestCase(runId, testCaseId);
+ const evalThreads = (await deps.threadModel.queryByTopicId(topicId)).filter(
+ (thread) => thread.type === 'eval',
+ );
+ let rejudged = 0;
+
+ for (const thread of evalThreads) {
+ const meta = (thread.metadata ?? {}) as Record<string, unknown>;
+ if (
+ !('completedAt' in meta) ||
+ !(REJUDGEABLE_THREAD_STATUSES.has(String(meta.status)) || isRegradableEmptyAnswer(meta))
+ ) {
+ continue;
+ }
+ const evalResult = await evaluateThread(deps, {
+ memorySnapshot: meta.memorySnapshot as EvalMemorySnapshot | undefined,
+ runId,
+ status: 'completed',
+ telemetry: {
+ completionReason: meta.completionReason as string | undefined,
+ cost: meta.cost as number | undefined,
+ duration: meta.duration as number | undefined,
+ llmCalls: meta.llmCalls as number | undefined,
+ steps: meta.steps as number | undefined,
+ toolCalls: meta.toolCalls as number | undefined,
+ totalTokens: meta.tokens as number | undefined,
+ },
+ testCaseId,
+ threadId: thread.id,
+ topicId,
+ });
+ await deps.executionRepo.updateThreadMetadata(
+ runId,
+ topicId,
+ thread.id,
+ { ...meta, ...evalResult, status: getThreadResultStatus(evalResult) },
+ { executionId: meta.executionId as string | undefined },
+ );
+ rejudged++;
+ }
+
+ const completedThreads = (await deps.threadModel.queryByTopicId(topicId)).filter((thread) => {
+ const meta = thread.metadata as Record<string, unknown> | null;
+ return thread.type === 'eval' && meta && 'completedAt' in meta;
+ });
+ await aggregateThreadResults(deps, {
+ completedThreads,
+ expectedExecutionId: parent?.evalResult?.executionId,
+ runId,
+ testCaseId,
+ topicId,
+ });
+ return rejudged;
+}
+
/**
* Aggregate all completed thread results into RunTopic.
* Writes threads[] array, plus top-level score/passed using pass@k logic.
@@ -532,6 +778,7 @@ async function evaluateThread(
async function aggregateThreadResults(
deps: EvalRunDeps,
params: {
+ expectedExecutionId?: string;
completedThreads: Array<{ id: string; metadata?: Record<string, unknown> | null }>;
runId: string;
testCaseId: string;
@@ -542,15 +789,20 @@ async function aggregateThreadResults(
// Build threads array from metadata
const threadResults: Array<{
+ executionId?: string;
completionReason?: string;
cost?: number;
duration?: number;
error?: string;
+ judgeError?: string;
+ judges?: EvalThreadResult['judges'];
llmCalls?: number;
+ memorySnapshot?: EvalMemorySnapshot;
+ operationId?: string;
passed?: boolean;
rubricScores?: Array<{ reason?: string; rubricId: string; score: number }>;
score?: number;
- status?: 'error' | 'external' | 'failed' | 'passed' | 'running' | 'timeout';
+ status?: EvalThreadResult['status'];
steps?: number;
threadId: string;
tokens?: number;
@@ -558,16 +810,22 @@ async function aggregateThreadResults(
}> = completedThreads.map((t) => {
const meta = (t.metadata ?? {}) as Record<string, unknown>;
return {
+ executionId: meta.executionId as string | undefined,
completionReason: meta.completionReason as string | undefined,
cost: meta.cost as number | undefined,
duration: meta.duration as number | undefined,
error: meta.error as string | undefined,
+ judgeError: meta.judgeError as string | undefined,
+ judges: meta.judges as EvalThreadResult['judges'],
llmCalls: meta.llmCalls as number | undefined,
+ // The attempt's Memory at the end, so a per-thread view can show it
+ // without reading thread.metadata.
+ memorySnapshot: meta.memorySnapshot as EvalMemorySnapshot | undefined,
+ operationId: meta.operationId as string | 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,
+ status: meta.status as EvalThreadResult['status'],
steps: meta.steps as number | undefined,
threadId: t.id,
tokens: meta.tokens as number | undefined,
@@ -575,17 +833,87 @@ async function aggregateThreadResults(
};
});
+ // Any invalid attempt makes the complete k-attempt estimate unavailable.
+ // Preserve successful attempts and all failure reasons without awarding a
+ // model verdict to the incomplete sample.
+ const errored = threadResults.filter(
+ (t) => t.status === 'error' || t.status === 'timeout' || t.error === 'No assistant output',
+ );
+ if (errored.length > 0) {
+ const status = errored.some((t) => t.status !== 'timeout') ? 'error' : 'timeout';
+ const messages = [
+ ...new Set(
+ errored.map(
+ (t) => t.error ?? (t.status === 'timeout' ? 'Execution timeout' : 'Execution error'),
+ ),
+ ),
+ ];
+ await deps.runTopicModel.updateByRunAndTopic(
+ runId,
+ topicId,
+ {
+ evalResult: {
+ executionId: params.expectedExecutionId,
+ completionReason: status,
+ error: `${errored.length} of ${threadResults.length} attempts failed to execute: ${messages.join('; ')}`,
+ threads: threadResults,
+ ...sumThreadTotals(threadResults),
+ } satisfies EvalRunTopicResult,
+ passed: null,
+ score: null,
+ status,
+ },
+ { executionId: params.expectedExecutionId },
+ );
+ return;
+ }
+
+ // ── A thread the judge could not grade: the case has no verdict yet. pass@k
+ // and pass^k are unknown until every thread is judged, so nothing is
+ // aggregated into passed/failed; the totals and per-thread results stay. ──
+ const unjudged = threadResults.filter((t) => t.status === JUDGE_ERROR_STATUS);
+ if (unjudged.length > 0) {
+ const totals = sumThreadTotals(threadResults);
+ await deps.runTopicModel.updateByRunAndTopic(
+ runId,
+ topicId,
+ {
+ evalResult: {
+ executionId: params.expectedExecutionId,
+ completionReason: 'completed',
+ errorPhase: 'judge',
+ judgeError: `${unjudged.length} of ${threadResults.length} attempts could not be judged: ${unjudged
+ .map((t) => t.judgeError ?? 'judge failed')
+ .join('; ')}`,
+ threads: threadResults,
+ ...totals,
+ } satisfies EvalRunTopicResult,
+ passed: null,
+ score: null,
+ status: JUDGE_ERROR_STATUS,
+ },
+ { executionId: params.expectedExecutionId },
+ );
+ return;
+ }
+
// ── 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',
- });
+ const hasExternal = threadResults.some((t) => t.status === 'external');
+ if (hasExternal) {
+ await deps.runTopicModel.updateByRunAndTopic(
+ runId,
+ topicId,
+ {
+ evalResult: {
+ executionId: params.expectedExecutionId,
+ awaitingExternalEval: true,
+ completionReason: 'external',
+ threads: threadResults,
+ } satisfies EvalRunTopicResult,
+ status: 'external',
+ },
+ { executionId: params.expectedExecutionId },
+ );
return;
}
@@ -598,7 +926,44 @@ async function aggregateThreadResults(
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
+ // 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: {
+ executionId: params.expectedExecutionId,
+ completionReason,
+ passAllK: allPassed,
+ passAtK: anyPassed,
+ threads: threadResults,
+ ...sumThreadTotals(threadResults),
+ } satisfies EvalRunTopicResult,
+ // pass@k: passed if any thread passed
+ passed: anyPassed,
+ score: bestScore,
+ status: anyPassed ? 'passed' : 'failed',
+ },
+ { executionId: params.expectedExecutionId },
+ );
+}
+
+/** Per-execution averages (primary fields) and cumulative totals across the K threads. */
+const sumThreadTotals = (
+ threadResults: Array<{
+ cost?: number;
+ duration?: number;
+ llmCalls?: number;
+ steps?: number;
+ tokens?: number;
+ toolCalls?: number;
+ }>,
+) => {
let totalCost = 0;
let totalDuration = 0;
let totalTokens = 0;
@@ -613,35 +978,16 @@ async function aggregateThreadResults(
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',
- });
-}
+ const k = Math.max(threadResults.length, 1);
+ return {
+ cost: totalCost ? roundCost(totalCost / k) : undefined,
+ duration: totalDuration ? totalDuration / k : undefined,
+ llmCalls: totalLlmCalls ? Math.round((totalLlmCalls / k) * 10) / 10 : undefined,
+ steps: totalSteps ? Math.round((totalSteps / k) * 10) / 10 : undefined,
+ 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,
+ };
+};
diff --git a/apps/server/src/services/agentEvalRun/trajectory.ts b/apps/server/src/services/agentEvalRun/trajectory.ts
index f05c5ec9435..d984d468054 100644
--- a/apps/server/src/services/agentEvalRun/trajectory.ts
+++ b/apps/server/src/services/agentEvalRun/trajectory.ts
@@ -2,33 +2,49 @@ import type { EvalCaseEnvironment, EvalRunConfig, EvalTestCaseMetadata } from '@
import { RequestTrigger } from '@lobechat/types';
import { AiAgentService } from '@/server/services/aiAgent';
+import { AgentEvalRunWorkflow } from '@/server/workflows/agentEvalRun';
+import { contenderChatConfigOf, resolveTopicAgentId } from './caseAgent';
+import { withResolvedEnvironment } from './caseEnvironment';
import { recordTrajectoryCompletion } from './completion';
+import { assertCaseConnectorBindings } from './connectorBindings';
import {
EVAL_AGENT_RUNTIME_QSTASH_RETRIES,
EVAL_AGENT_RUNTIME_QSTASH_RETRY_DELAY,
} from './constants';
import { createRunTopics } from './createRun';
import { createEvalRunDeps } from './deps';
+import { interruptEvalOperations } from './runLifecycle';
+import { prepareTrialMemory } from './trialMemory';
import type { EvalRunDeps } from './types';
-import { getCaseId, getEvalContextParams } from './utils';
+import { getCaseId, getEvalAttemptId, getEvalContextParams } from './utils';
export async function loadTrajectoryData(deps: EvalRunDeps, runId: string, testCaseId: string) {
- const run = await deps.runModel.findById(runId);
+ const run = await deps.runModel.findForCase(runId, testCaseId);
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 };
+ const rawTestCase = await deps.testCaseModel.findById(testCaseId);
+ if (!rawTestCase || rawTestCase.datasetId !== run.datasetId)
+ return { error: 'Test case not found' as const };
+ const testCase = await withResolvedEnvironment(deps, rawTestCase);
let envPrompt: string | undefined;
- let environment: EvalCaseEnvironment | undefined;
+ const environment = testCase.content.environment;
+ await assertCaseConnectorBindings(
+ deps,
+ run.datasetId,
+ environment,
+ run.config?.connectorSnapshots?.[testCaseId],
+ );
if (run.datasetId) {
const dataset = await deps.datasetModel.findById(run.datasetId);
envPrompt = dataset?.evalConfig?.envPrompt;
- environment = testCase.content.environment;
}
- return { envPrompt, environment, run, testCase };
+ // The resolved Environment already travels above. Repeating it in content
+ // duplicates frozen tool contracts in every JSON checkpoint and replay.
+ const { environment: _environment, ...content } = testCase.content;
+ return { envPrompt, environment, run, testCase: { ...testCase, content } };
}
export async function executeTrajectory(
@@ -90,8 +106,31 @@ async function executeTrajectoryCore(
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' });
+ await assertCaseConnectorBindings(
+ deps,
+ run.datasetId,
+ environment,
+ run.config?.connectorSnapshots?.[testCaseId],
+ );
+ const current = await deps.runTopicModel.findByRunAndTestCase(runId, testCaseId);
+ const executionId = crypto.randomUUID();
+ const claimed = await deps.executionRepo.claimExecution({
+ executionId,
+ expectedExecutionId: current?.evalResult?.executionId,
+ runId,
+ testCaseId,
+ topicId,
+ });
+ if (!claimed) return { cancelled: true, topicId };
+ const bindOperation = async (operationId: string) => {
+ const saved = await deps.runTopicModel.mergeExecutionResult(runId, topicId, executionId, {
+ operationId,
+ });
+ if (!saved) {
+ await interruptEvalOperations(deps, [operationId]);
+ throw new Error('Execution is no longer current');
+ }
+ };
const aiAgentService = new AiAgentService(deps.db, deps.userId, {
workspaceId: deps.workspaceId,
@@ -101,43 +140,62 @@ async function executeTrajectoryCore(
const db = deps.db;
try {
+ const memory = await prepareTrialMemory(deps, { environment, runId, testCaseId, topicId });
const execResult = await aiAgentService.execAgent({
- agentId: run.targetAgentId ?? undefined,
- appContext: { topicId },
+ agentId: await resolveTopicAgentId(deps, topicId, run.targetAgentId),
+ // Eval dialogue must not feed Agent Signal (feedback, self-iteration, Memory writes).
+ appContext: { suppressSignal: true, topicId },
autoStart: true,
+ chatConfigOverride: contenderChatConfigOf(run),
...(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,
+ const { allDone } = await recordTrajectoryCompletion(
+ createEvalRunDeps(db, userId, deps.workspaceId),
+ {
+ executionId,
+ topicId,
+ 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,
},
- testCaseId,
- });
+ );
+ // Queue mode finalizes from the completion webhook; in-process runs
+ // have only this handler, so the run must be finalized here.
+ if (allDone) await AgentEvalRunWorkflow.triggerFinalizeRun({ runId, userId });
},
id: 'eval-trajectory-complete',
type: 'onComplete' as const,
webhook: {
- body: { runId, testCaseId, userId },
+ body: { executionId, runId, testCaseId, topicId, userId },
delivery: 'qstash' as const,
url: webhookUrl,
},
},
],
- ...getEvalContextParams(envPrompt, environment, caseId),
+ ...getEvalContextParams(
+ envPrompt,
+ environment,
+ caseId,
+ memory,
+ getEvalAttemptId({ runId, topicId }),
+ run.config?.connectorSnapshots?.[testCaseId],
+ ),
+ onOperationCreated: bindOperation,
maxSteps: run.config?.maxSteps,
prompt: params.testCase.content.input || '',
queueRetries: EVAL_AGENT_RUNTIME_QSTASH_RETRIES,
@@ -146,9 +204,7 @@ async function executeTrajectoryCore(
});
if (execResult?.operationId) {
- await deps.runTopicModel.updateByRunAndTopic(runId, topicId, {
- evalResult: { operationId: execResult.operationId, rubricScores: [] },
- });
+ await bindOperation(execResult.operationId);
}
return { operationId: execResult?.operationId, topicId };
@@ -159,14 +215,24 @@ async function executeTrajectoryCore(
error,
);
- await deps.runTopicModel.updateByRunAndTopic(runId, topicId, {
- evalResult: { completionReason: 'error', error: errorMessage, rubricScores: [] },
- passed: false,
- score: 0,
- status: 'error',
- });
+ await deps.runTopicModel.updateByRunAndTopic(
+ runId,
+ topicId,
+ {
+ evalResult: {
+ executionId,
+ completionReason: 'error',
+ error: errorMessage,
+ rubricScores: [],
+ },
+ passed: false,
+ score: 0,
+ status: 'error',
+ },
+ { executionId },
+ );
- return { error: errorMessage, topicId };
+ return { error: errorMessage, executionId, topicId };
}
}
@@ -241,11 +307,19 @@ export async function executeTrajectoryOnDemand(
if (byId && byId.datasetId === run.datasetId) testCase = byId;
}
if (!testCase) throw new Error(`Test case not found for caseId=${caseId}`);
+ testCase = await withResolvedEnvironment(deps, testCase);
const testCaseId = testCase.id;
const dataset = await deps.datasetModel.findById(run.datasetId);
const envPrompt = dataset?.evalConfig?.envPrompt;
const environment = testCase.content.environment;
+ await assertCaseConnectorBindings(
+ deps,
+ run.datasetId,
+ environment,
+ run.config?.connectorSnapshots?.[testCaseId],
+ true,
+ );
// Idempotent re-run of a terminal case: drop only the old RunTopic
// association (the old Topic is preserved) and link a fresh one.
@@ -258,8 +332,13 @@ export async function executeTrajectoryOnDemand(
}
const topicId = (
- await createRunTopics(deps, runId, run.targetAgentId, [
- { content: testCase.content, id: testCaseId, sortOrder: testCase.sortOrder },
+ await createRunTopics(deps, run, [
+ {
+ content: testCase.content,
+ environmentId: testCase.environmentId,
+ id: testCaseId,
+ sortOrder: testCase.sortOrder,
+ },
])
)[0]!;
diff --git a/apps/server/src/services/agentEvalRun/trialMemory.ts b/apps/server/src/services/agentEvalRun/trialMemory.ts
new file mode 100644
index 00000000000..972f0109693
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/trialMemory.ts
@@ -0,0 +1,57 @@
+import type { EvalCaseEnvironment, EvalMemoryReference, EvalMemorySnapshot } from '@lobechat/types';
+
+import { AgentEvalMemoryService } from '@/server/services/agentEvalMemory';
+
+import type { EvalRunDeps } from './types';
+
+/**
+ * Memory of each eval attempt.
+ *
+ * Before an attempt runs, its own Memory entries are seeded from the case
+ * fixture (`environment.memory`, empty when absent); a pass@k thread is its
+ * own attempt. The Memory tool and persona injection of the attempt read and
+ * write only those entries, so attempts never see each other's writes and
+ * never touch the caller's memories. When the attempt completes, what its
+ * Memory holds is recorded on the result as a snapshot; the entries stay as
+ * evidence until the run is deleted.
+ */
+
+export interface TrialMemoryTarget {
+ environment?: EvalCaseEnvironment;
+ resume?: boolean;
+ runId: string;
+ testCaseId: string;
+ threadId?: string;
+ topicId: string;
+}
+
+export const prepareTrialMemory = (
+ deps: EvalRunDeps,
+ target: TrialMemoryTarget,
+): Promise<EvalMemoryReference> =>
+ new AgentEvalMemoryService(deps.db, deps.userId, deps.workspaceId).prepare({
+ fixture: target.environment?.memory ?? {},
+ resume: target.resume,
+ runId: target.runId,
+ testCaseId: target.testCaseId,
+ threadId: target.threadId,
+ topicId: target.topicId,
+ });
+
+/**
+ * What a completed attempt's Memory holds. A snapshot failure must not fail
+ * the attempt's grading; the entries themselves are still in the table.
+ */
+export const snapshotTrialMemory = async (
+ deps: EvalRunDeps,
+ target: Omit<TrialMemoryTarget, 'environment'>,
+): Promise<EvalMemorySnapshot | undefined> => {
+ try {
+ return await new AgentEvalMemoryService(deps.db, deps.userId, deps.workspaceId).snapshot(
+ target,
+ );
+ } catch (error) {
+ console.error('[agent-eval] failed to snapshot trial Memory', target, error);
+ return undefined;
+ }
+};
diff --git a/apps/server/src/services/agentEvalRun/types.ts b/apps/server/src/services/agentEvalRun/types.ts
index c861300ae58..c136d65751d 100644
--- a/apps/server/src/services/agentEvalRun/types.ts
+++ b/apps/server/src/services/agentEvalRun/types.ts
@@ -3,6 +3,7 @@ import type { LobeChatDatabase } from '@lobechat/database';
import type {
AgentEvalBenchmarkModel,
AgentEvalDatasetModel,
+ AgentEvalEnvironmentModel,
AgentEvalExperimentModel,
AgentEvalRunModel,
AgentEvalRunTopicModel,
@@ -11,6 +12,7 @@ import type {
import type { MessageModel } from '@/database/models/message';
import type { ThreadModel } from '@/database/models/thread';
import type { TopicModel } from '@/database/models/topic';
+import type { AgentEvalExecutionRepo } from '@/database/repositories/agentEvalExecution';
import type { AgentService } from '@/server/services/agent';
/**
@@ -23,6 +25,8 @@ export interface EvalRunDeps {
benchmarkModel: AgentEvalBenchmarkModel;
datasetModel: AgentEvalDatasetModel;
db: LobeChatDatabase;
+ environmentModel: AgentEvalEnvironmentModel;
+ executionRepo: AgentEvalExecutionRepo;
experimentModel: AgentEvalExperimentModel;
messageModel: MessageModel;
runModel: AgentEvalRunModel;
diff --git a/apps/server/src/services/agentEvalRun/utils.test.ts b/apps/server/src/services/agentEvalRun/utils.test.ts
new file mode 100644
index 00000000000..9b77219e9b6
--- /dev/null
+++ b/apps/server/src/services/agentEvalRun/utils.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ EVAL_INFRASTRUCTURE_TOOLS,
+ getEvalAllowedTools,
+ getEvalAttemptId,
+ getEvalContextParams,
+} from './utils';
+
+describe('getEvalContextParams', () => {
+ it('passes nothing when the case has no env prompt and no clock', () => {
+ expect(getEvalContextParams(undefined, {}, 'case-1')).toEqual({
+ evalRuntime: { caseId: 'case-1' },
+ });
+ });
+
+ it('carries the case clock and timezone without an env prompt', () => {
+ expect(
+ getEvalContextParams(undefined, { sessionDate: '2026-07-21', timezone: 'Asia/Shanghai' }),
+ ).toEqual({ evalContext: { sessionDate: '2026-07-21', timezone: 'Asia/Shanghai' } });
+ });
+
+ it('merges dataset and case env prompts next to the clock', () => {
+ expect(
+ getEvalContextParams('Dataset note', { envPrompt: 'Case note', sessionDate: '2026-07-21' }),
+ ).toEqual({
+ evalContext: { envPrompt: 'Dataset note\n\nCase note', sessionDate: '2026-07-21' },
+ });
+ });
+
+ it('carries the attempt id into the eval runtime', () => {
+ expect(getEvalContextParams(undefined, {}, 'case-1', undefined, 'run_1_tpc_1')).toMatchObject({
+ evalRuntime: { attemptId: 'run_1_tpc_1', caseId: 'case-1' },
+ });
+ });
+
+ it('sets the tool allowlist only for a case that declares its agent tools', () => {
+ expect(getEvalContextParams(undefined, { sessionDate: '2026-07-24' }, 'case-1')).toEqual({
+ evalContext: { sessionDate: '2026-07-24' },
+ evalRuntime: { caseId: 'case-1' },
+ });
+ expect(
+ getEvalContextParams(undefined, { agent: { plugins: ['notion'] } }, 'case-1'),
+ ).toMatchObject({
+ evalRuntime: { allowedTools: ['notion', ...EVAL_INFRASTRUCTURE_TOOLS], caseId: 'case-1' },
+ });
+ });
+});
+
+describe('getEvalAllowedTools', () => {
+ it('is undefined for a case without a declared tool list', () => {
+ expect(getEvalAllowedTools(undefined)).toBeUndefined();
+ expect(getEvalAllowedTools({ mock: { services: ['notion'] } })).toEqual([
+ 'notion',
+ ...EVAL_INFRASTRUCTURE_TOOLS,
+ ]);
+ });
+
+ it('unions declared plugins, mocked services, forwarded tools and the infrastructure tools', () => {
+ expect(
+ getEvalAllowedTools({
+ agent: { plugins: ['notion', 'lobe-web-browsing'] },
+ mock: { services: ['notion', 'lobe-web-browsing'] },
+ toolForwarding: { gmail: { endpoint: 'http://mock/exec' } },
+ }),
+ ).toEqual(['notion', 'lobe-web-browsing', 'gmail', ...EVAL_INFRASTRUCTURE_TOOLS]);
+ });
+
+ it('keeps only the infrastructure tools for a case that disables tools', () => {
+ expect(getEvalAllowedTools({ agent: { plugins: [] } })).toEqual(EVAL_INFRASTRUCTURE_TOOLS);
+ });
+});
+
+describe('getEvalAttemptId', () => {
+ it('names a case attempt by run and topic, and a pass@k attempt by its thread too', () => {
+ expect(getEvalAttemptId({ runId: 'run_1', topicId: 'tpc_1' })).toBe('run_1_tpc_1');
+ expect(getEvalAttemptId({ runId: 'run_1', threadId: 'thr_1', topicId: 'tpc_1' })).toBe(
+ 'run_1_tpc_1_thr_1',
+ );
+ // Null stays out so a resumed topic attempt keeps the same id.
+ expect(getEvalAttemptId({ runId: 'run_1', threadId: null, topicId: 'tpc_1' })).toBe(
+ 'run_1_tpc_1',
+ );
+ });
+});
diff --git a/apps/server/src/services/agentEvalRun/utils.ts b/apps/server/src/services/agentEvalRun/utils.ts
index 7a011c33f9f..42f3752586b 100644
--- a/apps/server/src/services/agentEvalRun/utils.ts
+++ b/apps/server/src/services/agentEvalRun/utils.ts
@@ -1,25 +1,102 @@
-import type { EvalCaseEnvironment, EvalTestCaseMetadata } from '@lobechat/types';
+import type {
+ EvalCaseEnvironment,
+ EvalConnectorSnapshots,
+ EvalTestCaseMetadata,
+} from '@lobechat/types';
import debug from 'debug';
import type { EvalRuntimeContext } from '@/server/services/agentRuntime/types';
+import { EVAL_INFRASTRUCTURE_TOOLS } from './constants';
+
+export { EVAL_INFRASTRUCTURE_TOOLS } from './constants';
+
/** Round cost to at most 6 decimal places to avoid floating-point noise */
export const roundCost = (v: number): number => Math.round(v * 1e6) / 1e6;
+/**
+ * Identity of one eval attempt: a case run, or one pass@k thread of it. It is
+ * derived, not stored, so a resumed attempt keeps it and a retried case (new
+ * topic) gets a new one. Sub-agents inherit it; mocks key their session on it.
+ */
+export const getEvalAttemptId = ({
+ runId,
+ threadId,
+ topicId,
+}: {
+ runId: string;
+ threadId?: string | null;
+ topicId: string;
+}) => [runId, topicId, threadId].filter(Boolean).join('_');
+
+/**
+ * The tool allowlist of a case that declares its own agent tools: those
+ * plugins, every mocked service and every forwarded tool, plus the
+ * infrastructure tools. `undefined` when the case declares no tool list, so a
+ * run on a real Agent keeps that Agent's tools.
+ */
+export const getEvalAllowedTools = (environment?: EvalCaseEnvironment): string[] | undefined => {
+ const declared = environment?.agent?.plugins;
+ const requiredMocks = [
+ ...(environment?.mock?.services ?? []),
+ ...Object.keys(environment?.toolForwarding ?? {}),
+ ];
+ const boundIdentifiers = Object.keys(environment?.connectorBindings ?? {}).filter(
+ (identifier) =>
+ (!environment?.mock && !environment?.toolForwarding) || requiredMocks.includes(identifier),
+ );
+ if (
+ !Array.isArray(declared) &&
+ !environment?.connectorBindings &&
+ !environment?.mock?.services?.length &&
+ !environment?.toolForwarding
+ )
+ return undefined;
+ return [
+ ...new Set([
+ ...(declared ?? []),
+ ...boundIdentifiers,
+ ...(environment?.mock?.services ?? []),
+ ...Object.keys(environment?.toolForwarding ?? {}),
+ ...EVAL_INFRASTRUCTURE_TOOLS,
+ ]),
+ ];
+};
+
export const getEvalContextParams = (
envPrompt?: string,
environment?: EvalCaseEnvironment,
caseId?: string,
+ memory?: EvalRuntimeContext['memory'],
+ attemptId?: string,
+ connectorSnapshots?: EvalConnectorSnapshots,
) => {
const mergedEnvPrompt =
[envPrompt, environment?.envPrompt].filter(Boolean).join('\n\n') || undefined;
+ const evalContext =
+ mergedEnvPrompt || environment?.sessionDate
+ ? {
+ ...(mergedEnvPrompt && { envPrompt: mergedEnvPrompt }),
+ ...(environment?.sessionDate && {
+ sessionDate: environment.sessionDate,
+ ...(environment.timezone && { timezone: environment.timezone }),
+ }),
+ }
+ : undefined;
+ const allowedTools = getEvalAllowedTools(environment);
const evalRuntime: EvalRuntimeContext | undefined =
- caseId || environment?.toolForwarding
- ? { ...(caseId && { caseId }), toolForwarding: environment?.toolForwarding }
+ caseId || connectorSnapshots || memory || attemptId || allowedTools
+ ? {
+ ...(allowedTools && { allowedTools }),
+ ...(attemptId && { attemptId }),
+ ...(caseId && { caseId }),
+ ...(memory && { memory }),
+ ...(connectorSnapshots && { connectorSnapshots }),
+ }
: undefined;
return {
- ...(mergedEnvPrompt && { evalContext: { envPrompt: mergedEnvPrompt } }),
+ ...(evalContext && { evalContext }),
...(evalRuntime && { evalRuntime }),
};
};
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/evalToolForwarding.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/evalToolForwarding.test.ts
deleted file mode 100644
index c2ae56eb352..00000000000
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/evalToolForwarding.test.ts
+++ /dev/null
@@ -1,266 +0,0 @@
-/**
- * @vitest-environment node
- */
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { hookDispatcher } from '../../hooks';
-import { AgentRuntimeService, createEvalToolForwardingHook } from '..';
-import { setUpService } from './testUtils';
-
-vi.mock('@lobechat/model-runtime', (...args) =>
- import('./testUtils').then((m) =>
- (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),
- ),
-);
-
-const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));
-
-vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));
-
-// Mock trusted client to avoid server-side env access
-vi.mock('@/libs/trusted-client', (...args) =>
- import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),
-);
-
-// Mock database and models
-vi.mock('@/server/services/file', (...args) =>
- import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),
-);
-
-vi.mock('@/database/models/message', (...args) =>
- import('./testUtils').then((m) =>
- (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),
- ),
-);
-
-vi.mock('@/database/models/agent', (...args) =>
- import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),
-);
-
-vi.mock('@/database/models/plugin', (...args) =>
- import('./testUtils').then((m) =>
- (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),
- ),
-);
-
-// Mock ModelRuntime to avoid server-side env access
-vi.mock('@/server/modules/ModelRuntime', (...args) =>
- import('./testUtils').then((m) =>
- (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),
- ),
-);
-
-// Mock search service to avoid server-side env access
-vi.mock('@/server/services/search', (...args) =>
- import('./testUtils').then((m) =>
- (m.serverServicesSearchModule as (...a: any[]) => any)(...args),
- ),
-);
-
-// Mock factory and redis dependencies to break env import chains,
-// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends
-vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>
- import('./testUtils').then((m) =>
- (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),
- ),
-);
-
-vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>
- import('./testUtils').then((m) =>
- (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),
- ),
-);
-
-// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports
-vi.mock('@/server/modules/AgentRuntime', (...args) =>
- import('./testUtils').then((m) =>
- (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),
- ),
-);
-
-// Spread the real module and override only `AgentRuntime` (to stub `.step()`).
-// Keeps the real status predicates + package-hosted executors (e.g. `finish`),
-// so this mock survives future executor migrations without edits.
-vi.mock('@lobechat/agent-runtime', (...args) =>
- import('./testUtils').then((m) =>
- (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),
- ),
-);
-
-vi.mock('@/server/services/queue', (...args) =>
- import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),
-);
-
-// Mock Mecha module
-vi.mock('@/server/modules/Mecha', (...args) =>
- import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),
-);
-
-// Mock model-bank
-vi.mock('model-bank', (...args) =>
- import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),
-);
-
-describe('AgentRuntimeService', () => {
- const mockUserId = 'test-user-id';
-
- beforeEach(() => {
- setUpService(AgentRuntimeService, mockUserId);
- });
-
- afterEach(() => {
- vi.unstubAllEnvs();
- delete process.env.AGENT_RUNTIME_BASE_URL;
- hookDispatcher.unregister('test-operation-1');
- });
-
- describe('eval tool forwarding hook', () => {
- const event = {
- apiName: 'search_tweets',
- args: { query: 'test' },
- callIndex: 2,
- identifier: 'twitter',
- mock: vi.fn(),
- operationId: 'op-forwarding',
- stepIndex: 3,
- };
-
- beforeEach(() => {
- event.mock.mockReset();
- mockSsrfSafeFetch.mockReset();
- });
-
- it('forwards the beforeToolCall payload and preserves the returned tool result', async () => {
- const timeoutSpy = vi.spyOn(global, 'setTimeout');
- const result = { content: 'fixture result', state: { source: 'mock' }, success: true };
- mockSsrfSafeFetch.mockResolvedValue(
- new Response(JSON.stringify({ data: result, success: true })),
- );
- const hook = createEvalToolForwardingHook({
- twitter: { endpoint: 'https://mock.test/tool-calls' },
- });
-
- await hook.handler!(event as any);
-
- expect(mockSsrfSafeFetch).toHaveBeenCalledWith(
- 'https://mock.test/tool-calls',
- expect.objectContaining({ method: 'POST' }),
- );
- expect(JSON.parse(mockSsrfSafeFetch.mock.calls[0][1].body)).toEqual({
- data: { apiName: 'search_tweets', args: { query: 'test' }, identifier: 'twitter' },
- metadata: { callIndex: 2, operationId: 'op-forwarding', stepIndex: 3 },
- type: 'toolCall',
- });
- expect(timeoutSpy).toHaveBeenCalledWith(expect.any(Function), 15_000);
- expect(event.mock).toHaveBeenCalledWith(result);
- timeoutSpy.mockRestore();
- });
-
- it('includes the dataset case id in forwarding metadata', async () => {
- const result = { content: 'fixture result', success: true };
- mockSsrfSafeFetch.mockResolvedValue(
- new Response(JSON.stringify({ data: result, success: true })),
- );
- const hook = createEvalToolForwardingHook(
- { twitter: { endpoint: 'https://mock.test/tool-calls' } },
- 'case-42',
- );
-
- await hook.handler!(event as any);
-
- expect(JSON.parse(mockSsrfSafeFetch.mock.calls[0][1].body)).toMatchObject({
- metadata: { caseId: 'case-42' },
- });
- });
-
- it('mocks a failed result without executing the real tool', async () => {
- mockSsrfSafeFetch.mockResolvedValue(
- new Response(JSON.stringify({ error: 'fixture unavailable', success: false })),
- );
- const hook = createEvalToolForwardingHook({
- twitter: { endpoint: 'https://mock.test/tool-calls' },
- });
-
- await hook.handler!(event as any);
-
- expect(event.mock).toHaveBeenCalledWith({
- content: 'fixture unavailable',
- error: 'fixture unavailable',
- success: false,
- });
- });
-
- it('mocks a placeholder when a successful response has no tool result', async () => {
- mockSsrfSafeFetch.mockResolvedValue(new Response(JSON.stringify({ success: true })));
- const hook = createEvalToolForwardingHook({
- twitter: { endpoint: 'https://mock.test/tool-calls' },
- });
-
- await hook.handler!(event as any);
-
- expect(event.mock).toHaveBeenCalledWith({ content: 'No tool result', success: true });
- });
-
- it('mocks a placeholder when a successful response has an invalid tool result', async () => {
- mockSsrfSafeFetch.mockResolvedValue(
- new Response(JSON.stringify({ data: { content: 1, success: true }, success: true })),
- );
- const hook = createEvalToolForwardingHook({
- twitter: { endpoint: 'https://mock.test/tool-calls' },
- });
-
- await hook.handler!(event as any);
-
- expect(event.mock).toHaveBeenCalledWith({ content: 'No tool result', success: true });
- });
-
- it('mocks a failed result when the forwarding response is not JSON', async () => {
- mockSsrfSafeFetch.mockResolvedValue(new Response('not-json'));
- const hook = createEvalToolForwardingHook({
- twitter: { endpoint: 'https://mock.test/tool-calls' },
- });
-
- await hook.handler!(event as any);
-
- expect(event.mock).toHaveBeenCalledWith({
- content: expect.stringContaining('SyntaxError'),
- error: expect.any(SyntaxError),
- success: false,
- });
- });
-
- it('releases the unread body of a non-2xx forwarding response', async () => {
- const cancel = vi.fn();
- mockSsrfSafeFetch.mockResolvedValue(
- new Response(new ReadableStream({ cancel, pull: () => new Promise(() => {}) }), {
- status: 503,
- }),
- );
- const hook = createEvalToolForwardingHook({
- twitter: { endpoint: 'https://mock.test/tool-calls' },
- });
-
- await hook.handler!(event as any);
-
- expect(event.mock).toHaveBeenCalledWith(
- expect.objectContaining({ content: expect.stringContaining('HTTP 503'), success: false }),
- );
- expect(cancel).toHaveBeenCalled();
- });
-
- it('mocks transport failures', async () => {
- mockSsrfSafeFetch.mockRejectedValue('SSRF blocked');
- const hook = createEvalToolForwardingHook({
- twitter: { endpoint: 'https://mock.test/tool-calls' },
- });
-
- await hook.handler!(event as any);
-
- expect(event.mock).toHaveBeenCalledWith({
- content: 'SSRF blocked',
- error: 'SSRF blocked',
- success: false,
- });
- });
- });
-});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/evalToolGateHook.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/evalToolGateHook.test.ts
new file mode 100644
index 00000000000..9ebd12f7a56
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/evalToolGateHook.test.ts
@@ -0,0 +1,56 @@
+import type { ToolRunResult } from '@lobechat/agent-runtime';
+import { describe, expect, it, vi } from 'vitest';
+
+import { EVAL_TOOL_GATE_HOOK_ID } from '../constants';
+import { createEvalToolGateHook, EVAL_TOOL_BLOCKED_ERROR } from '../evalToolGateHook';
+
+const call = (identifier: string, apiName = 'search') => {
+ const mock = vi.fn<(result: ToolRunResult) => boolean>(() => true);
+ const event = {
+ apiName,
+ args: {},
+ callIndex: 1,
+ identifier,
+ mock,
+ operationId: 'op_1',
+ stepIndex: 0,
+ };
+ return { event, mock };
+};
+
+const run = async (allowed: string[], identifier: string, apiName?: string) => {
+ const hook = createEvalToolGateHook(allowed);
+ const { event, mock } = call(identifier, apiName);
+ await hook.handler!(event as any);
+ return mock;
+};
+
+describe('createEvalToolGateHook', () => {
+ it('is a beforeToolCall hook with a stable id', () => {
+ const hook = createEvalToolGateHook(['notion']);
+ expect(hook.type).toBe('beforeToolCall');
+ expect(hook.id).toBe(EVAL_TOOL_GATE_HOOK_ID);
+ });
+
+ it('lets a declared tool through untouched', async () => {
+ const mock = await run(['notion', 'lobe-activator'], 'notion');
+ expect(mock).not.toHaveBeenCalled();
+ });
+
+ it("refuses a tool the case did not declare with the harness's error", async () => {
+ const mock = await run(['notion'], 'gmail', 'gmail_search_emails');
+ expect(mock).toHaveBeenCalledTimes(1);
+ const result = mock.mock.calls[0]?.[0];
+ expect(result?.success).toBe(false);
+ expect(JSON.parse(String(result?.content))).toEqual({
+ error: EVAL_TOOL_BLOCKED_ERROR,
+ message: "gmail is not part of this case's environment.",
+ requested: 'gmail/gmail_search_emails',
+ });
+ });
+
+ it('refuses everything when the case declares no tools', async () => {
+ const mock = await run([], 'lobe-local-system', 'runCommand');
+ expect(mock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/constants.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/constants.ts
index 85011799b60..5bd8a87f4fc 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/constants.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/constants.ts
@@ -47,6 +47,8 @@ export const DURABLE_LEASE_HEARTBEAT_EVERY_TICKS = 3;
* heartbeat cadence (STEP_LOCK_HEARTBEAT_MS Γ— DURABLE_LEASE_HEARTBEAT_EVERY_TICKS).
*/
export const DEAD_OPERATION_LEASE_MS = 10 * 60 * 1000;
+/** Refuses tool calls outside an eval attempt's allowlist (see createEvalToolGateHook). */
+export const EVAL_TOOL_GATE_HOOK_ID = 'eval-tool-gate';
export const EVAL_TOOL_FORWARDING_HOOK_ID = 'eval-tool-forwarding';
export const INTERVENTION_LIFECYCLE_CHECKPOINT_KEY = '_agentInterventionLifecycle';
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/evalConnectorHook.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/evalConnectorHook.test.ts
new file mode 100644
index 00000000000..f53fa1e83a5
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/evalConnectorHook.test.ts
@@ -0,0 +1,93 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ AgentEvalConnectorService,
+ EvalConnectorBindingError,
+} from '@/server/services/agentEvalConnector';
+
+import { createEvalConnectorHook } from './evalConnectorHook';
+
+const deps = { db: {} as never, userId: 'user' };
+const snapshots = {
+ notion: {
+ connectorId: 'connector-id',
+ datasetId: 'dataset',
+ fingerprint: 'contract',
+ transport: 'mcp' as const,
+ },
+};
+const event = () => ({
+ apiName: 'search',
+ args: { query: 'fixture' },
+ callIndex: 1,
+ identifier: 'notion',
+ mock: vi.fn(),
+ operationId: 'op',
+ stepIndex: 1,
+});
+afterEach(() => vi.restoreAllMocks());
+
+describe('evaluation connection hook', () => {
+ it('executes a bound call and supplies its result instead of the ordinary tool executor', async () => {
+ const execute = vi
+ .spyOn(AgentEvalConnectorService.prototype, 'execute')
+ .mockResolvedValue({ content: 'mock-data', success: true });
+ const hook = createEvalConnectorHook(deps, snapshots, { attemptId: 'attempt', caseId: 'case' });
+ const call = event();
+ await hook.handler!(call as never);
+ expect(call.mock).toHaveBeenCalledWith({ content: 'mock-data', success: true });
+ expect(execute.mock.calls[0][2].args).toBe('{"query":"fixture"}');
+ });
+
+ it('fails closed for a persisted legacy forwarding plan', async () => {
+ const execute = vi.spyOn(AgentEvalConnectorService.prototype, 'execute');
+ const hook = createEvalConnectorHook(deps, {}, { legacyIdentifiers: ['notion'] });
+ const call = event();
+ await hook.handler!(call as never);
+ expect(call.mock).toHaveBeenCalledWith({
+ content: 'The tool connection is unavailable.',
+ success: false,
+ });
+ expect(execute).not.toHaveBeenCalled();
+ });
+
+ it('intercepts legacy snapshots without falling through to the ordinary tool executor', async () => {
+ const execute = vi.spyOn(AgentEvalConnectorService.prototype, 'execute');
+ const hook = createEvalConnectorHook(
+ deps,
+ { notion: { ...snapshots.notion, datasetId: undefined } },
+ {},
+ );
+ const call = event();
+ await hook.handler!(call as never);
+ expect(call.mock).toHaveBeenCalledWith({
+ content: 'The tool connection is unavailable. Please try again later.',
+ success: false,
+ });
+ expect(execute).not.toHaveBeenCalled();
+ });
+
+ it('leaves unrelated tools to the ordinary executor', async () => {
+ const hook = createEvalConnectorHook(deps, snapshots, {});
+ const call = { ...event(), identifier: 'lobe-agent' };
+ await hook.handler!(call as never);
+ expect(call.mock).not.toHaveBeenCalled();
+ });
+
+ it('does not expose provider credentials in errors or evaluation routing details in errors', async () => {
+ const execute = vi.spyOn(AgentEvalConnectorService.prototype, 'execute');
+ const hook = createEvalConnectorHook(deps, snapshots, {});
+ const call = event();
+ execute.mockRejectedValueOnce(new Error('secret-token in https://private.test'));
+ await hook.handler!(call as never);
+ expect(JSON.stringify(call.mock.mock.calls)).not.toMatch(/secret-token|private.test/);
+ execute.mockRejectedValueOnce(
+ new EvalConnectorBindingError('The mock connection or its tools changed.'),
+ );
+ await hook.handler!(call as never);
+ expect(call.mock).toHaveBeenLastCalledWith({
+ content: 'The tool connection is unavailable. Please try again later.',
+ success: false,
+ });
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/evalConnectorHook.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/evalConnectorHook.ts
new file mode 100644
index 00000000000..da8241f8d8a
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/evalConnectorHook.ts
@@ -0,0 +1,69 @@
+import type { ToolCallHookEvent } from '@lobechat/agent-runtime';
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { EvalConnectorSnapshots } from '@lobechat/types';
+import debug from 'debug';
+
+import {
+ AgentEvalConnectorService,
+ getEvalConnectorDatasetId,
+} from '@/server/services/agentEvalConnector';
+
+import type { AgentHook } from '../hooks';
+
+const log = debug('lobe-server:eval-connector-hook');
+
+export const EVAL_CONNECTOR_HOOK_ID = 'eval-connector-bindings';
+
+/** Credentials stay in connection storage and are resolved afresh for each call. */
+export const createEvalConnectorHook = (
+ deps: { db: LobeChatDatabase; userId: string; workspaceId?: string },
+ snapshots: EvalConnectorSnapshots,
+ context: { attemptId?: string; caseId?: string; legacyIdentifiers?: string[] },
+): AgentHook => ({
+ handler: async (event) => {
+ const { apiName, args, callIndex, identifier, mock, operationId, stepIndex } =
+ event as unknown as ToolCallHookEvent;
+ if (!Object.hasOwn(snapshots, identifier)) {
+ if (context.legacyIdentifiers?.includes(identifier)) {
+ mock({
+ content: 'The tool connection is unavailable.',
+ success: false,
+ });
+ }
+ return;
+ }
+ try {
+ const service = new AgentEvalConnectorService(
+ deps.db,
+ deps.userId,
+ getEvalConnectorDatasetId(snapshots),
+ deps.workspaceId,
+ );
+ const result = await service.execute(identifier, snapshots, {
+ apiName,
+ args: typeof args === 'string' ? args : JSON.stringify(args),
+ attemptId: context.attemptId,
+ callIndex,
+ caseId: context.caseId,
+ operationId,
+ stepIndex,
+ });
+ mock(result);
+ } catch (error) {
+ log(
+ 'call failed connector=%s case=%s api=%s errorType=%s',
+ snapshots[identifier]?.connectorId,
+ context.caseId,
+ apiName,
+ error instanceof Error ? error.name : typeof error,
+ );
+ // Provider errors can contain URLs and headers; expose only our safe diagnostics.
+ mock({
+ content: 'The tool connection is unavailable. Please try again later.',
+ success: false,
+ });
+ }
+ },
+ id: EVAL_CONNECTOR_HOOK_ID,
+ type: 'beforeToolCall',
+});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/evalToolForwardingHook.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/evalToolForwardingHook.ts
deleted file mode 100644
index 264966c8301..00000000000
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/evalToolForwardingHook.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import type {
- ToolCallHookEvent,
- ToolForwardingRequest,
- ToolRunResult,
-} from '@lobechat/agent-runtime';
-import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
-import { type EvalToolForwardingConfig } from '@lobechat/types';
-import { isRecord } from '@lobechat/utils/object';
-
-import { type AgentHook } from '../hooks';
-import { EVAL_TOOL_FORWARDING_HOOK_ID } from './constants';
-
-export const toToolForwardingFailure = (error?: unknown): ToolRunResult => ({
- content: error === undefined ? 'Tool forwarding failed' : String(error),
- error,
- success: false,
-});
-
-export const createEvalToolForwardingHook = (
- toolForwarding: EvalToolForwardingConfig,
- caseId?: string,
-): AgentHook => ({
- handler: async (event) => {
- const { apiName, args, callIndex, identifier, mock, operationId, stepIndex } =
- event as unknown as ToolCallHookEvent;
- const target = toolForwarding[identifier];
- if (!target) return;
-
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), target.timeoutMs ?? 15_000);
-
- try {
- const payload: ToolForwardingRequest = {
- data: { apiName, args, identifier },
- metadata: { ...(caseId && { caseId }), callIndex, operationId, stepIndex },
- type: 'toolCall',
- };
- const response = await ssrfSafeFetch(target.endpoint, {
- body: JSON.stringify(payload),
- headers: { 'Content-Type': 'application/json' },
- method: 'POST',
- signal: controller.signal,
- });
- if (!response.ok) {
- // The error body is never read; release its connection now rather than at GC.
- await response.body?.cancel().catch(() => {});
- throw `Tool forwarding server responded with HTTP ${response.status}`;
- }
-
- const body: unknown = await response.json();
- if (!isRecord(body)) throw new Error('Invalid tool forwarding response');
-
- if (body.success === true) {
- const result = body.data;
- if (
- isRecord(result) &&
- typeof result.content === 'string' &&
- typeof result.success === 'boolean'
- ) {
- mock({ ...result, content: result.content, success: result.success });
- } else {
- mock({ content: 'No tool result', success: true });
- }
- } else {
- mock(toToolForwardingFailure(body.error));
- }
- } catch (error) {
- mock(toToolForwardingFailure(error));
- } finally {
- clearTimeout(timeout);
- }
- },
- id: EVAL_TOOL_FORWARDING_HOOK_ID,
- type: 'beforeToolCall',
-});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/evalToolGateHook.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/evalToolGateHook.ts
new file mode 100644
index 00000000000..33ba8409fec
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/evalToolGateHook.ts
@@ -0,0 +1,35 @@
+import type { ToolCallHookEvent } from '@lobechat/agent-runtime';
+
+import { type AgentHook } from '../hooks';
+import { EVAL_TOOL_GATE_HOOK_ID } from './constants';
+
+/** What the model reads when it calls a tool the case did not give it (the eval harness's wording). */
+export const EVAL_TOOL_BLOCKED_ERROR = 'external_tool_blocked_by_eval';
+
+/**
+ * Dispatch-time half of the eval tool gate: a call to an identifier outside
+ * the attempt's allowlist never executes and never leaves the sandbox; the
+ * model gets the same refusal the eval harness gave. The operation's tool set
+ * is already pruned to the allowlist (`applyEvalGateToToolSet`), so this only
+ * catches what slips past assembly: a name recalled from history, a guess, or
+ * a tool re-activated from an earlier turn.
+ */
+export const createEvalToolGateHook = (allowedTools: readonly string[]): AgentHook => {
+ const allowed = new Set(allowedTools);
+ return {
+ handler: async (event) => {
+ const { apiName, identifier, mock } = event as unknown as ToolCallHookEvent;
+ if (allowed.has(identifier)) return;
+ mock({
+ content: JSON.stringify({
+ error: EVAL_TOOL_BLOCKED_ERROR,
+ message: `${identifier} is not part of this case's environment.`,
+ requested: `${identifier}/${apiName}`,
+ }),
+ success: false,
+ });
+ },
+ id: EVAL_TOOL_GATE_HOOK_ID,
+ type: 'beforeToolCall',
+ };
+};
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
index 3035c1a96e1..f47b30d4ecb 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
@@ -10,6 +10,7 @@ import debug from 'debug';
import { LocalQueueServiceImpl } from '@/server/services/queue/impls';
+import { hookDispatcher } from '../../hooks';
import {
type AgentExecutionParams,
type AgentExecutionResult,
@@ -419,6 +420,8 @@ export async function executeStep(
stepStartAt,
});
} finally {
+ // Per-worker interceptors are recreated on the next step; retain unrelated callbacks.
+ hookDispatcher.unregisterRuntimeToolHooks(operationId);
invokeAgentSpan.end();
abortPoll?.stop();
stopRunSlotLease?.();
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts
index 2cab98f3cf4..862ec04f53d 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts
@@ -114,7 +114,7 @@ if (process.env.VERCEL) {
debug.log = console.info.bind(console);
}
-export { createEvalToolForwardingHook } from './evalToolForwardingHook';
+export { createEvalToolGateHook, EVAL_TOOL_BLOCKED_ERROR } from './evalToolGateHook';
export type { AgentRuntimeDelegate, AgentRuntimeServiceOptions } from './types';
/**
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
index f57040bb1a8..c9074d8715e 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
@@ -21,8 +21,8 @@ import { createWidgetDryRunAudit } from '@/server/services/widget/dryRunAudit';
import { stateHasEntityFileEdits } from '@/server/services/workRegistration';
import { hookDispatcher } from '../hooks';
-import { EVAL_TOOL_FORWARDING_HOOK_ID } from './constants';
-import { createEvalToolForwardingHook } from './evalToolForwardingHook';
+import { createEvalConnectorHook } from './evalConnectorHook';
+import { createEvalToolGateHook } from './evalToolGateHook';
import type { AgentRuntimeServiceContext } from './types';
const log = debug('lobe-server:agent-runtime-service');
@@ -215,13 +215,27 @@ export async function createAgentRuntime(
userId: origin?.userId,
};
+ // The gate registers first so a refused call never reaches the forwarder.
+ if (origin?.trigger === RequestTrigger.Eval && plan?.eval?.allowedTools) {
+ hookDispatcher.registerRuntimeToolHooks(operationId, [
+ createEvalToolGateHook(plan.eval.allowedTools),
+ ]);
+ }
+
if (
origin?.trigger === RequestTrigger.Eval &&
- plan?.eval?.toolForwarding &&
- !hookDispatcher.hasHook(operationId, EVAL_TOOL_FORWARDING_HOOK_ID)
+ (plan?.eval?.connectorSnapshots || plan?.eval?.toolForwarding)
) {
- hookDispatcher.register(operationId, [
- createEvalToolForwardingHook(plan.eval.toolForwarding, plan.eval.caseId),
+ hookDispatcher.registerRuntimeToolHooks(operationId, [
+ createEvalConnectorHook(
+ { db: deps.serverDB, userId: deps.userId, workspaceId: deps.workspaceId },
+ plan.eval.connectorSnapshots ?? {},
+ {
+ attemptId: plan.eval.attemptId,
+ caseId: plan.eval.caseId,
+ legacyIdentifiers: Object.keys(plan.eval.toolForwarding ?? {}),
+ },
+ ),
]);
}
diff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.runtimeTools.test.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.runtimeTools.test.ts
new file mode 100644
index 00000000000..2dffdf47a44
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.runtimeTools.test.ts
@@ -0,0 +1,167 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentEvalConnectorService } from '@/server/services/agentEvalConnector';
+import { createEvalConnectorHook } from '@/server/services/agentRuntime/AgentRuntimeService/evalConnectorHook';
+import { createEvalToolGateHook } from '@/server/services/agentRuntime/AgentRuntimeService/evalToolGateHook';
+
+import { HookDispatcher } from './HookDispatcher';
+
+const boundary = vi.hoisted(() => ({ deliver: vi.fn(), queue: true }));
+vi.mock('@/server/services/queue/impls', () => ({
+ isQueueAgentRuntimeEnabled: () => boundary.queue,
+}));
+vi.mock('@lobechat/env/agentHook', () => ({ getAgentHookConfig: () => ({}) }));
+vi.mock('./httpWebhook', () => ({
+ deliverWebhook: boundary.deliver,
+ executeToolCallWebhook: vi.fn(),
+}));
+vi.mock('@/database/models/user', () => ({ UserModel: { getEmailsByIds: async () => [] } }));
+vi.mock('@/database/server', () => ({ getServerDB: async () => ({}) }));
+
+const operationId = 'queued-eval-operation';
+const alias = 'lobe-web-browsing';
+const snapshots = {
+ [alias]: {
+ connectorId: 'exact-connection',
+ datasetId: 'dataset',
+ fingerprint: 'frozen',
+ transport: 'mcp' as const,
+ },
+};
+const event = {
+ apiName: 'search',
+ args: { query: 'fixture' },
+ identifier: alias,
+ stepIndex: 2,
+ userId: 'user',
+};
+const hooks = () => [
+ createEvalToolGateHook([alias]),
+ createEvalConnectorHook({ db: {} as never, userId: 'user' }, snapshots, {
+ attemptId: 'attempt',
+ caseId: 'case',
+ }),
+];
+
+beforeEach(() => {
+ boundary.queue = true;
+ boundary.deliver.mockReset();
+});
+afterEach(() => vi.restoreAllMocks());
+
+describe('trusted runtime tool interceptors', () => {
+ it.each([true, false])(
+ 'intercepts a native alias once in queue=%s without serializing the handler',
+ async (queue) => {
+ boundary.queue = queue;
+ const execute = vi
+ .spyOn(AgentEvalConnectorService.prototype, 'execute')
+ .mockResolvedValue({ content: 'fixture-result', success: true });
+ const dispatcher = new HookDispatcher();
+ dispatcher.registerRuntimeToolHooks(operationId, hooks());
+ dispatcher.registerRuntimeToolHooks(operationId, hooks());
+ expect(await dispatcher.dispatchBeforeToolCall(operationId, event as never, [])).toEqual({
+ isMocked: true,
+ result: { content: 'fixture-result', success: true },
+ });
+ expect(execute).toHaveBeenCalledOnce();
+ expect(execute.mock.calls[0][1]).toEqual(snapshots);
+ expect(execute.mock.calls[0][2]).toMatchObject({ attemptId: 'attempt', caseId: 'case' });
+ expect(dispatcher.getSerializedHooks(operationId)).toBeUndefined();
+ },
+ );
+
+ it('keeps caller handlers ignored in queue mode even when their ID spoofs a runtime hook', async () => {
+ const execute = vi
+ .spyOn(AgentEvalConnectorService.prototype, 'execute')
+ .mockResolvedValue({ content: 'real-mock-result', success: true });
+ const spoof = vi.fn();
+ const dispatcher = new HookDispatcher();
+ dispatcher.register(operationId, [
+ { id: 'eval-connector-bindings', type: 'beforeToolCall', handler: spoof },
+ ]);
+ dispatcher.registerRuntimeToolHooks(operationId, hooks());
+ await dispatcher.dispatchBeforeToolCall(operationId, event as never, []);
+ expect(spoof).not.toHaveBeenCalled();
+ expect(execute).toHaveBeenCalledOnce();
+ });
+
+ it('runs the allowlist gate first and never calls the connection when it refuses', async () => {
+ const execute = vi.spyOn(AgentEvalConnectorService.prototype, 'execute');
+ const dispatcher = new HookDispatcher();
+ dispatcher.registerRuntimeToolHooks(operationId, [createEvalToolGateHook([]), hooks()[1]]);
+ expect(await dispatcher.dispatchBeforeToolCall(operationId, event as never, [])).toMatchObject({
+ isMocked: true,
+ result: { success: false },
+ });
+ expect(execute).not.toHaveBeenCalled();
+ });
+
+ it('fails closed when a runtime interceptor throws instead of falling through to an ordinary handler', async () => {
+ boundary.queue = false;
+ const ordinary = vi.fn();
+ const dispatcher = new HookDispatcher();
+ dispatcher.register(operationId, [
+ { handler: ordinary, id: 'ordinary', type: 'beforeToolCall' },
+ ]);
+ dispatcher.registerRuntimeToolHooks(operationId, [
+ {
+ handler: async () => {
+ throw new Error('interceptor failed');
+ },
+ id: 'runtime',
+ type: 'beforeToolCall',
+ },
+ ]);
+ await expect(dispatcher.dispatchBeforeToolCall(operationId, event as never)).rejects.toThrow(
+ 'interceptor failed',
+ );
+ expect(ordinary).not.toHaveBeenCalled();
+ });
+
+ it('reconstructs on a cold worker and retains serialized notifications through runtime cleanup', async () => {
+ vi.spyOn(AgentEvalConnectorService.prototype, 'execute').mockResolvedValue({
+ content: 'fixture-result',
+ success: true,
+ });
+ const serialized = [
+ {
+ id: 'complete',
+ type: 'onComplete' as const,
+ webhook: { url: 'https://notification.test/complete' },
+ },
+ ];
+ for (const dispatcher of [new HookDispatcher(), new HookDispatcher()]) {
+ dispatcher.register(operationId, serialized);
+ dispatcher.registerRuntimeToolHooks(operationId, hooks());
+ expect(
+ (await dispatcher.dispatchBeforeToolCall(operationId, event as never, serialized))
+ ?.isMocked,
+ ).toBe(true);
+ dispatcher.unregisterRuntimeToolHooks(operationId);
+ expect(dispatcher.hasHook(operationId, 'eval-connector-bindings')).toBe(false);
+ await dispatcher.dispatch(
+ operationId,
+ 'onComplete',
+ { operationId, status: 'done' } as never,
+ serialized,
+ );
+ }
+ expect(boundary.deliver).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not restore runtime interception from a same-ID serialized webhook', async () => {
+ const dispatcher = new HookDispatcher();
+ const serialized = [
+ {
+ id: 'eval-connector-bindings',
+ type: 'beforeToolCall' as const,
+ webhook: { url: 'https://notification.test/observe' },
+ },
+ ];
+ expect(
+ await dispatcher.dispatchBeforeToolCall(operationId, event as never, serialized),
+ ).toBeNull();
+ expect(dispatcher.hasHook(operationId, 'eval-connector-bindings')).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
index afe3520288f..4b57edfdf99 100644
--- a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
@@ -59,6 +59,28 @@ export class HookDispatcher {
*/
private hooks: Map<string, AgentHook[]> = new Map();
+ /** Worker-created tool interceptors; never accepted from or persisted to wire hooks. */
+ private readonly runtimeToolHooks = new Map<string, AgentHook[]>();
+
+ registerRuntimeToolHooks(operationId: string, hooks: AgentHook[]): void {
+ for (const hook of hooks) {
+ if (hook.type !== 'beforeToolCall' || typeof hook.handler !== 'function' || hook.webhook) {
+ throw new Error('Runtime tool hooks must be local beforeToolCall handlers');
+ }
+ if (typeof hook.id !== 'string' || !hook.id) throw new Error('Hook id must be a string');
+ if (hook.matcher !== undefined) agentHookMatcherSchema.parse(hook.matcher);
+ }
+ const byId = new Map(
+ (this.runtimeToolHooks.get(operationId) ?? []).map((hook) => [hook.id, hook]),
+ );
+ for (const hook of hooks) byId.set(hook.id, hook);
+ this.runtimeToolHooks.set(operationId, [...byId.values()]);
+ }
+
+ unregisterRuntimeToolHooks(operationId: string): void {
+ this.runtimeToolHooks.delete(operationId);
+ }
+
/** Shared by normal dispatch and tool control, including cold-worker recovery. */
private resolveHooks(
operationId: string,
@@ -264,6 +286,14 @@ export class HookDispatcher {
).catch((error: unknown) => {
log('[%s][beforeToolCall] Observation delivery rejected: %O', operationId, error);
});
+ // Trusted interceptors are reconstructed on each worker from server-owned run state.
+ // They remain synchronous in queue mode; errors propagate so the real tool cannot
+ // run when an interceptor fails. Ordinary caller handlers keep their existing rules.
+ for (const hook of this.runtimeToolHooks.get(operationId) ?? []) {
+ if (mockedResult) break;
+ if (matchesHook(hook.matcher, toolCallEvent))
+ await hook.handler!(toolCallEvent as AgentHookEvent);
+ }
// Legacy local handlers can supply an asynchronous mock. Invoke them once;
// the first mock stops only handlers, not the independent HTTP observation.
await this.dispatchHooks(
@@ -300,11 +330,18 @@ export class HookDispatcher {
* Check if any hooks are registered for an operation
*/
hasHooks(operationId: string): boolean {
- return (this.hooks.get(operationId)?.length ?? 0) > 0;
+ return (
+ (this.hooks.get(operationId)?.length ?? 0) +
+ (this.runtimeToolHooks.get(operationId)?.length ?? 0) >
+ 0
+ );
}
hasHook(operationId: string, hookId: string): boolean {
- return this.hooks.get(operationId)?.some((hook) => hook.id === hookId) ?? false;
+ return [
+ ...(this.hooks.get(operationId) ?? []),
+ ...(this.runtimeToolHooks.get(operationId) ?? []),
+ ].some((hook) => hook.id === hookId);
}
/**
@@ -381,6 +418,7 @@ export class HookDispatcher {
*/
unregister(operationId: string): void {
this.hooks.delete(operationId);
+ this.unregisterRuntimeToolHooks(operationId);
log('[%s] Unregistered all hooks', operationId);
}
}
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 26cab64bbc7..6d27cccd6bf 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -16,6 +16,8 @@ import type {
AgentRunInitRequest,
AgentShareVisitorContext,
ChatTopicBotContext,
+ EvalConnectorSnapshots,
+ EvalMemoryReference,
EvalToolForwardingConfig,
ExpertiseContextSnapshot,
FrozenCredentialFacts,
@@ -731,6 +733,24 @@ export interface StartExecutionResult {
success: boolean;
}
export interface EvalRuntimeContext {
+ /**
+ * The only tool identifiers an attempt may see or call: what the case
+ * declares (its connectors, mocked services and forwarded tools) plus the
+ * runtime's own infrastructure tools. Absent when the case does not declare
+ * an environment of its own (an Evaluation Lab run on a real Agent keeps the
+ * Agent's tools). Enforced twice: the operation's tool set is pruned to it
+ * before the first step, and a `beforeToolCall` hook refuses anything else.
+ */
+ allowedTools?: string[];
+ /**
+ * The eval attempt this run serves: one case run, or one pass@k thread of
+ * it, including the sub-agents it forks. Mocks key their session on it.
+ */
+ attemptId?: string;
caseId?: string;
+ /** Exact connection references plus target/tool fingerprints; no credentials. */
+ connectorSnapshots?: EvalConnectorSnapshots;
+ /** Server-created isolated Memory scope of this trial; never taken from user input. */
+ memory?: EvalMemoryReference;
toolForwarding?: EvalToolForwardingConfig;
}
diff --git a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
index da4dcc134a6..a494f8b5ba3 100644
--- a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
@@ -309,6 +309,36 @@ describe('AiAgentService.execSubAgent', () => {
);
});
+ it('keeps a callSubAgent child inside its eval attempt', async () => {
+ const execAgentSpy = vi
+ .spyOn(service, 'execAgent')
+ .mockResolvedValue({ operationId: 'op-child', success: true } as any);
+ const context = { sessionDate: '2026-07-24', timezone: 'America/New_York' };
+ const runtime = {
+ caseId: 'case-7',
+ memory: { fixtureHash: 'hash', scopeId: 'scope-1' },
+ toolForwarding: { twitter: { endpoint: 'http://mock/twitter' } },
+ };
+
+ await service.execVirtualSubAgent({
+ agentId: 'agent-1',
+ eval: { context, maxSteps: 20, runtime },
+ instruction: 'collect the posts',
+ parentMessageId: 'tool-msg-1',
+ parentOperationId: 'parent-op-1',
+ topicId: 'topic-1',
+ } as any);
+
+ expect(execAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ appContext: expect.objectContaining({ suppressSignal: true }),
+ evalContext: context,
+ evalRuntime: runtime,
+ maxSteps: 20,
+ }),
+ );
+ });
+
it('should store operationId and startedAt in Thread metadata', async () => {
vi.spyOn(service, 'execAgent').mockResolvedValue(createSuccessfulExecAgentResult());
diff --git a/apps/server/src/services/aiAgent/evalGate/frozenManifests.test.ts b/apps/server/src/services/aiAgent/evalGate/frozenManifests.test.ts
new file mode 100644
index 00000000000..39195d27a9c
--- /dev/null
+++ b/apps/server/src/services/aiAgent/evalGate/frozenManifests.test.ts
@@ -0,0 +1,37 @@
+import { generateToolsFromManifest } from '@lobechat/context-engine';
+import { expect, it } from 'vitest';
+
+import type { ShareGateToolSet } from '../shareGate/types';
+import { applyFrozenEvalManifests } from './frozenManifests';
+
+it('restores original native contracts after device filtering and dispatches through the server hook', () => {
+ const original = {
+ identifier: 'lobe-local-system',
+ type: 'builtin' as const,
+ meta: { title: 'Local System' },
+ api: [
+ { name: 'readFile', description: 'Original description', parameters: { type: 'object' } },
+ ],
+ };
+ const stale = {
+ ...original,
+ meta: { title: 'LobeBench Mock' },
+ api: [...original.api, { name: 'unrelated', description: '', parameters: {} }],
+ };
+ const set: ShareGateToolSet = {
+ manifestMap: { [original.identifier]: stale },
+ executorMap: { [original.identifier]: 'client' },
+ sourceMap: {},
+ tools: generateToolsFromManifest(stale),
+ enabledToolIds: [],
+ activatableToolIds: [],
+ };
+ applyFrozenEvalManifests(set, [original]);
+ expect(set.manifestMap[original.identifier]).toEqual(original);
+ expect(set.tools).toEqual(generateToolsFromManifest(original));
+ expect(set.executorMap[original.identifier]).toBe('server');
+ expect(set.enabledToolIds).toEqual([original.identifier]);
+ expect(JSON.stringify(set)).not.toContain('Mock');
+ applyFrozenEvalManifests(set, [original]);
+ expect(set.tools).toHaveLength(1);
+});
diff --git a/apps/server/src/services/aiAgent/evalGate/frozenManifests.ts b/apps/server/src/services/aiAgent/evalGate/frozenManifests.ts
new file mode 100644
index 00000000000..f7700f154b6
--- /dev/null
+++ b/apps/server/src/services/aiAgent/evalGate/frozenManifests.ts
@@ -0,0 +1,24 @@
+import type { LobeToolManifest } from '@lobechat/context-engine';
+import { generateToolsFromManifest } from '@lobechat/context-engine';
+
+import { dropToolFromSet } from '../shareGate/toolSetMutation';
+import type { ShareGateToolSet } from '../shareGate/types';
+
+/** Restore the case contract after ordinary device/builtin discovery. Only execution is mocked. */
+export const applyFrozenEvalManifests = (
+ toolSet: ShareGateToolSet,
+ manifests: readonly LobeToolManifest[],
+): void => {
+ for (const manifest of manifests) {
+ const { identifier } = manifest;
+ dropToolFromSet(toolSet, identifier);
+ toolSet.manifestMap[identifier] = manifest;
+ // Bound calls must reach the server's beforeToolCall hook, including native aliases.
+ toolSet.executorMap[identifier] = 'server';
+ toolSet.sourceMap[identifier] = 'mcp';
+ toolSet.enabledToolIds.push(identifier);
+ toolSet.activatableToolIds.push(identifier);
+ toolSet.tools ??= [];
+ toolSet.tools.push(...generateToolsFromManifest(manifest));
+ }
+};
diff --git a/apps/server/src/services/aiAgent/evalGate/index.ts b/apps/server/src/services/aiAgent/evalGate/index.ts
new file mode 100644
index 00000000000..f14e66a7d8d
--- /dev/null
+++ b/apps/server/src/services/aiAgent/evalGate/index.ts
@@ -0,0 +1 @@
+export { applyEvalGateToToolSet } from './toolSet';
diff --git a/apps/server/src/services/aiAgent/evalGate/toolSet.test.ts b/apps/server/src/services/aiAgent/evalGate/toolSet.test.ts
new file mode 100644
index 00000000000..5083f8bafa0
--- /dev/null
+++ b/apps/server/src/services/aiAgent/evalGate/toolSet.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildToolSet, toolName } from '../shareGate/testUtils';
+import { applyEvalGateToToolSet } from './toolSet';
+
+describe('applyEvalGateToToolSet', () => {
+ it('drops every tool the case did not declare, from every structure', () => {
+ const toolSet = buildToolSet([
+ { apis: [{ name: 'search' }], identifier: 'notion', type: 'mcp' },
+ { apis: [{ name: 'gmail_search_emails' }], identifier: 'gmail', type: 'mcp' },
+ { apis: [{ name: 'runCommand' }], identifier: 'lobe-local-system' },
+ { apis: [{ name: 'activateTools' }], identifier: 'lobe-activator' },
+ ]);
+
+ applyEvalGateToToolSet(toolSet, ['notion', 'lobe-activator']);
+
+ expect(Object.keys(toolSet.manifestMap).sort()).toEqual(['lobe-activator', 'notion']);
+ expect(Object.keys(toolSet.executorMap).sort()).toEqual(['lobe-activator', 'notion']);
+ expect(Object.keys(toolSet.sourceMap).sort()).toEqual(['lobe-activator', 'notion']);
+ expect(toolSet.enabledToolIds.sort()).toEqual(['lobe-activator', 'notion']);
+ expect(toolSet.activatableToolIds.sort()).toEqual(['lobe-activator', 'notion']);
+ const names = (toolSet.tools ?? []).map((tool: any) => tool.function?.name ?? tool.name);
+ expect(names).toContain(toolName('notion', 'search', 'mcp'));
+ expect(names).not.toContain(toolName('gmail', 'gmail_search_emails', 'mcp'));
+ expect(names).not.toContain(toolName('lobe-local-system', 'runCommand'));
+ });
+
+ it('leaves a tool set alone when everything in it is allowed', () => {
+ const toolSet = buildToolSet([
+ { apis: [{ name: 'search' }], identifier: 'notion', type: 'mcp' },
+ ]);
+ const before = JSON.stringify(toolSet);
+
+ applyEvalGateToToolSet(toolSet, ['notion', 'lobe-activator']);
+
+ expect(JSON.stringify(toolSet)).toBe(before);
+ });
+
+ it('empties the set when the case declares no tools at all', () => {
+ const toolSet = buildToolSet([
+ { apis: [{ name: 'search' }], identifier: 'notion', type: 'mcp' },
+ ]);
+
+ applyEvalGateToToolSet(toolSet, []);
+
+ expect(toolSet.manifestMap).toEqual({});
+ expect(toolSet.tools).toEqual([]);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/evalGate/toolSet.ts b/apps/server/src/services/aiAgent/evalGate/toolSet.ts
new file mode 100644
index 00000000000..537c8aba446
--- /dev/null
+++ b/apps/server/src/services/aiAgent/evalGate/toolSet.ts
@@ -0,0 +1,34 @@
+import { dropToolFromSet } from '../shareGate/toolSetMutation';
+import type { ShareGateToolSet } from '../shareGate/types';
+
+/**
+ * Keep an eval attempt inside the case's environment: every tool identifier
+ * that is not on the attempt's allowlist leaves the operation's tool set
+ * before the first step β€” manifests, executors, sources, enabled and
+ * activatable ids and the function-calling schema alike.
+ *
+ * `toolDiscovery` only narrows the candidate plugin list; always-on builtins
+ * (local system, remote device, credentials, …) and every plugin the account
+ * installed for other cases still land in `toolManifestMap`, where
+ * `lobe-activator` can activate them mid-run. Without this pass a hidden
+ * attempt agent reaches tools the case never gave it, and a case then fails
+ * or passes on what the account happens to hold rather than on the model.
+ * Same shape and position as {@link applyShareGateToToolSet}; the
+ * `beforeToolCall` eval gate hook is the matching dispatch-time enforcement.
+ */
+export const applyEvalGateToToolSet = (
+ toolSet: ShareGateToolSet,
+ allowedTools: readonly string[],
+): void => {
+ const allowed = new Set(allowedTools);
+ const present = new Set([
+ ...Object.keys(toolSet.manifestMap),
+ ...Object.keys(toolSet.executorMap),
+ ...Object.keys(toolSet.sourceMap),
+ ...toolSet.enabledToolIds,
+ ...toolSet.activatableToolIds,
+ ]);
+ for (const identifier of present) {
+ if (!allowed.has(identifier)) dropToolFromSet(toolSet, identifier);
+ }
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/operationInit.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/operationInit.test.ts
index 41e0fcbdcea..a95452e5d1d 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/operationInit.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/operationInit.test.ts
@@ -31,6 +31,8 @@ const fullInput = (): Parameters<typeof buildOperationInitRequest>[0] => ({
disableSelfFeedbackIntentTool: false,
disableTools: false,
ephemeralUserMessage: 'ephemeral',
+ evalAllowedTools: ['lobe-memory____search'],
+ evalMemory: { fixtureHash: 'fixture-hash', runId: 'eval-run', topicId: 'eval-topic' },
exclusivePluginIds: undefined,
files: [
{ content: new ArrayBuffer(8), mimeType: 'image/png', name: 'a.png' },
@@ -43,6 +45,7 @@ const fullInput = (): Parameters<typeof buildOperationInitRequest>[0] => ({
localDeviceId: 'device-1',
mentionedAgents: [{ id: 'agt_2', name: 'Fox' }],
parentMessageId: 'msg-parent',
+ prompt: 'Hello',
requestTrigger: 'chat' as any,
requestedDeviceId: 'device-2',
resumeApproval: undefined,
@@ -101,6 +104,16 @@ describe('buildOperationInitRequest', () => {
});
describe('persisted init request', () => {
+ it('keeps the evaluation tool gate and isolated memory across deferred initialization', async () => {
+ const request = buildOperationInitRequest(fullInput());
+ // Exercise the Redis JSON wire format, not an in-process structured clone.
+ // eslint-disable-next-line unicorn/prefer-structured-clone
+ const persisted = JSON.parse(JSON.stringify(toPersistedInitRequest(request)));
+ const restored = await rehydrateDetachedFileContent(persisted, vi.fn());
+ expect(restored.evalAllowedTools).toEqual(request.evalAllowedTools);
+ expect(restored.evalMemory).toEqual(request.evalMemory);
+ });
+
const withDocuments = (): OperationInitRequest =>
buildOperationInitRequest({
...fullInput(),
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index e842bbea7e9..3d5fc26fd07 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -639,6 +639,9 @@ export const execAgentTurn = async (
disableSelfFeedbackIntentTool: params.disableSelfFeedbackIntentTool,
disableTools: params.disableTools,
ephemeralUserMessage,
+ evalAllowedTools: evalRuntime?.allowedTools,
+ evalConnectorSnapshots: evalRuntime?.connectorSnapshots,
+ evalMemory: evalRuntime?.memory,
exclusivePluginIds,
existingMessageIds,
files,
diff --git a/apps/server/src/services/aiAgent/pipeline/operationInit.ts b/apps/server/src/services/aiAgent/pipeline/operationInit.ts
index 5038f086a1d..10fd8b42616 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationInit.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationInit.ts
@@ -179,6 +179,7 @@ export const runOperationInit = async (
disableTools: request.disableTools,
disabledPluginIds: ctx.disabledPluginIds,
discordContext: ctx.discordContext,
+ evalConnectorSnapshots: request.evalConnectorSnapshots,
exclusivePluginIds: request.exclusivePluginIds,
externalFileTypes: request.externalFileTypes,
functionTools: request.functionTools,
@@ -218,6 +219,8 @@ export const runOperationInit = async (
disabledPluginIds: ctx.disabledPluginIds,
discovery,
ephemeralUserMessage: request.ephemeralUserMessage,
+ evalAllowedTools: request.evalAllowedTools,
+ evalMemory: request.evalMemory,
globalMemoryEnabled: request.globalMemoryEnabled,
hasMentionedAgents: request.hasMentionedAgents,
loadHistoryMessages: deps.loadHistoryMessages,
diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
index f08c9679acf..65944ad9376 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
@@ -5,8 +5,12 @@ import { TaskIdentifier } from '@lobechat/builtin-tool-task';
import type { OperationSkillSet, ProjectInstructionFile } from '@lobechat/context-engine';
import { buildExpertiseContextSnapshot } from '@lobechat/context-engine';
import type { LobeChatDatabase } from '@lobechat/database';
-import type { LobeAgentAgencyConfig, WorkspaceInitResult } from '@lobechat/types';
-import { getWorkingDirEffectivePath } from '@lobechat/types';
+import type {
+ EvalMemoryReference,
+ LobeAgentAgencyConfig,
+ WorkspaceInitResult,
+} from '@lobechat/types';
+import { getWorkingDirEffectivePath, RequestTrigger } from '@lobechat/types';
import debug from 'debug';
import type { AgentModel } from '@/database/models/agent';
@@ -17,11 +21,13 @@ import type { TopicModel } from '@/database/models/topic';
import { UserPersonaModel } from '@/database/models/userMemory/persona';
import type { ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngineering/types';
import type { AgentDocumentsService } from '@/server/services/agentDocuments';
+import { AgentEvalMemoryService } from '@/server/services/agentEvalMemory';
import { deviceGateway } from '@/server/services/deviceGateway';
import { FileService } from '@/server/services/file';
import { redisService } from '@/server/services/redis';
import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';
+import { applyEvalGateToToolSet } from '../evalGate';
import { pruneRegeneratedBranch } from '../pruneRegeneratedBranch';
import { resolveDeviceWorkingDirectoryConfig } from '../resolveDeviceWorkingDirectory';
import { applyShareGateToToolSet } from '../shareGate';
@@ -183,6 +189,10 @@ export interface OperationPrepInput {
disabledPluginIds: string[];
discovery: ToolDiscoveryResult;
ephemeralUserMessage?: string;
+ /** The only tools an eval attempt may see or call (case environment + infrastructure). */
+ evalAllowedTools?: string[];
+ /** Isolated Memory scope of an eval trial; persona is read from it, never the caller. */
+ evalMemory?: EvalMemoryReference;
globalMemoryEnabled: boolean;
hasMentionedAgents: boolean;
loadHistoryMessages: () => Promise<any[]>;
@@ -452,11 +462,7 @@ export const prepareOperation = async (
activeDeviceId,
activeDeviceScope,
agentPlugins,
- builtinModels,
- composioManifests,
- connectorManifests,
executionPlan,
- lobehubSkillManifests,
onlineDevices,
toolsEngine,
toolsResult,
@@ -532,10 +538,21 @@ export const prepareOperation = async (
// 10. Fetch user persona for memory injection (reuses globalMemoryEnabled from step 8)
let userMemory: ServerUserMemoryConfig | undefined;
+ // An eval attempt reads its persona from its own Memory entries (the case
+ // fixture's), never the caller's. Checking the reference sits outside the
+ // best-effort persona fetch: a foreign reference must fail the attempt.
+ const evalPersona = input.evalMemory
+ ? await new AgentEvalMemoryService(deps.db, deps.userId, deps.workspaceId).getPersonaDocument(
+ input.evalMemory,
+ { threadId: appContext?.threadId, topicId },
+ )
+ : undefined;
+
if (globalMemoryEnabled) {
try {
- const personaModel = new UserPersonaModel(deps.db, deps.userId);
- const persona = await personaModel.getLatestPersonaDocument();
+ const persona = input.evalMemory
+ ? evalPersona
+ : await new UserPersonaModel(deps.db, deps.userId).getLatestPersonaDocument();
if (persona?.persona) {
userMemory = {
@@ -637,6 +654,24 @@ export const prepareOperation = async (
);
}
+ // Eval attempts stay inside the case's environment the same way: whatever
+ // discovery merged in (always-on builtins, every plugin the account holds
+ // for other cases) is pruned to the attempt's allowlist here, so neither the
+ // first step nor a later `lobe-activator` call can reach past it.
+ if (input.evalAllowedTools) {
+ applyEvalGateToToolSet(
+ {
+ activatableToolIds,
+ enabledToolIds: toolsResult.enabledToolIds,
+ executorMap: discovery.toolExecutorMap,
+ manifestMap: discovery.toolManifestMap,
+ sourceMap: discovery.toolSourceMap,
+ tools,
+ },
+ input.evalAllowedTools,
+ );
+ }
+
log('execAgent: prepared evalContext for executor');
await throwIfExecutionAborted('operation preparation');
@@ -812,11 +847,16 @@ export const prepareOperation = async (
// ContextEngine owns the Lab-controlled injection decision via enableExpertise.
const expertiseAgentId = appContext?.agentSignal?.agentId ?? resolvedAgentId;
let expertise;
- try {
- const expertiseModel = new ExpertiseModel(deps.db, deps.userId, deps.workspaceId);
- expertise = await buildExpertiseContextSnapshot(expertiseModel, expertiseAgentId);
- } catch (error) {
- console.error('Failed to build expertise snapshot for agent:', expertiseAgentId, error);
+ // Learned expertise is the caller's account state. An eval attempt sees only
+ // what its case declares, so it is left out (its write side, Agent Signal,
+ // is suppressed on eval turns as well).
+ if (ctx.trigger !== RequestTrigger.Eval) {
+ try {
+ const expertiseModel = new ExpertiseModel(deps.db, deps.userId, deps.workspaceId);
+ expertise = await buildExpertiseContextSnapshot(expertiseModel, expertiseAgentId);
+ } catch (error) {
+ console.error('Failed to build expertise snapshot for agent:', expertiseAgentId, error);
+ }
}
return {
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
index 3ada594be33..fd39dd5a8f7 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
@@ -15,6 +15,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type * as MechaModule from '@/server/modules/Mecha';
import { createServerAgentToolsEngine } from '@/server/modules/Mecha';
+import { AgentEvalConnectorService } from '@/server/services/agentEvalConnector';
import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
import {
buildConnectorOwnershipPrompt,
@@ -79,6 +80,9 @@ const { connectorToolState } = vi.hoisted(() => ({
// Permission patching builds its own model rather than using `deps`.
vi.mock('@/database/models/connectorTool', () => ({
ConnectorToolModel: class {
+ static forEvaluation() {
+ return new this();
+ }
queryByConnector = vi.fn(async () => connectorToolState.tools);
},
}));
@@ -553,3 +557,54 @@ describe('discoverTools β€” credential snapshot', () => {
expect(credsList).not.toHaveBeenCalled();
});
});
+
+describe('discoverTools β€” exact eval mock bindings', () => {
+ it.each(['notion', 'lobe-web-browsing'])(
+ 'replaces ordinary manifests for bound alias %s and skips identifier resolution',
+ async (alias) => {
+ const snapshots = {
+ [alias]: {
+ connectorId: 'fixed-uuid',
+ datasetId: 'dataset',
+ fingerprint: 'fixed-contract',
+ transport: 'mcp' as const,
+ },
+ };
+ const resolve = vi
+ .spyOn(AgentEvalConnectorService.prototype, 'resolveBindings')
+ .mockResolvedValue({
+ manifests: [{ ...skillManifest(alias), type: 'mcp' } as never],
+ snapshots,
+ });
+ const requested: string[] = [];
+ try {
+ const result = await run({
+ agentConfig: { plugins: [alias] },
+ connectorResolve: (ids) => {
+ requested.push(...ids);
+ return [];
+ },
+ input: { evalConnectorSnapshots: snapshots },
+ installedPlugins: [
+ {
+ identifier: alias,
+ manifest: {
+ ...skillManifest(alias),
+ api: [{ name: 'realAccountWrite', parameters: {} }],
+ },
+ },
+ ],
+ }).promise;
+ expect(requested).not.toContain(alias);
+ expect(
+ result.toolManifestMap[alias].api.map((tool: { name: string }) => tool.name),
+ ).toEqual(['doThing']);
+ expect(JSON.stringify(result.toolManifestMap[alias])).not.toMatch(
+ /mcpParams|realAccountWrite/,
+ );
+ } finally {
+ resolve.mockRestore();
+ }
+ },
+ );
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
index ee1cd251b9b..dfa818a50bc 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
@@ -34,11 +34,16 @@ import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
import type { ServerAgentToolsContext } from '@/server/modules/Mecha';
import { createServerAgentToolsEngine } from '@/server/modules/Mecha';
+import {
+ AgentEvalConnectorService,
+ getEvalConnectorDatasetId,
+} from '@/server/services/agentEvalConnector';
import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';
import { resolveUnsupportedMessageApis } from '@/server/services/bot/platforms/messageCapabilities';
import { deviceGateway } from '@/server/services/deviceGateway';
import { buildAllowedBuiltinTools } from '../../deviceToolRegistry';
+import { applyFrozenEvalManifests } from '../../evalGate/frozenManifests';
import {
filterPluginsByShareGate,
getShareGrantActivatedPluginIds,
@@ -102,6 +107,7 @@ export const discoverTools = async (
disableTools,
disabledPluginIds: requestedDisabledPluginIds,
discordContext,
+ evalConnectorSnapshots,
exclusivePluginIds,
externalFileTypes: rawExternalFileTypes,
functionTools,
@@ -143,6 +149,18 @@ export const discoverTools = async (
let hasEnabledKnowledgeBases = false;
let operationAgentGroup: AgentGroupConfig | undefined;
const isBotConversation = !!(botContext || discordContext);
+ const boundConnectorIds = new Set(Object.keys(evalConnectorSnapshots ?? {}));
+ const boundConnectorManifests =
+ evalConnectorSnapshots && boundConnectorIds.size
+ ? (
+ await new AgentEvalConnectorService(
+ deps.db,
+ deps.userId,
+ getEvalConnectorDatasetId(evalConnectorSnapshots),
+ deps.workspaceId,
+ ).resolveBindings(evalConnectorSnapshots, evalConnectorSnapshots)
+ ).manifests
+ : [];
// Device-tool access (`canUseDevice` / `deviceAccessReason`) was resolved
// once before the hetero early exit; the decision flows into the
@@ -217,8 +235,11 @@ export const discoverTools = async (
: startToolReads(deps, {
agentConfig,
attachedFileIds,
- candidateIds: [...agentPlugins],
- exclusivePluginIds,
+ candidateIds: agentPlugins.filter((identifier) => !boundConnectorIds.has(identifier)),
+ // Bound eval tools must not auto-discover unrelated credential-bearing
+ // connectors. This limits reads only; progressive activation remains enabled.
+ exclusivePluginIds:
+ exclusivePluginIds ?? (evalConnectorSnapshots ? agentPlugins : undefined),
isGoalTurn,
projectId: appContext?.projectId,
requestedDeviceId,
@@ -250,6 +271,7 @@ export const discoverTools = async (
const disabledPluginIdSet = new Set(disabledPluginIds);
const installedPlugins = (await toolReads.installedPlugins).filter(
(p) =>
+ !boundConnectorIds.has(p.identifier) &&
!disabledPluginIdSet.has(p.identifier) &&
(!shareGrantedExtensionIds || shareGrantedExtensionIds.has(p.identifier)),
);
@@ -274,7 +296,10 @@ export const discoverTools = async (
// borrowed tool runs on (see `buildOwnershipNote`).
connectorOwnershipNote = await buildOwnershipNote(deps, connectors);
- connectorManifests = buildConnectorManifests(connectorsMcp, connectorTools);
+ connectorManifests = [
+ ...buildConnectorManifests(connectorsMcp, connectorTools),
+ ...boundConnectorManifests,
+ ];
scheduleConnectorRefresh(deps, {
connectorGateKeeper,
@@ -536,7 +561,10 @@ export const discoverTools = async (
// read off here and await it at the end: it is one Market round trip, and
// every step of the run reads the answer back off the operation instead of
// asking again.
- if (toolsResult.enabledToolIds?.includes(CredsIdentifier)) {
+ if (
+ toolsResult.enabledToolIds?.includes(CredsIdentifier) &&
+ !boundConnectorIds.has(CredsIdentifier)
+ ) {
credentialFactsPromise = readCredentialFacts(deps);
}
@@ -689,6 +717,26 @@ export const discoverTools = async (
};
}
+ if (!disableTools && boundConnectorManifests.length > 0) {
+ const frozenToolSet = {
+ activatableToolIds: [],
+ enabledToolIds: toolsResult.enabledToolIds,
+ executorMap: toolExecutorMap,
+ manifestMap: toolManifestMap,
+ sourceMap: toolSourceMap,
+ tools,
+ };
+ applyFrozenEvalManifests(
+ frozenToolSet,
+ boundConnectorManifests.filter(
+ (manifest) =>
+ (!exclusivePluginIds || exclusivePluginIds.includes(manifest.identifier)) &&
+ !requestedDisabledPluginIds.includes(manifest.identifier),
+ ),
+ );
+ tools = frozenToolSet.tools;
+ }
+
return {
activeDeviceId,
activeDeviceScope,
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/types.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/types.ts
index 9f12c5f5a5f..7a88f5aa4a1 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/types.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/types.ts
@@ -9,6 +9,7 @@ import type {
import type { LobeChatDatabase } from '@lobechat/database';
import type {
ChatTopicBotContext,
+ EvalConnectorSnapshots,
FrozenCredentialFacts,
FrozenModelFacts,
RequestTrigger,
@@ -53,6 +54,7 @@ export interface ToolDiscoveryInput {
disableSelfFeedbackIntentTool?: boolean;
disableTools?: boolean;
discordContext?: any;
+ evalConnectorSnapshots?: EvalConnectorSnapshots;
exclusivePluginIds?: string[];
/**
* Mime types of the raw bot/IM uploads. The stage only ever looked at the
diff --git a/apps/server/src/services/aiAgent/subAgentRuns.ts b/apps/server/src/services/aiAgent/subAgentRuns.ts
index a1333f4c26f..4bd7348c064 100644
--- a/apps/server/src/services/aiAgent/subAgentRuns.ts
+++ b/apps/server/src/services/aiAgent/subAgentRuns.ts
@@ -350,6 +350,11 @@ export const execAgentThreadRun = async (
? { parentOperationId, toolMessageId: parentMessageId }
: undefined;
+ // Eval inheritance (see `ExecVirtualSubAgentParams.eval`): the child keeps
+ // the attempt's prompt context, runtime and step cap, and its dialogue stays
+ // out of Agent Signal like the parent's.
+ const inheritedEval = 'eval' in params ? params.eval : undefined;
+
const appContext: NonNullable<InternalExecAgentParams['appContext']> = {
groupId,
// Every run spawned here executes in an isolation thread on the SPAWNER's
@@ -359,6 +364,7 @@ export const execAgentThreadRun = async (
isSubAgent: options.isSubAgent,
orchestrationRole: options.orchestrationRole,
subAgentProgress,
+ ...(inheritedEval && { suppressSignal: true }),
threadId: thread.id,
topicId,
};
@@ -375,9 +381,12 @@ export const execAgentThreadRun = async (
autoStart: true,
chatConfigOverride: options.chatConfig,
deviceId: options.deviceId,
+ ...(inheritedEval?.context && { evalContext: inheritedEval.context }),
+ ...(inheritedEval?.runtime && { evalRuntime: inheritedEval.runtime }),
hooks,
...(options.llmExecutor && { llmExecutor: options.llmExecutor }),
localDeviceId: options.localDeviceId,
+ ...(inheritedEval?.maxSteps && { maxSteps: inheritedEval.maxSteps }),
// Explicit sub-agent model override resolved at the spawn site.
model: options.model,
parentOperationId: recordedParentOperationId,
diff --git a/apps/server/src/services/connector/sync.ts b/apps/server/src/services/connector/sync.ts
index 418d962033f..b2addbaa4c4 100644
--- a/apps/server/src/services/connector/sync.ts
+++ b/apps/server/src/services/connector/sync.ts
@@ -102,6 +102,7 @@ export const syncConnectorToolsById = async (
connectorId: string,
/** `userId` decides the `mcp_apps` flag: with it on, view-only tools are listed too. */
ctx: ConnectorToolSyncContext & { userId?: string | null },
+ options: { pruneMissingAutoTools?: boolean } = {},
): Promise<{ toolCount: number }> => {
let connector = await ctx.connectorModel.findById(connectorId);
if (!connector) throw new Error('Connector not found');
@@ -138,6 +139,17 @@ export const syncConnectorToolsById = async (
}));
await ctx.connectorToolModel.upsertMany(connectorId, syncInputs);
+ if (options.pruneMissingAutoTools) {
+ // Eval contracts exclude vanished auto tools. Retain denied/approval rows as
+ // permission tombstones so a later upstream listing cannot auto-approve them.
+ const restricted = (await ctx.connectorToolModel.queryByConnector(connectorId))
+ .filter((tool) => tool.permission !== 'auto')
+ .map((tool) => tool.toolName);
+ await ctx.connectorToolModel.deleteToolsNotIn(connectorId, [
+ ...syncInputs.map((tool) => tool.toolName),
+ ...restricted,
+ ]);
+ }
await ctx.connectorModel.updateStatus(connectorId, ConnectorStatus.connected);
return { toolCount: syncInputs.length };
diff --git a/apps/server/src/services/mcp/index.test.ts b/apps/server/src/services/mcp/index.test.ts
index f9de5d76ea4..3ad2f1fae9b 100644
--- a/apps/server/src/services/mcp/index.test.ts
+++ b/apps/server/src/services/mcp/index.test.ts
@@ -128,6 +128,16 @@ describe('MCPService stdio authorization', () => {
expect(MCPClient.prototype.initialize).toHaveBeenCalledOnce();
});
+ it('isolates cached MCP sessions for the same URL with different credentials', async () => {
+ const service = new MCPService();
+ const base = { name: 'same-endpoint', type: 'http' as const, url: 'https://mcp.example.com' };
+ await service.listRawTools({ ...base, auth: { type: 'bearer', token: 'first-token' } });
+ await service.listRawTools({ ...base, auth: { type: 'bearer', token: 'second-token' } });
+ await service.listRawTools({ ...base, auth: { type: 'bearer', token: 'first-token' } });
+ expect(MCPClient).toHaveBeenCalledTimes(2);
+ expect(MCPClient.prototype.initialize).toHaveBeenCalledTimes(2);
+ });
+
it('keeps HTTP MCP available on the web', async () => {
await expect(
new MCPService().listRawTools({
diff --git a/apps/server/src/services/memory/userMemory/extract/extractTopic.ts b/apps/server/src/services/memory/userMemory/extract/extractTopic.ts
index 329dd37ddc8..c74c54e6e61 100644
--- a/apps/server/src/services/memory/userMemory/extract/extractTopic.ts
+++ b/apps/server/src/services/memory/userMemory/extract/extractTopic.ts
@@ -27,6 +27,7 @@ import { AsyncTaskModel } from '@/database/models/asyncTask';
import { UserModel } from '@/database/models/user';
import type { UserMemoryHybridSearchAggregatedResult } from '@/database/models/userMemory';
import { UserMemoryModel } from '@/database/models/userMemory';
+import { notEvalTopic } from '@/database/utils/evalTopic';
import { buildWorkspaceWhere } from '@/database/utils/workspace';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import { S3 } from '@/server/modules/S3';
@@ -113,6 +114,8 @@ export async function extractTopic(ctx: MemoryExtractionExecutorContext, job: To
where: and(
eq(topics.id, job.topicId),
buildWorkspaceWhere({ userId: job.userId, workspaceId: job.workspaceId }, topics),
+ // Eval dialogue never becomes the user's memory.
+ notEvalTopic(),
),
});
diff --git a/apps/server/src/services/memory/userMemory/extract/queries.ts b/apps/server/src/services/memory/userMemory/extract/queries.ts
index 0ff7e1694ef..f9f7d9280a1 100644
--- a/apps/server/src/services/memory/userMemory/extract/queries.ts
+++ b/apps/server/src/services/memory/userMemory/extract/queries.ts
@@ -16,6 +16,7 @@ import {
shouldRunUserMemoryLexicalSearch,
UserMemoryModel,
} from '@/database/models/userMemory';
+import { notEvalTopic } from '@/database/utils/evalTopic';
import { buildWorkspaceWhere } from '@/database/utils/workspace';
import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import { recordUserMemoryLexicalSearchDecision } from '@/server/services/ftsSearch/observability';
@@ -258,7 +259,11 @@ export async function filterTopicIdsForUser(
const db = await ctx.db;
const rows = await db.query.topics.findMany({
columns: { id: true },
- where: and(buildWorkspaceWhere({ userId, workspaceId }, topics), inArray(topics.id, topicIds)),
+ where: and(
+ buildWorkspaceWhere({ userId, workspaceId }, topics),
+ inArray(topics.id, topicIds),
+ notEvalTopic(),
+ ),
});
return rows.map((row) => row.id);
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/memory.ts b/apps/server/src/services/toolExecution/serverRuntimes/memory.ts
index bbec4cea066..a503b2edcbc 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/memory.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/memory.ts
@@ -46,6 +46,7 @@ import {
initModelRuntimeFromDB,
initModelRuntimeWithUserPayload,
} from '@/server/modules/ModelRuntime';
+import { AgentEvalMemoryService } from '@/server/services/agentEvalMemory';
import {
emitToolOutcomeSafely,
resolveToolOutcomeScope,
@@ -110,7 +111,7 @@ const createEmbedder = (
};
};
-class MemoryServerRuntimeService implements MemoryRuntimeService {
+export class MemoryServerRuntimeService implements MemoryRuntimeService {
private agentId?: string;
private emitOutcome?: typeof emitToolOutcomeSafely;
private messageId?: string;
@@ -172,6 +173,8 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {
summary: string;
toolAction: string;
}) => {
+ // Eval trials and fixture seeding run without an outcome emitter.
+ if (!this.emitOutcome) return;
const { scope, scopeKey } = resolveToolOutcomeScope({
agentId: this.agentId,
taskId: this.taskId,
@@ -848,7 +851,27 @@ export const memoryRuntime: ServerRuntimeRegistration = {
throw new Error('userId is required for Memory execution');
}
- // Resolve memoryEffort from user settings
+ // An eval attempt reads and writes only its own Memory entries. An attempt
+ // without a reference must fail rather than fall back to the caller's
+ // memories, and the reference is checked against this exact topic / thread.
+ if (context.isEval && !context.evalMemory) {
+ throw new Error('Eval Memory requires an initialized attempt reference');
+ }
+ if (context.evalMemory) {
+ const service = await new AgentEvalMemoryService(
+ context.serverDB,
+ context.userId,
+ context.workspaceId,
+ ).runtime({
+ context,
+ // An eval attempt uses its Agent's effort setting.
+ memoryEffort: normalizeMemoryEffort(context.memoryEffort),
+ memoryEmbeddingRuntime: context.memoryEmbeddingRuntime,
+ reference: context.evalMemory,
+ });
+ return new MemoryExecutionRuntime({ service, toolPermission: context.memoryToolPermission });
+ }
+
let memoryEffort: MemoryEffort = 'medium';
try {
const userSettingsRow = await context.serverDB.query.userSettings.findFirst({
diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.ts
index e21cb860347..0f2dd63e5a2 100644
--- a/apps/server/src/services/toolExecution/types.ts
+++ b/apps/server/src/services/toolExecution/types.ts
@@ -6,6 +6,7 @@ import {
type ChatTopicBotContext,
type ClientSecretPayload,
type DeviceUnavailableErrorData,
+ type EvalMemoryReference,
type ExecSubAgentParams,
type ExecutionPlan,
type StepActivatedSkill,
@@ -263,6 +264,13 @@ export interface ToolExecutionContext {
* runtime name a follow-up tool in its result only when the model can actually call it.
*/
enabledToolIds?: string[];
+ /**
+ * Optional server-owned embedding runtime for memory search.
+ *
+ * Use when the acting user is synthetic and should not read user key vaults.
+ */
+ /** Server-authored isolated Memory scope of an eval trial. Never a tool argument. */
+ evalMemory?: EvalMemoryReference;
/**
* Legacy agent invocation callback forwarded from RuntimeExecutorContext.
* Kept for tool runtimes that still dispatch through exec_sub_agent style
@@ -279,6 +287,8 @@ export interface ToolExecutionContext {
executionTimeoutMs?: number;
/** Current group ID for group chat context */
groupId?: string | null;
+ /** Eval trials must run on isolated Memory; set even when the scope is missing. */
+ isEval?: boolean;
/** Whether this tool call is executing inside an isolated sub-agent run. */
isSubAgent?: boolean;
/**
@@ -297,11 +307,7 @@ export interface ToolExecutionContext {
* {@link localSandbox}.
*/
localSandboxNetwork?: boolean;
- /**
- * Optional server-owned embedding runtime for memory search.
- *
- * Use when the acting user is synthetic and should not read user key vaults.
- */
+ memoryEffort?: string;
memoryEmbeddingRuntime?: ToolExecutionMemoryEmbeddingRuntime;
/** Memory tool permission from agent chat config */
memoryToolPermission?: 'read-only' | 'read-write';
diff --git a/apps/server/src/workflows/agentEvalRun/index.ts b/apps/server/src/workflows/agentEvalRun/index.ts
index 6f83e8b2c4d..969a5d0b7dd 100644
--- a/apps/server/src/workflows/agentEvalRun/index.ts
+++ b/apps/server/src/workflows/agentEvalRun/index.ts
@@ -53,6 +53,7 @@ export interface ResumeAgentTrajectoryPayload {
caseId?: string;
environment?: EvalCaseEnvironment;
envPrompt?: string;
+ expectedExecutionId?: string;
maxSteps?: number;
parentMessageId: string;
runId: string;
@@ -72,6 +73,7 @@ export interface OnTrajectoryCompletePayload {
duration?: number;
errorDetail?: unknown;
errorMessage?: string;
+ executionId?: string;
llmCalls?: number;
operationId: string;
reason: string;
@@ -80,11 +82,13 @@ export interface OnTrajectoryCompletePayload {
steps?: number;
testCaseId: string;
toolCalls?: number;
+ topicId?: string;
totalTokens?: number;
userId: string;
}
export interface RunThreadTrajectoryPayload {
+ executionId?: string;
runId: string;
testCaseId: string;
threadId: string;
@@ -97,6 +101,7 @@ export interface ResumeThreadTrajectoryPayload {
caseId?: string;
environment?: EvalCaseEnvironment;
envPrompt?: string;
+ expectedExecutionId?: string;
maxSteps?: number;
parentMessageId: string;
runId: string;
@@ -111,6 +116,7 @@ export interface OnThreadCompletePayload {
cost?: number;
duration?: number;
errorMessage?: string;
+ executionId?: string;
llmCalls?: number;
operationId: string;
reason: string;
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
index ea611ffe6f6..d82d276ee2d 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts
@@ -7,7 +7,7 @@ import type {
MessageTransport,
StreamSink,
} from '../transport';
-import { TOOL_CALL_REPEAT_LIMIT } from '../utils/toolCallRepeatGuard';
+import { TOOL_CALL_BURST_LIMIT, TOOL_CALL_REPEAT_LIMIT } from '../utils/toolCallRepeatGuard';
import {
finalizeCallLlmTurn,
persistInterruptedCallLlmResult,
@@ -184,6 +184,117 @@ describe('callLlmFinalizer', () => {
expect(result.newState.toolCallRepeatGuard?.stoppedByRepeatLimit).toBe(true);
});
+ const createToolBatch = (count: number, argumentsFor: (index: number) => string) => {
+ const toolsCalling = Array.from({ length: count }, (_, index) => ({
+ apiName: 'get_users_posts',
+ arguments: argumentsFor(index),
+ id: `call-${index}`,
+ identifier: 'twitter',
+ type: 'default' as const,
+ }));
+ return {
+ toolCalls: toolsCalling.map((tool) => ({
+ function: { arguments: tool.arguments, name: tool.apiName },
+ id: tool.id,
+ type: 'function' as const,
+ })),
+ toolsCalling,
+ };
+ };
+
+ it('blocks a turn that repeats one tool call limit times within the same response', async () => {
+ const messages = createMessageTransport();
+ const state = AgentRuntime.createInitialState({ operationId: 'operation-1' });
+
+ const result = await finalizeCallLlmTurn({
+ assistantMessageId: 'assistant-7',
+ events: [],
+ host: createHost(messages),
+ model: 'mimo',
+ output: createOutput({
+ content: '',
+ ...createToolBatch(TOOL_CALL_REPEAT_LIMIT, () => '{"id":"acme_ai","max_results":100}'),
+ }),
+ provider: 'openrouter',
+ shouldReplayAssistantReasoning: false,
+ state,
+ });
+
+ expect(result.nextContext).toMatchObject({
+ payload: { hasToolsCalling: false, toolsCalling: [] },
+ phase: 'llm_result',
+ });
+ expect(messages.update).toHaveBeenCalledWith(
+ 'assistant-7',
+ expect.objectContaining({
+ content: `Stopped after the same tool call was requested ${TOOL_CALL_REPEAT_LIMIT} consecutive times.`,
+ tools: undefined,
+ }),
+ );
+ expect(result.newState.toolCallRepeatGuard?.stoppedByRepeatLimit).toBe(true);
+ });
+
+ it('blocks a turn that requests more distinct tool calls than the burst limit', async () => {
+ const messages = createMessageTransport();
+ const state = AgentRuntime.createInitialState({ operationId: 'operation-1' });
+ const count = TOOL_CALL_BURST_LIMIT + 1;
+
+ const result = await finalizeCallLlmTurn({
+ assistantMessageId: 'assistant-8',
+ events: [],
+ host: createHost(messages),
+ model: 'mimo',
+ output: createOutput({
+ content: '',
+ ...createToolBatch(count, (index) => `{"query":"topic ${index}"}`),
+ }),
+ provider: 'openrouter',
+ shouldReplayAssistantReasoning: false,
+ state,
+ });
+
+ expect(result.nextContext).toMatchObject({
+ payload: { hasToolsCalling: false, toolsCalling: [] },
+ phase: 'llm_result',
+ });
+ expect(result.events).toContainEqual(
+ expect.objectContaining({
+ result: expect.objectContaining({ finishReason: 'tool_call_repeat_limit' }),
+ type: 'llm_result',
+ }),
+ );
+ expect(messages.update).toHaveBeenCalledWith(
+ 'assistant-8',
+ expect.objectContaining({
+ content: `Stopped after ${count} tool calls were requested in one turn (limit ${TOOL_CALL_BURST_LIMIT}).`,
+ tools: undefined,
+ }),
+ );
+ expect(result.newState.toolCallRepeatGuard?.stoppedByRepeatLimit).toBe(true);
+ });
+
+ it('lets a fan-out at the burst limit through to the tools', async () => {
+ const state = AgentRuntime.createInitialState({ operationId: 'operation-1' });
+ const batch = createToolBatch(TOOL_CALL_BURST_LIMIT, (index) => `{"query":"topic ${index}"}`);
+
+ const result = await finalizeCallLlmTurn({
+ assistantMessageId: 'assistant-9',
+ events: [],
+ host: createHost(),
+ model: 'mimo',
+ output: createOutput({ content: '', ...batch }),
+ provider: 'openrouter',
+ shouldReplayAssistantReasoning: false,
+ state,
+ });
+
+ expect(result.nextContext).toMatchObject({
+ payload: { hasToolsCalling: true, toolsCalling: batch.toolsCalling },
+ phase: 'llm_result',
+ });
+ expect(result.newState.toolCallRepeatGuard?.stoppedByRepeatLimit).toBeUndefined();
+ });
+
it('preserves user cancellation when an aborted stream emits the limit-th repeated tool call', async () => {
const state = AgentRuntime.createInitialState({ operationId: 'operation-1' });
state.toolCallRepeatGuard = {
diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
index 00734466e87..d24aff96805 100644
--- a/packages/agent-runtime/src/executors/callLlmFinalizer.ts
+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.ts
@@ -6,8 +6,6 @@ import type {
ModelReasoning,
ModelUsage,
} from '@lobechat/types';
-import { serializePartsForStorage } from '../utils/multimodalContent';
-import { sanitizeToolCallArguments } from '../utils/sanitizeToolCallArguments';
import { UsageCounter } from '../core/UsageCounter';
import type { AgentRuntimeHost, LLMAttemptOutput } from '../transport';
@@ -17,8 +15,12 @@ import type {
GeneralAgentCallLLMResultPayload,
InstructionExecutionResult,
} from '../types';
+import { serializePartsForStorage } from '../utils/multimodalContent';
+import { sanitizeToolCallArguments } from '../utils/sanitizeToolCallArguments';
import {
hasRepeatedToolCall,
+ hasToolCallBurst,
+ TOOL_CALL_BURST_LIMIT,
TOOL_CALL_REPEAT_LIMIT,
updateToolCallRepeatGuard,
} from '../utils/toolCallRepeatGuard';
@@ -298,7 +300,12 @@ export const finalizeCallLlmTurn = async ({
}: FinalizeCallLlmTurnInput): Promise<InstructionExecutionResult> => {
const { operation, transports } = host;
const repeatCounts = updateToolCallRepeatGuard(state.toolCallRepeatGuard, output.toolsCalling);
- const stoppedByRepeatLimit = output.finishReason !== 'abort' && hasRepeatedToolCall(repeatCounts);
+ const repeated = hasRepeatedToolCall(repeatCounts);
+ // Same stop for a turn that asks for more calls than the burst limit: the
+ // calls differ, but nothing legitimate fans out that wide, and dispatching
+ // them would hit a real service once per call.
+ const stoppedByRepeatLimit =
+ output.finishReason !== 'abort' && (repeated || hasToolCallBurst(output.toolsCalling));
// Carried on the state so the terminal reason can name this stop. Sticky once
// set: later turns emit no tool calls, and `updateToolCallRepeatGuard` resets
// its counts on those, which would otherwise erase the only trace of why the
@@ -312,7 +319,9 @@ export const finalizeCallLlmTurn = async ({
const finalizedOutput = stoppedByRepeatLimit
? {
...output,
- content: `Stopped after the same tool call was requested ${TOOL_CALL_REPEAT_LIMIT} consecutive times.`,
+ content: repeated
+ ? `Stopped after the same tool call was requested ${TOOL_CALL_REPEAT_LIMIT} consecutive times.`
+ : `Stopped after ${output.toolsCalling.length} tool calls were requested in one turn (limit ${TOOL_CALL_BURST_LIMIT}).`,
finishReason: 'tool_call_repeat_limit',
toolCalls: [],
toolsCalling: [],
diff --git a/packages/agent-runtime/src/transport/tool.ts b/packages/agent-runtime/src/transport/tool.ts
index a02c562197f..de038aba3a6 100644
--- a/packages/agent-runtime/src/transport/tool.ts
+++ b/packages/agent-runtime/src/transport/tool.ts
@@ -43,6 +43,13 @@ export interface ToolRunResult {
export interface ToolForwardingRequest {
data: Pick<ChatToolPayload, 'apiName' | 'identifier'> & { args: Record<string, unknown> };
metadata: {
+ /**
+ * The eval attempt this call belongs to. One attempt is one case run (or
+ * one pass@k thread of it) including every sub-agent it forks, so a mock
+ * keys its session on this, not on `operationId`, which changes per
+ * sub-agent.
+ */
+ attemptId?: string;
caseId?: string;
callIndex: number;
operationId: string;
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index bc3a777ba2b..d3dd4047a48 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -18,6 +18,7 @@ import type {
AgentSignalOperationMarker,
ChatToolPayload,
ChatTopicBotContext,
+ EvalConnectorSnapshots,
EvalToolForwardingConfig,
ExecutionPlan,
ExpertiseContextSnapshot,
@@ -157,7 +158,17 @@ export interface AgentRunPrincipal {
*/
export interface AgentRunPlan {
/** Evaluation execution controls (tool forwarding) for eval runs. */
- eval?: { caseId?: string; toolForwarding?: EvalToolForwardingConfig };
+ eval?: {
+ connectorSnapshots?: EvalConnectorSnapshots;
+ /** The only tool identifiers the attempt may see or call; see EvalRuntimeContext. */
+ allowedTools?: string[];
+ /** The eval attempt (case run or pass@k thread) this operation serves; inherited by sub-agents. */
+ attemptId?: string;
+ caseId?: string;
+ /** Isolated Memory scope of the eval trial (server-created). */
+ memory?: { fixtureHash: string; runId: string; threadId?: string; topicId: string };
+ toolForwarding?: EvalToolForwardingConfig;
+ };
/** Where (and whether) the run executes, resolved once at the entry point. */
execution?: ExecutionPlan;
/** Operation-level skill set for the skill resolver. */
diff --git a/packages/agent-runtime/src/utils/toolCallRepeatGuard.test.ts b/packages/agent-runtime/src/utils/toolCallRepeatGuard.test.ts
index 98c4df94536..494393d16d4 100644
--- a/packages/agent-runtime/src/utils/toolCallRepeatGuard.test.ts
+++ b/packages/agent-runtime/src/utils/toolCallRepeatGuard.test.ts
@@ -3,6 +3,8 @@ import { describe, expect, it } from 'vitest';
import {
hasRepeatedToolCall,
+ hasToolCallBurst,
+ TOOL_CALL_BURST_LIMIT,
TOOL_CALL_REPEAT_LIMIT,
updateToolCallRepeatGuard,
} from './toolCallRepeatGuard';
@@ -57,4 +59,40 @@ describe('toolCallRepeatGuard', () => {
expect(resetGuard).toEqual({ counts: {} });
expect(hasRepeatedToolCall(resetGuard)).toBe(false);
});
+
+ it('counts copies of one call inside a single turn toward the limit', () => {
+ const copies = (count: number) =>
+ Array.from({ length: count }, () => createToolCall('{"id":"acme_ai"}'));
+
+ expect(
+ hasRepeatedToolCall(updateToolCallRepeatGuard(undefined, copies(TOOL_CALL_REPEAT_LIMIT - 1))),
+ ).toBe(false);
+ expect(
+ hasRepeatedToolCall(updateToolCallRepeatGuard(undefined, copies(TOOL_CALL_REPEAT_LIMIT))),
+ ).toBe(true);
+ });
+
+ it('adds copies in the current turn to the count carried from earlier turns', () => {
+ const copies = (count: number) =>
+ Array.from({ length: count }, () => createToolCall('{"id":"acme_ai"}'));
+ const half = Math.ceil(TOOL_CALL_REPEAT_LIMIT / 2);
+
+ const firstTurn = updateToolCallRepeatGuard(undefined, copies(half - 1));
+ expect(hasRepeatedToolCall(updateToolCallRepeatGuard(firstTurn, copies(half - 1)))).toBe(false);
+ expect(hasRepeatedToolCall(updateToolCallRepeatGuard(firstTurn, copies(half + 1)))).toBe(true);
+ });
+
+ it('flags a turn that requests more tool calls than the burst limit even with distinct arguments', () => {
+ const distinct = (count: number) =>
+ Array.from({ length: count }, (_, index) => createToolCall(`{"query":"topic ${index}"}`));
+
+ expect(hasToolCallBurst(distinct(TOOL_CALL_BURST_LIMIT))).toBe(false);
+ expect(hasToolCallBurst(distinct(TOOL_CALL_BURST_LIMIT + 1))).toBe(true);
+ // Distinct arguments never trip the repeat count; only the burst cap catches this turn.
+ expect(
+ hasRepeatedToolCall(
+ updateToolCallRepeatGuard(undefined, distinct(TOOL_CALL_BURST_LIMIT + 1)),
+ ),
+ ).toBe(false);
+ });
});
diff --git a/packages/agent-runtime/src/utils/toolCallRepeatGuard.ts b/packages/agent-runtime/src/utils/toolCallRepeatGuard.ts
index c7bfe60e24b..99435cb4b28 100644
--- a/packages/agent-runtime/src/utils/toolCallRepeatGuard.ts
+++ b/packages/agent-runtime/src/utils/toolCallRepeatGuard.ts
@@ -10,6 +10,15 @@ import type { AgentState } from '../types';
*/
export const TOOL_CALL_REPEAT_LIMIT = 20;
+/**
+ * Tool calls one LLM turn may request before the turn is stopped without
+ * running any of them. A model that has lost the thread can fill its whole
+ * output budget with tool calls (MiMo V2.6 Flash emitted 4,383 in one turn,
+ * 131k tokens, mostly varied arguments); every one of those would otherwise
+ * be dispatched to a real service. Legitimate fan-out stays far below this.
+ */
+export const TOOL_CALL_BURST_LIMIT = 50;
+
const canonicalize = (value: unknown): unknown => {
if (Array.isArray(value)) return value.map(canonicalize);
@@ -49,7 +58,11 @@ export const updateToolCallRepeatGuard = (
for (const toolCalling of toolsCalling) {
const signature = getToolCallSignature(toolCalling);
- counts[signature] = (previousCounts[signature] ?? 0) + 1;
+ // Copies of one call inside a single turn count like consecutive turns:
+ // a model that asks for the same call hundreds of times in one response is
+ // as stuck as one that asks once per turn, and counting per turn let the
+ // whole batch through to the tools.
+ counts[signature] = (counts[signature] ?? previousCounts[signature] ?? 0) + 1;
}
return { counts };
@@ -57,3 +70,6 @@ export const updateToolCallRepeatGuard = (
export const hasRepeatedToolCall = (guard: AgentState['toolCallRepeatGuard']) =>
Object.values(guard?.counts ?? {}).some((count) => count >= TOOL_CALL_REPEAT_LIMIT);
+
+export const hasToolCallBurst = (toolsCalling: ChatToolPayload[]) =>
+ toolsCalling.length > TOOL_CALL_BURST_LIMIT;
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index e8752b77073..b23a6cce3b0 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -244,6 +244,8 @@ export class MessagesEngine {
const hasDateAwareTools =
toolIds.includes('lobe-web-browsing') || toolIds.includes('lobe-user-memory');
const isSystemDateEnabled = enableSystemDate !== false && !hasDateAwareTools;
+ // An eval attempt renders "today" from its case clock, never the wall clock.
+ const evalClock = evalContext?.sessionDate ? new Date(evalContext.sessionDate) : undefined;
const currentUserMessage = [...messages]
.reverse()
.find((m) => m.role === 'user' && typeof m.content === 'string')?.content as
@@ -342,7 +344,7 @@ export class MessagesEngine {
enabled: !!botPlatformContext,
}),
// System date
- new SystemDateProvider({ enabled: isSystemDateEnabled, timezone }),
+ new SystemDateProvider({ enabled: isSystemDateEnabled, now: evalClock, timezone }),
// Model info (name / id / knowledge cutoff)
new ModelInfoProvider({
displayName: modelDisplayName,
diff --git a/packages/context-engine/src/providers/EvalContextSystemInjector.ts b/packages/context-engine/src/providers/EvalContextSystemInjector.ts
index 5bc0b997acc..a59f23cc152 100644
--- a/packages/context-engine/src/providers/EvalContextSystemInjector.ts
+++ b/packages/context-engine/src/providers/EvalContextSystemInjector.ts
@@ -13,6 +13,13 @@ const log = debug('context-engine:provider:EvalContextSystemInjector');
export interface EvalContext {
envPrompt?: string;
+ /**
+ * The attempt's clock (ISO date or instant). Every "today" the model sees
+ * renders from it, so the prompt reads like a real session on that day.
+ */
+ sessionDate?: string;
+ /** IANA timezone the clock renders in; UTC when absent. */
+ timezone?: string;
}
export interface EvalContextSystemInjectorConfig {
diff --git a/packages/context-engine/src/providers/SystemDateProvider.ts b/packages/context-engine/src/providers/SystemDateProvider.ts
index 50d0ffd8211..39dfbe335fa 100644
--- a/packages/context-engine/src/providers/SystemDateProvider.ts
+++ b/packages/context-engine/src/providers/SystemDateProvider.ts
@@ -13,6 +13,8 @@ const log = debug('context-engine:provider:SystemDateProvider');
export interface SystemDateProviderConfig {
enabled?: boolean;
+ /** The clock to render; the wall clock when absent (eval attempts pin it). */
+ now?: Date;
timezone?: string | null;
}
@@ -33,7 +35,7 @@ export class SystemDateProvider extends BaseSystemRoleProvider {
}
const tz = this.config.timezone || 'UTC';
- const today = new Date();
+ const today = this.config.now ?? new Date();
const year = today.toLocaleString('en-US', { timeZone: tz, year: 'numeric' });
const month = today.toLocaleString('en-US', { month: '2-digit', timeZone: tz });
diff --git a/packages/context-engine/src/providers/__tests__/SystemDateProvider.test.ts b/packages/context-engine/src/providers/__tests__/SystemDateProvider.test.ts
index c7fa37ffccd..355ec3a6fea 100644
--- a/packages/context-engine/src/providers/__tests__/SystemDateProvider.test.ts
+++ b/packages/context-engine/src/providers/__tests__/SystemDateProvider.test.ts
@@ -33,6 +33,17 @@ describe('SystemDateProvider', () => {
expect(result.metadata.systemDateInjected).toBe(true);
});
+ it('renders a pinned clock instead of today', async () => {
+ const provider = new SystemDateProvider({ now: new Date('2026-07-21T00:00:00Z') });
+ const context = createContext([
+ { content: 'Hello', createdAt: Date.now(), id: '1', role: 'user', updatedAt: Date.now() },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages[0].content).toBe('Current date: 2026-07-21 (UTC)');
+ });
+
it('should include timezone name when timezone is provided', async () => {
const provider = new SystemDateProvider({ timezone: 'Asia/Shanghai' });
const context = createContext([
diff --git a/packages/database/src/models/__tests__/connector.test.ts b/packages/database/src/models/__tests__/connector.test.ts
index ac433fbebfc..997da548ffb 100644
--- a/packages/database/src/models/__tests__/connector.test.ts
+++ b/packages/database/src/models/__tests__/connector.test.ts
@@ -3,9 +3,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
import type { ConnectorCredentials } from '../../schemas';
-import { agents, userConnectors, users, workspaces } from '../../schemas';
+import { agentEvalDatasets, agents, userConnectors, users, workspaces } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { ConnectorModel } from '../connector';
+import { EvalConnectorUpdateError } from '../connectorEval';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -46,6 +47,14 @@ beforeEach(async () => {
vi.clearAllMocks();
await serverDB.delete(users);
await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(agentEvalDatasets).values(
+ ['private-dataset', 'ds-test', 'wrong-dataset'].map((id) => ({
+ id,
+ identifier: id,
+ name: id,
+ userId,
+ })),
+ );
await serverDB
.insert(workspaces)
.values({ id: workspaceId, name: 'WS', primaryOwnerId: userId, slug: 'ws' });
@@ -56,6 +65,228 @@ afterEach(async () => {
});
describe('ConnectorModel', () => {
+ describe('imported evaluation connection edits', () => {
+ const marker = { datasetId: 'private-dataset', packageSha256: 'private-package' };
+ const createEval = async () => {
+ const model = ConnectorModel.forEvaluation(
+ serverDB,
+ userId,
+ marker.datasetId,
+ undefined,
+ gateKeeper,
+ );
+ const row = await model.create({
+ credentials: JSON.stringify({ type: 'bearer', token: 'old-token' }),
+ identifier: `eval-${crypto.randomUUID()}`,
+ name: 'Private mock',
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mock.example/mcp',
+ metadata: { agentEval: marker },
+ sourceType: 'custom',
+ status: 'connected',
+ tokenExpiresAt: new Date(123),
+ });
+ return { model, row };
+ };
+
+ it('hides evaluation connections from ordinary inventories and exact identifier calls', async () => {
+ const { model: evaluation, row } = await createEval();
+ const model = new ConnectorModel(serverDB, userId, undefined, gateKeeper);
+ expect(await model.query()).toEqual([]);
+ expect(await model.queryPublic()).toEqual([]);
+ expect(await model.queryByIdentifiers([row.identifier])).toEqual([]);
+ expect(await model.resolveByIdentifiers([row.identifier])).toEqual([]);
+ expect(await model.findScopedByIdentifier(row.identifier)).toBeNull();
+ expect(await model.queryReferencesByIdentifiers([row.identifier])).toEqual([]);
+ expect((await evaluation.queryPublic()).map((c) => c.id)).toContain(row.id);
+ await expect(
+ evaluation.update(row.id, { metadata: { mountedByAgentId: 'ordinary-agent' } }),
+ ).rejects.toThrow('cannot');
+ const normal = await model.create({
+ identifier: row.identifier,
+ name: 'My real connection',
+ sourceType: 'custom',
+ status: 'disconnected',
+ });
+ expect((await model.queryPublic()).map((c) => c.id)).toEqual([normal.id]);
+ expect((await model.findScopedByIdentifier(row.identifier))?.id).toBe(normal.id);
+ });
+
+ it('retains the server-owned marker through metadata replacement and keeps omitted credentials', async () => {
+ const { model, row } = await createEval();
+ await model.update(row.id, {
+ metadata: { description: 'Updated', agentEval: { datasetId: 'spoofed' } },
+ });
+ const [stored] = await serverDB
+ .select()
+ .from(userConnectors)
+ .where(eq(userConnectors.id, row.id));
+ expect(stored.metadata).toEqual({ agentEval: marker, description: 'Updated' });
+ expect(stored.credentials).toBe(row.credentials);
+ expect(
+ await new ConnectorModel(serverDB, userId).resolveByIdentifiers([row.identifier]),
+ ).toEqual([]);
+ await model.update(row.id, { metadata: null });
+ expect((await model.findById(row.id))?.metadata).toEqual({ agentEval: marker });
+ });
+
+ it('encrypts the header-only editor payload instead of persisting metadata headers', async () => {
+ const { model, row } = await createEval();
+ await model.update(row.id, {
+ credentials: null,
+ metadata: { customHeaders: { 'X-Mock-Token': 'new-header-token' }, description: 'Renamed' },
+ });
+ const [stored] = await serverDB
+ .select()
+ .from(userConnectors)
+ .where(eq(userConnectors.id, row.id));
+ expect(stored.credentials).toBe(
+ `enc:${JSON.stringify({ headers: { 'X-Mock-Token': 'new-header-token' }, type: 'header' })}`,
+ );
+ expect(stored.metadata).toEqual({ agentEval: marker, description: 'Renamed' });
+ expect(stored.tokenExpiresAt).toBeNull();
+ expect(stored.status).toBe('disconnected');
+ expect((await model.findById(row.id))?.credentials).toEqual({
+ headers: { 'X-Mock-Token': 'new-header-token' },
+ type: 'header',
+ });
+ });
+
+ it('combines bearer authentication and additional headers inside the encrypted column', async () => {
+ const { model, row } = await createEval();
+ await model.update(row.id, {
+ credentials: JSON.stringify({ type: 'bearer', token: 'replacement-token' }),
+ metadata: {
+ customHeaders: { 'X-Tenant': 'private-tenant', 'authorization': 'old-header' },
+ },
+ });
+ const stored = await model.findById(row.id);
+ expect(stored?.credentials).toEqual({
+ headers: { 'Authorization': 'Bearer replacement-token', 'X-Tenant': 'private-tenant' },
+ type: 'header',
+ });
+ expect(stored?.metadata).toEqual({ agentEval: marker });
+ });
+
+ it('honors explicit clears on the same URL and clears resubmitted headers when changing URL', async () => {
+ for (const changeUrl of [false, true]) {
+ const { model, row } = await createEval();
+ await model.update(row.id, {
+ credentials: null,
+ ...(changeUrl
+ ? {
+ mcpServerUrl: 'https://other-mock.example/mcp',
+ metadata: { customHeaders: { Authorization: 'Bearer old-token' } },
+ }
+ : {}),
+ });
+ const stored = await model.findById(row.id);
+ expect(stored?.credentials).toBeNull();
+ expect(stored?.metadata?.customHeaders).toBeUndefined();
+ expect(stored?.metadata?.agentEval).toEqual(marker);
+ expect(stored?.status).toBe('disconnected');
+ expect(stored?.tokenExpiresAt).toBeNull();
+ }
+ });
+
+ it('allows changing the address with replacement credentials but rejects implicit reuse', async () => {
+ const { model, row } = await createEval();
+ const mcpServerUrl = 'https://other-mock.example/mcp';
+ await expect(
+ model.update(row.id, {
+ mcpServerUrl: 'https://[email protected]/mcp',
+ credentials: null,
+ }),
+ ).rejects.toThrow('without embedded credentials');
+ await expect(model.update(row.id, { mcpServerUrl })).rejects.toBeInstanceOf(
+ EvalConnectorUpdateError,
+ );
+ expect((await model.findById(row.id))?.mcpServerUrl).toBe(row.mcpServerUrl);
+ await model.update(row.id, {
+ mcpServerUrl,
+ credentials: JSON.stringify({ type: 'bearer', token: 'new-server-token' }),
+ });
+ expect(await model.findById(row.id)).toMatchObject({
+ mcpServerUrl,
+ credentials: { type: 'bearer', token: 'new-server-token' },
+ });
+ });
+
+ it('never writes imported credentials without encryption or echoes invalid header values', async () => {
+ const { model, row } = await createEval();
+ const withoutKey = ConnectorModel.forEvaluation(serverDB, userId, marker.datasetId);
+ await expect(
+ withoutKey.update(row.id, { credentials: JSON.stringify(apikeyCredentials) }),
+ ).rejects.toThrow('Secure connection storage');
+ await expect(
+ model.update(row.id, { metadata: { customHeaders: { Bad: 'secret\r\ninjection' } } }),
+ ).rejects.toThrow('Invalid mock connection headers');
+ expect((await model.findById(row.id))?.credentials).toEqual({
+ type: 'bearer',
+ token: 'old-token',
+ });
+ });
+
+ it('does not change ordinary header storage or let an ordinary update spoof import provenance', async () => {
+ const model = new ConnectorModel(serverDB, userId, undefined, gateKeeper);
+ const row = await model.create({
+ identifier: 'ordinary',
+ name: 'Ordinary',
+ sourceType: 'custom',
+ status: 'connected',
+ });
+ await model.update(row.id, {
+ credentials: null,
+ metadata: { agentEval: marker, customHeaders: { 'X-Token': 'ordinary-header' } },
+ });
+ expect(await model.findById(row.id)).toMatchObject({
+ credentials: null,
+ metadata: { customHeaders: { 'X-Token': 'ordinary-header' } },
+ status: 'connected',
+ });
+ expect((await model.findById(row.id))?.metadata?.agentEval).toBeUndefined();
+ });
+ });
+
+ it('keeps imported Dataset mocks out of ordinary runtime resolution while allowing exact binding', async () => {
+ const model = new ConnectorModel(serverDB, userId, undefined, gateKeeper);
+ const evaluation = ConnectorModel.forEvaluation(
+ serverDB,
+ userId,
+ 'ds-test',
+ undefined,
+ gateKeeper,
+ );
+ const imported = await evaluation.create({
+ credentials: JSON.stringify(apikeyCredentials),
+ identifier: 'private-dataset-mock',
+ metadata: { agentEval: { datasetId: 'ds-test', packageSha256: 'private-hash' } },
+ name: 'Dataset mock',
+ sourceType: 'custom',
+ status: 'connected',
+ });
+ gateKeeper.decrypt.mockClear();
+ expect(await model.resolveByIdentifiers(['private-dataset-mock'])).toEqual([]);
+ expect(await model.resolveAll()).toEqual([]);
+ expect(gateKeeper.decrypt).not.toHaveBeenCalled();
+ expect(await model.findPublicById(imported.id)).toBeNull();
+ expect(await model.findById(imported.id)).toBeNull();
+ await model.update(imported.id, { name: 'Unauthorized ordinary edit' });
+ await model.delete(imported.id);
+ expect((await evaluation.findById(imported.id))?.credentials).toEqual(apikeyCredentials);
+ expect((await evaluation.findPublicById(imported.id))?.name).toBe('Dataset mock');
+ expect(
+ await ConnectorModel.forEvaluation(serverDB, userId, 'wrong-dataset').findPublicById(
+ imported.id,
+ ),
+ ).toBeNull();
+ expect(
+ await ConnectorModel.forEvaluation(serverDB, otherUserId, 'ds-test').findPublicById(
+ imported.id,
+ ),
+ ).toBeNull();
+ });
+
describe('create', () => {
it('creates a connector without credentials', async () => {
const model = new ConnectorModel(serverDB, userId);
@@ -184,6 +415,7 @@ describe('ConnectorModel', () => {
metadata: {
customHeaders: { 'X-Private': 'secret' },
description: 'Public description',
+ mountedByAgentId: 'mounted-agent',
},
name: 'Public MCP',
oidcConfig: { clientSecret: 'secret', scheme: 'pre_registration' },
@@ -203,6 +435,7 @@ describe('ConnectorModel', () => {
description: 'Public description',
hasCredentials: true,
id: created.id,
+ mountedByAgentId: 'mounted-agent',
});
expect(found).not.toHaveProperty('credentials');
expect(found).not.toHaveProperty('metadata');
diff --git a/packages/database/src/models/__tests__/connectorAgentScope.test.ts b/packages/database/src/models/__tests__/connectorAgentScope.test.ts
index 03e80533a37..55363b7d180 100644
--- a/packages/database/src/models/__tests__/connectorAgentScope.test.ts
+++ b/packages/database/src/models/__tests__/connectorAgentScope.test.ts
@@ -4,6 +4,10 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
import { agents, userConnectors, userConnectorTools, users, workspaces } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
+import {
+ countAgentConnectorsAffected,
+ rehomeAgentConnectorsForScopeTransfer,
+} from '../../utils/agentConnectors';
import { ConnectorModel } from '../connector';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -58,6 +62,51 @@ afterEach(async () => {
});
describe('ConnectorModel agent-scoped resolution', () => {
+ it('keeps legacy eval rows and credentials out of normal Agent handovers', async () => {
+ const owned = await insertConnector({
+ agentId: agentA,
+ identifier: 'eval-owned',
+ name: 'Eval',
+ credentials: 'encrypted-owned',
+ metadata: { agentEval: { datasetId: 'dataset' } },
+ });
+ const mounted = await insertConnector({
+ identifier: 'eval-mounted',
+ name: 'Eval',
+ credentials: 'encrypted-mounted',
+ metadata: { agentEval: { datasetId: 'dataset' }, mountedByAgentId: agentA },
+ });
+ const ordinary = await insertConnector({
+ agentId: agentA,
+ identifier: 'ordinary',
+ name: 'Ordinary',
+ credentials: 'ordinary-auth',
+ });
+ expect(
+ await countAgentConnectorsAffected(serverDB, {
+ agentIds: [agentA],
+ recipientId: otherUserId,
+ }),
+ ).toBe(1);
+ await rehomeAgentConnectorsForScopeTransfer(serverDB, {
+ agentIds: [agentA],
+ targetUserId: otherUserId,
+ targetWorkspaceId: workspaceId,
+ });
+ for (const row of [owned, mounted]) {
+ const [stored] = await serverDB
+ .select()
+ .from(userConnectors)
+ .where(eq(userConnectors.id, row.id));
+ expect(stored).toEqual(row);
+ }
+ const [transferred] = await serverDB
+ .select()
+ .from(userConnectors)
+ .where(eq(userConnectors.id, ordinary.id));
+ expect(transferred).toMatchObject({ credentials: null, userId: otherUserId, workspaceId });
+ });
+
describe('resolveByIdentifiers (personal run)', () => {
it('prefers the agent-owned row over the base personal row (Agent > Personal)', async () => {
await insertConnector({ identifier: 'gmail', name: 'Personal Gmail' });
diff --git a/packages/database/src/models/__tests__/connectorTool.test.ts b/packages/database/src/models/__tests__/connectorTool.test.ts
index d0d02524b4e..28769063317 100644
--- a/packages/database/src/models/__tests__/connectorTool.test.ts
+++ b/packages/database/src/models/__tests__/connectorTool.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
import type { NewUserConnector } from '../../schemas';
import {
+ agentEvalDatasets,
ConnectorToolPermission,
ToolCRUDType,
userConnectors,
@@ -64,6 +65,29 @@ const tool = (overrides: Partial<SyncToolInput>): SyncToolInput => ({
});
describe('ConnectorToolModel', () => {
+ it('isolates eval tool IDs and mutations behind their owned Dataset scope', async () => {
+ await serverDB
+ .insert(agentEvalDatasets)
+ .values({ id: 'eval-dataset', identifier: 'eval-dataset', name: 'Eval', userId });
+ const id = await insertConnector({ metadata: { agentEval: { datasetId: 'eval-dataset' } } });
+ const evaluation = ConnectorToolModel.forEvaluation(serverDB, userId, 'eval-dataset');
+ const normal = new ConnectorToolModel(serverDB, userId);
+ await evaluation.upsertMany(id, [tool({ toolName: 'private-read' })]);
+ const [row] = await evaluation.queryByConnector(id);
+ expect(await normal.findById(row.id)).toBeUndefined();
+ expect(await normal.queryByConnector(id)).toEqual([]);
+ await expect(normal.upsertMany(id, [tool({ toolName: 'injected' })])).rejects.toThrow(
+ 'Connection not available',
+ );
+ await normal.deleteToolsNotIn(id, []);
+ expect(await evaluation.queryByConnector(id)).toHaveLength(1);
+ expect(
+ await ConnectorToolModel.forEvaluation(serverDB, userId, 'wrong-dataset').queryByConnector(
+ id,
+ ),
+ ).toEqual([]);
+ });
+
describe('upsertMany', () => {
it('returns early without inserting when the tool list is empty', async () => {
const model = new ConnectorToolModel(serverDB, userId);
diff --git a/packages/database/src/models/__tests__/plugin.test.ts b/packages/database/src/models/__tests__/plugin.test.ts
index d739f47cc93..30cc0c2548e 100644
--- a/packages/database/src/models/__tests__/plugin.test.ts
+++ b/packages/database/src/models/__tests__/plugin.test.ts
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
import type { NewInstalledPlugin } from '../../schemas';
-import { userInstalledPlugins, users } from '../../schemas';
+import { userInstalledPlugins, users, workspaces } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { PluginModel } from '../plugin';
@@ -24,6 +24,53 @@ afterEach(async () => {
});
describe('PluginModel', () => {
+ it('excludes quarantined evaluation installations from normal discovery and execution lookup', async () => {
+ await pluginModel.create({
+ identifier: 'eval-only',
+ type: 'customPlugin',
+ source: 'agent-eval',
+ });
+ await pluginModel.create({ identifier: 'ordinary', type: 'customPlugin' });
+ expect((await pluginModel.query()).map((p) => p.identifier)).toEqual(['ordinary']);
+ expect(await pluginModel.findById('eval-only')).toBeUndefined();
+ expect(await pluginModel.findById('ordinary')).toBeDefined();
+ });
+
+ it('installing a real plugin coexists with a legacy eval installation in another workspace and preserves its connection', async () => {
+ await serverDB.insert(workspaces).values({
+ id: 'legacy-eval-workspace',
+ name: 'Eval',
+ slug: 'legacy-eval',
+ primaryOwnerId: userId,
+ });
+ const evaluationModel = new PluginModel(serverDB, userId, 'legacy-eval-workspace');
+ await evaluationModel.create({
+ identifier: 'notion',
+ type: 'customPlugin',
+ source: 'agent-eval',
+ customParams: { mcp: { type: 'http', url: 'https://mock.invalid/mcp' } },
+ settings: { token: 'old-private-token' },
+ manifest: { identifier: 'notion' } as any,
+ });
+ await pluginModel.create({
+ identifier: 'notion',
+ type: 'plugin',
+ manifest: { identifier: 'notion', meta: { title: 'Notion' } } as any,
+ });
+ const saved = await pluginModel.findById('notion');
+ expect(saved?.source).toBeNull();
+ expect(saved?.customParams).toBeNull();
+ expect(saved?.settings).toBeNull();
+ expect((await pluginModel.query()).map((p) => p.identifier)).toEqual(['notion']);
+ const stored = await serverDB.select().from(userInstalledPlugins);
+ expect(stored).toHaveLength(2);
+ const evaluation = stored.find((p) => p.source === 'agent-eval');
+ expect(evaluation?.identifier).toMatch(/^agent-eval:/);
+ expect(evaluation?.manifest?.identifier).toBe('notion');
+ expect(evaluation?.customParams?.mcp?.url).toBe('https://mock.invalid/mcp');
+ expect(evaluation?.settings).toEqual({ token: 'old-private-token' });
+ });
+
describe('create', () => {
it('should create a new installed plugin', async () => {
const params = {
diff --git a/packages/database/src/models/agentEval/__tests__/benchmark.test.ts b/packages/database/src/models/agentEval/__tests__/benchmark.test.ts
index f8f7c5866fb..8a884de9606 100644
--- a/packages/database/src/models/agentEval/__tests__/benchmark.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/benchmark.test.ts
@@ -90,6 +90,28 @@ describe('AgentEvalBenchmarkModel', () => {
});
});
+ describe('releaseDatasets', () => {
+ it('frees the datasets of a benchmark the account may delete, so deleting it keeps them', async () => {
+ const [benchmark] = await serverDB
+ .insert(agentEvalBenchmarks)
+ .values({ identifier: 'release', isSystem: false, name: 'Release', rubrics: [], userId })
+ .returning();
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({ benchmarkId: benchmark.id, identifier: 'kept', name: 'Kept', userId })
+ .returning();
+
+ expect(await benchmarkModel2.releaseDatasets(benchmark.id)).toBe(0);
+ expect(await benchmarkModel.releaseDatasets(benchmark.id)).toBe(1);
+ await benchmarkModel.delete(benchmark.id);
+
+ const kept = await serverDB.query.agentEvalDatasets.findFirst({
+ where: eq(agentEvalDatasets.id, dataset.id),
+ });
+ expect(kept?.benchmarkId).toBeNull();
+ });
+ });
+
describe('delete', () => {
it('should delete a user-created benchmark', async () => {
const [benchmark] = await serverDB
@@ -241,7 +263,7 @@ describe('AgentEvalBenchmarkModel', () => {
expect(result.datasetCount).toBe(2);
});
- it('should return testCaseCount for benchmarks with test cases', async () => {
+ it('should count active test cases without retired historical rows', async () => {
const benchmarks = await serverDB.query.agentEvalBenchmarks.findMany();
const userBenchmark = benchmarks.find((b) => b.identifier === 'user-1')!;
@@ -256,11 +278,18 @@ describe('AgentEvalBenchmarkModel', () => {
})
.returning();
- // Add 3 test cases to the dataset
+ // Three runnable cases and one retired row kept for historical results.
await serverDB.insert(agentEvalTestCases).values([
{ datasetId: dataset.id, content: { input: 'test' }, sortOrder: 1, userId },
{ datasetId: dataset.id, content: { input: 'test' }, sortOrder: 2, userId },
{ datasetId: dataset.id, content: { input: 'test' }, sortOrder: 3, userId },
+ {
+ datasetId: dataset.id,
+ content: { input: 'retired' },
+ metadata: { retired: true },
+ sortOrder: 4,
+ userId,
+ },
]);
const results = await benchmarkModel.query(true);
diff --git a/packages/database/src/models/agentEval/__tests__/dataset.test.ts b/packages/database/src/models/agentEval/__tests__/dataset.test.ts
index 2f806ff8aa3..7c7824c7926 100644
--- a/packages/database/src/models/agentEval/__tests__/dataset.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/dataset.test.ts
@@ -123,51 +123,6 @@ describe('AgentEvalDatasetModel', () => {
});
});
- describe('delete', () => {
- it('should delete a dataset owned by the user', async () => {
- const [dataset] = await serverDB
- .insert(agentEvalDatasets)
- .values({
- benchmarkId,
- identifier: 'delete-test',
- name: 'Delete Test',
- userId,
- })
- .returning();
-
- await datasetModel.delete(dataset.id);
-
- const deleted = await serverDB.query.agentEvalDatasets.findFirst({
- where: eq(agentEvalDatasets.id, dataset.id),
- });
- expect(deleted).toBeUndefined();
- });
-
- it('should not delete a dataset owned by another user', async () => {
- const [dataset] = await serverDB
- .insert(agentEvalDatasets)
- .values({
- benchmarkId,
- identifier: 'other-user-dataset',
- name: 'Other User Dataset',
- userId: userId2,
- })
- .returning();
-
- await datasetModel.delete(dataset.id);
-
- const stillExists = await serverDB.query.agentEvalDatasets.findFirst({
- where: eq(agentEvalDatasets.id, dataset.id),
- });
- expect(stillExists).toBeDefined();
- });
-
- it('should return 0 rowCount when dataset not found', async () => {
- await datasetModel.delete('non-existent-id');
- // No rowCount in PGlite
- });
- });
-
describe('query', () => {
beforeEach(async () => {
// Create another benchmark
diff --git a/packages/database/src/models/agentEval/__tests__/datasetAccess.test.ts b/packages/database/src/models/agentEval/__tests__/datasetAccess.test.ts
new file mode 100644
index 00000000000..f63d64c2ae4
--- /dev/null
+++ b/packages/database/src/models/agentEval/__tests__/datasetAccess.test.ts
@@ -0,0 +1,360 @@
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { AgentEvalDatasetDeletionRepo } from '../../../repositories/agentEvalDatasetDeletion';
+import {
+ agentEvalDatasets,
+ agentEvalEnvironments,
+ agentEvalRuns,
+ agentEvalRunTopics,
+ agentEvalTestCases,
+ topics,
+ users,
+ workspaces,
+} from '../../../schemas';
+import { AgentEvalDatasetModel } from '../dataset';
+import { AgentEvalDatasetWriteError } from '../datasetAccess';
+import { AgentEvalTestCaseModel, isRetiredEvalTestCase } from '../testCase';
+
+const db = await getTestDB();
+const userId = 'data-integrity-user';
+const otherUserId = 'data-integrity-other';
+const workspaceId = 'data-integrity-workspace';
+const otherWorkspaceId = 'data-integrity-other-workspace';
+const datasets = new AgentEvalDatasetModel(db, userId);
+const cases = new AgentEvalTestCaseModel(db, userId);
+const fixedMetadata = { custom: true, kind: 'lobe-bench', release: 'release-v1' };
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await db.insert(workspaces).values([
+ { id: workspaceId, name: 'Workspace', primaryOwnerId: userId, slug: workspaceId },
+ {
+ id: otherWorkspaceId,
+ name: 'Other workspace',
+ primaryOwnerId: otherUserId,
+ slug: otherWorkspaceId,
+ },
+ ]);
+});
+
+afterEach(async () => {
+ await db.delete(agentEvalRunTopics);
+ await db.delete(agentEvalRuns);
+ await db.delete(topics);
+ await db.delete(agentEvalTestCases);
+ await db.delete(agentEvalDatasets);
+ await db.delete(agentEvalEnvironments);
+ await db.delete(workspaces);
+ await db.delete(users);
+});
+
+const newDataset = (identifier = 'own', metadata?: Record<string, unknown>) =>
+ datasets.create({ identifier, metadata, name: identifier });
+
+describe('case parent authorization', () => {
+ it('rejects foreign, system, missing and cross-workspace parents without inserting', async () => {
+ const own = await newDataset();
+ const rows = await db
+ .insert(agentEvalDatasets)
+ .values([
+ { identifier: 'foreign', name: 'Foreign', userId: otherUserId },
+ { identifier: 'system', name: 'System', userId: null },
+ { identifier: 'own-workspace', name: 'Workspace', userId, workspaceId },
+ ])
+ .returning();
+ for (const datasetId of [...rows.map((row) => row.id), 'missing']) {
+ await expect(
+ cases.create({ content: { input: 'Blocked' }, datasetId }),
+ ).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ await expect(
+ cases.batchCreate([
+ { content: { input: 'Should roll back too' }, datasetId: own.id },
+ { content: { input: 'Blocked' }, datasetId },
+ ]),
+ ).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ }
+ expect(await db.select().from(agentEvalTestCases)).toEqual([]);
+ });
+
+ it('allows workspace collaborators while rejecting personal, other-workspace and system parents', async () => {
+ const workspaceCases = new AgentEvalTestCaseModel(db, userId, workspaceId);
+ const [shared, foreignWorkspace, personal, system] = await db
+ .insert(agentEvalDatasets)
+ .values([
+ { identifier: 'shared', name: 'Shared', userId: otherUserId, workspaceId },
+ { identifier: 'foreign-workspace', name: 'Foreign', userId, workspaceId: otherWorkspaceId },
+ { identifier: 'personal', name: 'Personal', userId },
+ { identifier: 'system-workspace', name: 'System', userId: null, workspaceId },
+ ])
+ .returning();
+ const added = await workspaceCases.create({
+ content: { input: 'Shared case' },
+ datasetId: shared.id,
+ workspaceId: otherWorkspaceId,
+ });
+ expect(added).toMatchObject({ userId, workspaceId });
+ for (const row of [foreignWorkspace, personal, system]) {
+ await expect(
+ workspaceCases.create({ content: { input: 'Blocked' }, datasetId: row.id }),
+ ).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ }
+ });
+
+ it('normalizes blank workspace scopes consistently for parent lookup and insertion', async () => {
+ const own = await newDataset();
+ const result = await new AgentEvalTestCaseModel(db, userId, ' ').create({
+ content: { input: 'Personal' },
+ datasetId: own.id,
+ });
+ expect(result.workspaceId).toBeNull();
+ expect(await cases.batchCreate([])).toEqual([]);
+ });
+
+ it('rejects unreadable environment references in every case write path', async () => {
+ const own = await newDataset();
+ const [foreign, ownEnvironment, system] = await db
+ .insert(agentEvalEnvironments)
+ .values([
+ { config: {}, name: 'Foreign', userId: otherUserId },
+ { config: {}, name: 'Own', userId },
+ { config: {}, name: 'System', userId: null },
+ ])
+ .returning();
+ const first = await cases.create({
+ content: { input: 'Own environment' },
+ datasetId: own.id,
+ environmentId: ownEnvironment.id,
+ });
+ await cases.create({
+ content: { input: 'System environment' },
+ datasetId: own.id,
+ environmentId: system.id,
+ });
+ await expect(
+ cases.create({ content: { input: 'Blocked' }, datasetId: own.id, environmentId: foreign.id }),
+ ).rejects.toThrow('Environment not found or not readable');
+ await expect(
+ cases.batchCreate([
+ { content: { input: 'Would be valid' }, datasetId: own.id },
+ { content: { input: 'Blocked' }, datasetId: own.id, environmentId: foreign.id },
+ ]),
+ ).rejects.toThrow('Environment not found or not readable');
+ await expect(cases.update(first.id, { environmentId: foreign.id })).rejects.toThrow(
+ 'Environment not found or not readable',
+ );
+ await expect(
+ datasets.create({ identifier: 'blocked-copy', name: 'Blocked' }, [
+ { content: { input: 'Blocked' }, environmentId: foreign.id },
+ ]),
+ ).rejects.toThrow('Environment not found or not readable');
+ expect(await cases.countByDatasetId(own.id)).toBe(2);
+ expect((await datasets.queryList()).map((row) => row.id)).toEqual([own.id]);
+ });
+
+ it('accepts a collaborator environment only in the matching workspace', async () => {
+ const workspaceDatasets = new AgentEvalDatasetModel(db, userId, workspaceId);
+ const [shared, foreign] = await db
+ .insert(agentEvalEnvironments)
+ .values([
+ { config: {}, name: 'Shared', userId: otherUserId, workspaceId },
+ { config: {}, name: 'Foreign workspace', userId, workspaceId: otherWorkspaceId },
+ ])
+ .returning();
+ const dataset = await workspaceDatasets.create({ identifier: 'shared-copy', name: 'Shared' }, [
+ { content: { input: 'Shared' }, environmentId: shared.id },
+ ]);
+ expect((await workspaceDatasets.findById(dataset.id))?.testCases[0].workspaceId).toBe(
+ workspaceId,
+ );
+ await expect(
+ workspaceDatasets.create({ identifier: 'foreign-copy', name: 'Foreign' }, [
+ { content: { input: 'Foreign' }, environmentId: foreign.id },
+ ]),
+ ).rejects.toThrow('Environment not found or not readable');
+ });
+});
+
+describe('fixed Lobe Bench datasets', () => {
+ it('supports the legacy first batch, then rejects additions, edits and individual deletions', async () => {
+ const dataset = await newDataset('fixed', fixedMetadata);
+ const [first] = await cases.batchCreate([
+ { content: { input: 'First' }, datasetId: dataset.id },
+ { content: { input: 'Second' }, datasetId: dataset.id },
+ ]);
+ await expect(
+ cases.create({ content: { input: 'Extra' }, datasetId: dataset.id }),
+ ).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ await expect(
+ cases.batchCreate([{ content: { input: 'Extra' }, datasetId: dataset.id }]),
+ ).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ await expect(cases.update(first.id, { content: { input: 'Changed' } })).rejects.toBeInstanceOf(
+ AgentEvalDatasetWriteError,
+ );
+ await expect(cases.delete(first.id)).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ expect((await datasets.findById(dataset.id))?.testCases).toHaveLength(2);
+ });
+
+ it('allows only one concurrent initial fill', async () => {
+ const dataset = await newDataset('concurrent', fixedMetadata);
+ const results = await Promise.allSettled([
+ cases.batchCreate([{ content: { input: 'First' }, datasetId: dataset.id }]),
+ cases.batchCreate([{ content: { input: 'Second' }, datasetId: dataset.id }]),
+ ]);
+ expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1);
+ expect(await cases.countByDatasetId(dataset.id)).toBe(1);
+ });
+
+ it('preserves identity, version and grading configuration while allowing renaming', async () => {
+ const dataset = await newDataset('fixed', fixedMetadata);
+ for (const metadata of [
+ {},
+ { ...fixedMetadata, custom: false },
+ { ...fixedMetadata, release: 'v2' },
+ ]) {
+ await expect(datasets.update(dataset.id, { metadata })).rejects.toBeInstanceOf(
+ AgentEvalDatasetWriteError,
+ );
+ }
+ await expect(datasets.update(dataset.id, { evalMode: 'regex' })).rejects.toBeInstanceOf(
+ AgentEvalDatasetWriteError,
+ );
+ const renamed = await datasets.update(dataset.id, {
+ description: 'A fixed selection',
+ metadata: { ...fixedMetadata },
+ name: 'Renamed',
+ });
+ expect(renamed).toMatchObject({ metadata: fixedMetadata, name: 'Renamed' });
+ });
+
+ it('creates the dataset and its initial copied cases atomically and freezes the copies', async () => {
+ const dataset = await datasets.create(
+ { identifier: 'atomic', metadata: fixedMetadata, name: 'Atomic' },
+ [{ content: { input: 'Copied' }, metadata: { source: 'library' } }],
+ );
+ const [copied] = (await datasets.findById(dataset.id))!.testCases;
+ expect(copied).toMatchObject({ content: { input: 'Copied' }, sortOrder: 1, userId });
+ await expect(cases.update(copied.id, { content: { input: 'Changed' } })).rejects.toBeInstanceOf(
+ AgentEvalDatasetWriteError,
+ );
+ await expect(
+ datasets.create({ identifier: 'failed-copy', metadata: fixedMetadata, name: 'Failed' }, [
+ { content: { input: 'First copy' }, id: 'duplicate-case-id' },
+ { content: { input: 'Conflicting copy' }, id: 'duplicate-case-id' },
+ ]),
+ ).rejects.toThrow();
+ expect((await datasets.queryList()).map((row) => row.identifier)).toEqual(['atomic']);
+ });
+
+ it('keeps ordinary Eval Lab editing and explicit dataset deletion available', async () => {
+ const dataset = await newDataset('lab');
+ const first = await cases.create({ content: { input: 'First' }, datasetId: dataset.id });
+ const second = await cases.create({ content: { input: 'Second' }, datasetId: dataset.id });
+ expect(await cases.update(first.id, { content: { input: 'Edited' } })).toMatchObject({
+ content: { input: 'Edited' },
+ });
+ await cases.delete(second.id);
+ expect(await cases.countByDatasetId(dataset.id)).toBe(1);
+ const fixed = await datasets.create(
+ { identifier: 'fixed', metadata: fixedMetadata, name: 'Fixed' },
+ [{ content: { input: 'Copy' } }],
+ );
+ await new AgentEvalDatasetDeletionRepo(db, userId).deleteDataset(fixed.id);
+ expect(await datasets.findById(fixed.id)).toBeUndefined();
+ });
+});
+
+describe('retired cases preserve execution evidence', () => {
+ it.each([
+ { label: 'SQL null', metadata: null, active: true },
+ { label: 'missing key', metadata: {}, active: true },
+ { label: 'JSON null', metadata: { retired: null }, active: true },
+ { label: 'boolean false', metadata: { retired: false }, active: true },
+ { label: 'string true', metadata: { retired: 'true' }, active: true },
+ { label: 'boolean true', metadata: { retired: true }, active: false },
+ ])('treats only boolean true as retired: $label', async ({ metadata, active }) => {
+ const dataset = await newDataset();
+ const [row] = await db
+ .insert(agentEvalTestCases)
+ .values({
+ content: { input: 'Question' },
+ datasetId: dataset.id,
+ metadata,
+ userId,
+ })
+ .returning();
+ expect((await cases.findByDatasetId(dataset.id)).map((item) => item.id)).toEqual(
+ active ? [row.id] : [],
+ );
+ expect(await cases.findById(row.id)).toBeDefined();
+ });
+
+ it('keeps run topics, hides retired rows from catalog reads, and can reactivate the same id', async () => {
+ const [dataset] = await db
+ .insert(agentEvalDatasets)
+ .values({
+ identifier: 'system',
+ name: 'System',
+ userId: null,
+ })
+ .returning();
+ const [stale, active] = await db
+ .insert(agentEvalTestCases)
+ .values([
+ {
+ content: { input: 'Old' },
+ datasetId: dataset.id,
+ metadata: { caseId: 'old' },
+ userId: null,
+ },
+ {
+ content: { input: 'Current' },
+ datasetId: dataset.id,
+ metadata: { caseId: 'current' },
+ userId: null,
+ },
+ ])
+ .returning();
+ const [run] = await db
+ .insert(agentEvalRuns)
+ .values({ datasetId: dataset.id, name: 'History', userId })
+ .returning();
+ const [topic] = await db.insert(topics).values({ userId, title: 'History' }).returning();
+ const [result] = await db
+ .insert(agentEvalRunTopics)
+ .values({
+ evalResult: { externalResult: { passed: true, reason: 'Saved judge evidence', score: 1 } },
+ passed: true,
+ runId: run.id,
+ score: 1,
+ status: 'passed',
+ testCaseId: stale.id,
+ topicId: topic.id,
+ userId,
+ })
+ .returning();
+
+ await db
+ .update(agentEvalTestCases)
+ .set({ metadata: { ...stale.metadata, retired: true } })
+ .where(eq(agentEvalTestCases.id, stale.id));
+ expect(await db.select().from(agentEvalRunTopics)).toEqual([result]);
+ expect(isRetiredEvalTestCase((await cases.findById(stale.id))!)).toBe(true);
+ expect((await cases.findByDatasetId(dataset.id)).map((row) => row.id)).toEqual([active.id]);
+ expect(await cases.countByDatasetId(dataset.id)).toBe(1);
+ expect(await cases.findByDatasetIdAndCaseId(dataset.id, 'old')).toBeUndefined();
+ expect((await datasets.findById(dataset.id))?.testCases.map((row) => row.id)).toEqual([
+ active.id,
+ ]);
+ expect((await datasets.query())[0].testCaseCount).toBe(1);
+
+ // Reactivating the same row keeps its historical run results intact.
+ await db
+ .update(agentEvalTestCases)
+ .set({ metadata: { caseId: 'old' } })
+ .where(eq(agentEvalTestCases.id, stale.id));
+ expect(await cases.countByDatasetId(dataset.id)).toBe(2);
+ expect(await db.select().from(agentEvalRunTopics)).toEqual([result]);
+ });
+});
diff --git a/packages/database/src/models/agentEval/__tests__/datasetFreeze.test.ts b/packages/database/src/models/agentEval/__tests__/datasetFreeze.test.ts
new file mode 100644
index 00000000000..353cdff3be5
--- /dev/null
+++ b/packages/database/src/models/agentEval/__tests__/datasetFreeze.test.ts
@@ -0,0 +1,192 @@
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ agentEvalBenchmarks,
+ agentEvalDatasets,
+ agentEvalTestCases,
+ users,
+} from '../../../schemas';
+import { AgentEvalDatasetModel } from '../dataset';
+import { AgentEvalDatasetWriteError } from '../datasetAccess';
+import { AgentEvalTestCaseModel } from '../testCase';
+
+const db = await getTestDB();
+const userId = 'dataset-freeze-user';
+const datasets = new AgentEvalDatasetModel(db, userId);
+const cases = new AgentEvalTestCaseModel(db, userId);
+let lobeBenchId: string;
+let labId: string;
+
+beforeEach(async () => {
+ await db.insert(users).values({ id: userId });
+ const [bench, lab] = await db
+ .insert(agentEvalBenchmarks)
+ .values([
+ {
+ identifier: 'lobe-bench',
+ isSystem: true,
+ metadata: { kind: 'lobe-bench' },
+ name: 'Lobe Bench',
+ rubrics: [],
+ userId: null,
+ },
+ { identifier: 'lab', isSystem: false, name: 'Lab', rubrics: [], userId },
+ ])
+ .returning();
+ lobeBenchId = bench.id;
+ labId = lab.id;
+});
+
+afterEach(async () => {
+ await db.delete(agentEvalTestCases);
+ await db.delete(agentEvalDatasets);
+ await db.delete(agentEvalBenchmarks);
+ await db.delete(users);
+});
+
+describe('server-derived Lobe Bench dataset freezing', () => {
+ it.each([
+ undefined,
+ { kind: 'lobe-bench' },
+ { custom: false, kind: 'lobe-bench' },
+ { custom: false, kind: 'eval-lab' },
+ ])('freezes an atomic API creation under Lobe Bench with metadata %o', async (metadata) => {
+ // createDataset accepts optional metadata and passes it straight to this model.
+ const dataset = await datasets.create(
+ { benchmarkId: lobeBenchId, identifier: 'api-created', metadata, name: 'API created' },
+ [{ content: { input: 'Original' } }],
+ );
+ expect(dataset).toMatchObject({ metadata: { custom: true, kind: 'lobe-bench' }, userId });
+ expect((await datasets.query({ benchmarkId: lobeBenchId })).map((row) => row.id)).toContain(
+ dataset.id,
+ );
+ const [testCase] = (await datasets.findById(dataset.id))!.testCases;
+ await expect(
+ cases.update(testCase.id, { content: { input: 'Changed' } }),
+ ).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ await expect(datasets.update(dataset.id, { metadata: {} })).rejects.toBeInstanceOf(
+ AgentEvalDatasetWriteError,
+ );
+ });
+
+ it('allows the first fill of an unmarked empty dataset, then freezes it', async () => {
+ const dataset = await datasets.create({
+ benchmarkId: lobeBenchId,
+ identifier: 'empty',
+ name: 'Empty',
+ });
+ const [first] = await cases.batchCreate([
+ { content: { input: 'First' }, datasetId: dataset.id },
+ ]);
+ expect(first).toBeDefined();
+ await expect(
+ cases.batchCreate([{ content: { input: 'Extra' }, datasetId: dataset.id }]),
+ ).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ expect(await cases.countByDatasetId(dataset.id)).toBe(1);
+ });
+
+ it('protects legacy unmarked datasets and keeps them frozen after moving out', async () => {
+ const [legacy] = await db
+ .insert(agentEvalDatasets)
+ .values({
+ benchmarkId: lobeBenchId,
+ identifier: 'legacy',
+ name: 'Legacy',
+ userId,
+ })
+ .returning();
+ const [testCase] = await db
+ .insert(agentEvalTestCases)
+ .values({
+ content: { input: 'Original' },
+ datasetId: legacy.id,
+ userId,
+ })
+ .returning();
+ await expect(cases.delete(testCase.id)).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ await expect(datasets.update(legacy.id, { evalMode: 'regex' })).rejects.toBeInstanceOf(
+ AgentEvalDatasetWriteError,
+ );
+ const moved = await datasets.update(legacy.id, { benchmarkId: labId, name: 'Moved' });
+ expect(moved?.metadata).toMatchObject({ custom: true, kind: 'lobe-bench' });
+ await expect(
+ cases.update(testCase.id, { content: { input: 'Changed' } }),
+ ).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ await expect(datasets.update(legacy.id, { metadata: {} })).rejects.toBeInstanceOf(
+ AgentEvalDatasetWriteError,
+ );
+ });
+
+ it('keeps ordinary Lab editable, then freezes a dataset moved into Lobe Bench', async () => {
+ const dataset = await datasets.create(
+ { benchmarkId: labId, identifier: 'lab-data', name: 'Lab data' },
+ [{ content: { input: 'Original' } }],
+ );
+ const [first] = (await datasets.findById(dataset.id))!.testCases;
+ expect(await cases.update(first.id, { content: { input: 'Editable in Lab' } })).toMatchObject({
+ content: { input: 'Editable in Lab' },
+ });
+ const moved = await datasets.update(dataset.id, { benchmarkId: lobeBenchId });
+ expect(moved?.metadata).toMatchObject({ custom: true, kind: 'lobe-bench' });
+ await expect(
+ cases.create({ content: { input: 'Extra' }, datasetId: dataset.id }),
+ ).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ await datasets.update(dataset.id, { benchmarkId: labId });
+ await expect(cases.delete(first.id)).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ });
+
+ it('classifies existing datasets by the current parent kind without granting parent write rights', async () => {
+ const dataset = await datasets.create(
+ { benchmarkId: labId, identifier: 'reclassified', name: 'Reclassified' },
+ [{ content: { input: 'Original' } }],
+ );
+ await db
+ .update(agentEvalBenchmarks)
+ .set({ metadata: { kind: 'lobe-bench' } })
+ .where(eq(agentEvalBenchmarks.id, labId));
+ const [first] = (await datasets.findById(dataset.id))!.testCases;
+ await expect(cases.update(first.id, { content: { input: 'Changed' } })).rejects.toBeInstanceOf(
+ AgentEvalDatasetWriteError,
+ );
+ expect((await datasets.update(dataset.id, { name: 'Renamed' }))?.metadata).toMatchObject({
+ custom: true,
+ kind: 'lobe-bench',
+ });
+ });
+
+ it('recognizes dataset kind even with a false custom marker and no Lobe Bench parent', async () => {
+ const dataset = await datasets.create(
+ {
+ benchmarkId: labId,
+ identifier: 'marked',
+ metadata: { custom: false, kind: 'lobe-bench' },
+ name: 'Marked',
+ },
+ [{ content: { input: 'Original' } }],
+ );
+ await expect(
+ cases.create({ content: { input: 'Extra' }, datasetId: dataset.id }),
+ ).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ expect(dataset.metadata).toMatchObject({ custom: true, kind: 'lobe-bench' });
+ });
+
+ it('does not turn system datasets into writable or custom user datasets', async () => {
+ const [system] = await db
+ .insert(agentEvalDatasets)
+ .values({
+ benchmarkId: lobeBenchId,
+ identifier: 'system',
+ metadata: { kind: 'lobe-bench' },
+ name: 'System',
+ userId: null,
+ })
+ .returning();
+ await expect(
+ cases.create({ content: { input: 'Injected' }, datasetId: system.id }),
+ ).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ expect(await datasets.update(system.id, { name: 'Changed' })).toBeUndefined();
+ expect((await datasets.findById(system.id))?.metadata).toEqual({ kind: 'lobe-bench' });
+ });
+});
diff --git a/packages/database/src/models/agentEval/__tests__/environment.test.ts b/packages/database/src/models/agentEval/__tests__/environment.test.ts
new file mode 100644
index 00000000000..709a47be703
--- /dev/null
+++ b/packages/database/src/models/agentEval/__tests__/environment.test.ts
@@ -0,0 +1,65 @@
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agentEvalEnvironments, agentEvalTestCases, users } from '../../../schemas';
+import { AgentEvalEnvironmentModel } from '../environment';
+
+const serverDB = await getTestDB();
+
+const userId = 'environment-test-user';
+const otherUserId = 'environment-test-other-user';
+const environmentModel = new AgentEvalEnvironmentModel(serverDB, userId);
+
+beforeEach(async () => {
+ await serverDB.delete(agentEvalTestCases);
+ await serverDB.delete(agentEvalEnvironments);
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(agentEvalTestCases);
+ await serverDB.delete(agentEvalEnvironments);
+ await serverDB.delete(users);
+});
+
+describe('AgentEvalEnvironmentModel', () => {
+ it('creates environments owned by the actor', async () => {
+ const created = await environmentModel.create({
+ config: { sessionDate: '2026-07-24' },
+ name: 'Mine',
+ });
+ expect(created.userId).toBe(userId);
+ expect((await environmentModel.findById(created.id))?.name).toBe('Mine');
+ });
+
+ it('reads system environments (userId null) next to its own, never another user’s', async () => {
+ await serverDB.insert(agentEvalEnvironments).values([
+ { config: {}, identifier: 'env-system', name: 'System', userId: null },
+ { config: {}, identifier: 'env-mine', name: 'Mine', userId },
+ { config: {}, identifier: 'env-theirs', name: 'Theirs', userId: otherUserId },
+ ]);
+
+ const listed = await environmentModel.query();
+ expect(listed.map((e) => e.identifier).sort()).toEqual(['env-mine', 'env-system']);
+ expect((await environmentModel.findByIdentifier('env-system'))?.name).toBe('System');
+ expect(await environmentModel.findByIdentifier('env-theirs')).toBeUndefined();
+ });
+
+ it('never updates or deletes a system environment', async () => {
+ const [system] = await serverDB
+ .insert(agentEvalEnvironments)
+ .values({ config: {}, identifier: 'env-system', name: 'System', userId: null })
+ .returning();
+
+ expect(await environmentModel.update(system.id, { name: 'Changed' })).toBeUndefined();
+ await environmentModel.delete(system.id);
+
+ const [still] = await serverDB
+ .select()
+ .from(agentEvalEnvironments)
+ .where(eq(agentEvalEnvironments.id, system.id));
+ expect(still.name).toBe('System');
+ });
+});
diff --git a/packages/database/src/models/agentEval/__tests__/environmentBindings.test.ts b/packages/database/src/models/agentEval/__tests__/environmentBindings.test.ts
new file mode 100644
index 00000000000..0a5e6a4120c
--- /dev/null
+++ b/packages/database/src/models/agentEval/__tests__/environmentBindings.test.ts
@@ -0,0 +1,174 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ agentEvalDatasets,
+ agentEvalEnvironments,
+ agentEvalTestCases,
+ users,
+} from '../../../schemas';
+import { ConnectorModel } from '../../connector';
+import { AgentEvalDatasetModel } from '../dataset';
+import { AgentEvalEnvironmentModel } from '../environment';
+import { AgentEvalTestCaseModel } from '../testCase';
+
+const db = await getTestDB();
+const userId = 'eval-environment-binding-owner';
+const datasets = new AgentEvalDatasetModel(db, userId);
+const cases = new AgentEvalTestCaseModel(db, userId);
+const environments = new AgentEvalEnvironmentModel(db, userId);
+
+beforeEach(async () => {
+ await db.insert(users).values({ id: userId });
+});
+afterEach(async () => {
+ await db.delete(agentEvalTestCases);
+ await db.delete(agentEvalEnvironments);
+ await db.delete(agentEvalDatasets);
+ await db.delete(users);
+});
+
+const fixture = async () => {
+ const first = await datasets.create({ identifier: 'first', name: 'First Dataset' });
+ const second = await datasets.create({ identifier: 'second', name: 'Second Dataset' });
+ const connector = await ConnectorModel.forEvaluation(db, userId, first.id).create({
+ identifier: 'first-connection',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://fixture.test/mcp/first/notion',
+ name: 'Notion',
+ sourceType: 'custom',
+ status: 'connected',
+ });
+ const config = { connectorBindings: { notion: { connectorId: connector.id } } };
+ const environment = await environments.create({ config, name: 'First Dataset environment' });
+ return { config, connector, environment, first, second };
+};
+
+describe('Dataset ownership of assigned Environment connections', () => {
+ it('rejects a same-owner other-Dataset Environment in create, batch, update, and dataset copies atomically', async () => {
+ const { environment, first, second } = await fixture();
+ const original = await cases.create({ content: { input: 'Original' }, datasetId: second.id });
+ const foreignAssignment = {
+ content: { input: 'Cross Dataset' },
+ datasetId: second.id,
+ environmentId: environment.id,
+ };
+ await expect(cases.create(foreignAssignment)).rejects.toThrow('another Dataset');
+ await expect(
+ cases.batchCreate([{ ...foreignAssignment, datasetId: first.id }, foreignAssignment]),
+ ).rejects.toThrow('another Dataset');
+ await expect(cases.update(original.id, { environmentId: environment.id })).rejects.toThrow(
+ 'another Dataset',
+ );
+ await expect(
+ datasets.create({ identifier: 'copy', name: 'Copy' }, [
+ { content: { input: 'Copy' }, environmentId: environment.id },
+ ]),
+ ).rejects.toThrow('another Dataset');
+ expect(await db.select().from(agentEvalTestCases)).toEqual([original]);
+ expect((await datasets.queryList()).map(({ id }) => id).sort()).toEqual(
+ [first.id, second.id].sort(),
+ );
+ });
+
+ it('also rejects cross-Dataset inline bindings through direct model calls and preserves prior content', async () => {
+ const { config, first, second } = await fixture();
+ const original = await cases.create({ content: { input: 'Original' }, datasetId: second.id });
+ const foreignAssignment = {
+ content: { environment: config, input: 'Cross Dataset' },
+ datasetId: second.id,
+ };
+ await expect(cases.create(foreignAssignment)).rejects.toThrow('another Dataset');
+ await expect(
+ cases.batchCreate([{ ...foreignAssignment, datasetId: first.id }, foreignAssignment]),
+ ).rejects.toThrow('another Dataset');
+ await expect(cases.update(original.id, { content: { environment: config } })).rejects.toThrow(
+ 'another Dataset',
+ );
+ await expect(
+ datasets.create({ identifier: 'inline-copy', name: 'Copy' }, [foreignAssignment]),
+ ).rejects.toThrow('another Dataset');
+ expect(await cases.findById(original.id)).toEqual(original);
+ expect(await db.select().from(agentEvalTestCases)).toEqual([original]);
+ expect(await datasets.count()).toBe(2);
+ });
+
+ it('validates all referenced bindings even when the case overrides them with an empty set', async () => {
+ const { environment, second } = await fixture();
+ await expect(
+ cases.create({
+ content: { environment: { connectorBindings: {} }, input: 'Shadowed' },
+ datasetId: second.id,
+ environmentId: environment.id,
+ }),
+ ).rejects.toThrow('another Dataset');
+ expect(await db.select().from(agentEvalTestCases)).toEqual([]);
+ });
+
+ it('allows same-Dataset shared and inline connections across environments and case updates', async () => {
+ const { config, environment, first } = await fixture();
+ const secondEnvironment = await environments.create({ config, name: 'Another environment' });
+ const firstCase = await cases.create({
+ content: { input: 'Shared' },
+ datasetId: first.id,
+ environmentId: environment.id,
+ });
+ const added = await cases.batchCreate([
+ { content: { input: 'Another' }, datasetId: first.id, environmentId: secondEnvironment.id },
+ { content: { environment: config, input: 'Inline' }, datasetId: first.id },
+ ]);
+ expect(added).toHaveLength(2);
+ expect(
+ await cases.update(firstCase.id, {
+ content: { environment: config },
+ environmentId: secondEnvironment.id,
+ }),
+ ).toMatchObject({ content: { environment: config, input: 'Shared' } });
+ });
+
+ it('keeps environments without bindings reusable across Datasets and dataset creation', async () => {
+ const first = await datasets.create({ identifier: 'first', name: 'First' });
+ const second = await datasets.create({ identifier: 'second', name: 'Second' });
+ const environment = await environments.create({
+ config: { connectorBindings: {}, mock: { services: ['notion'] } },
+ name: 'Unbound shared environment',
+ });
+ const added = await cases.batchCreate(
+ [first, second].map(({ id }) => ({
+ content: { input: 'Shared' },
+ datasetId: id,
+ environmentId: environment.id,
+ })),
+ );
+ expect(added).toHaveLength(2);
+ const copy = await datasets.create({ identifier: 'copy', name: 'Copy' }, [
+ { content: { input: 'Copied' }, environmentId: environment.id },
+ ]);
+ expect((await datasets.findById(copy.id))?.testCases).toHaveLength(1);
+ });
+
+ it('rejects ordinary or missing connection UUIDs even from an otherwise readable Environment', async () => {
+ const dataset = await datasets.create({ identifier: 'ordinary', name: 'Dataset' });
+ const ordinary = await new ConnectorModel(db, userId).create({
+ identifier: 'notion',
+ name: 'Notion',
+ sourceType: 'custom',
+ status: 'connected',
+ });
+ for (const connectorId of [ordinary.id, crypto.randomUUID()]) {
+ const environment = await environments.create({
+ config: { connectorBindings: { notion: { connectorId } } },
+ name: 'Invalid connection environment',
+ });
+ await expect(
+ cases.create({
+ content: { input: 'Unavailable' },
+ datasetId: dataset.id,
+ environmentId: environment.id,
+ }),
+ ).rejects.toThrow('another Dataset');
+ }
+ expect(await db.select().from(agentEvalTestCases)).toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/agentEval/__tests__/environmentUpdates.test.ts b/packages/database/src/models/agentEval/__tests__/environmentUpdates.test.ts
new file mode 100644
index 00000000000..b377f14da0e
--- /dev/null
+++ b/packages/database/src/models/agentEval/__tests__/environmentUpdates.test.ts
@@ -0,0 +1,111 @@
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agentEvalEnvironments, users } from '../../../schemas';
+import { AgentEvalEnvironmentBindingError, AgentEvalEnvironmentModel } from '../environment';
+
+const db = await getTestDB();
+const userId = 'atomic-environment-owner';
+const otherId = 'atomic-environment-other';
+const model = new AgentEvalEnvironmentModel(db, userId);
+const originalBindings = { notion: { connectorId: '11111111-1111-4111-8111-111111111111' } };
+const repairedBindings = { notion: { connectorId: '22222222-2222-4222-8222-222222222222' } };
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: userId }, { id: otherId }]);
+});
+afterEach(async () => {
+ await db.delete(agentEvalEnvironments);
+ await db.delete(users);
+});
+
+describe('Atomic Environment configuration updates', () => {
+ it.each(['omitted', 'stale'] as const)(
+ 'preserves a concurrent connection repair when submitted bindings are %s',
+ async (mode) => {
+ const original = await model.create({
+ config: { agent: { systemRole: 'Original persona' }, connectorBindings: originalBindings },
+ name: 'Shared environment',
+ });
+ let announceLock!: () => void;
+ let finishRepair!: () => void;
+ const locked = new Promise<void>((resolve) => {
+ announceLock = resolve;
+ });
+ const release = new Promise<void>((resolve) => {
+ finishRepair = resolve;
+ });
+ // Reproduce the Dataset repair transaction's row-lock/write sequence.
+ const repair = db.transaction(async (tx) => {
+ const [current] = await tx
+ .select()
+ .from(agentEvalEnvironments)
+ .where(eq(agentEvalEnvironments.id, original.id))
+ .for('update');
+ announceLock();
+ await release;
+ await tx
+ .update(agentEvalEnvironments)
+ .set({
+ config: { ...current.config, connectorBindings: repairedBindings },
+ })
+ .where(eq(agentEvalEnvironments.id, original.id));
+ });
+ await locked;
+ const save = model.update(original.id, {
+ config: {
+ agent: { systemRole: 'Edited persona' },
+ ...(mode === 'stale' ? { connectorBindings: originalBindings } : {}),
+ },
+ });
+ const checked =
+ mode === 'stale'
+ ? expect(save).rejects.toBeInstanceOf(AgentEvalEnvironmentBindingError)
+ : expect(save).resolves.toMatchObject({
+ config: { connectorBindings: repairedBindings },
+ });
+ finishRepair();
+ await Promise.all([repair, checked]);
+ expect((await model.findById(original.id))?.config).toEqual({
+ agent: { systemRole: mode === 'stale' ? 'Original persona' : 'Edited persona' },
+ connectorBindings: repairedBindings,
+ });
+ },
+ );
+
+ it('accepts the unchanged migration configuration but rejects an explicit clear', async () => {
+ const original = await model.create({
+ config: { connectorBindings: originalBindings },
+ name: 'Migration',
+ });
+ await expect(
+ model.update(original.id, {
+ config: {
+ connectorBindings: { notion: { transport: 'mcp', ...originalBindings.notion } },
+ timezone: 'UTC',
+ },
+ }),
+ ).resolves.toMatchObject({ config: { connectorBindings: originalBindings, timezone: 'UTC' } });
+ await expect(
+ model.update(original.id, { config: { connectorBindings: {} } }),
+ ).rejects.toBeInstanceOf(AgentEvalEnvironmentBindingError);
+ expect((await model.findById(original.id))?.config).toEqual({
+ connectorBindings: originalBindings,
+ timezone: 'UTC',
+ });
+ });
+
+ it("does not lock or update a different owner's Environment", async () => {
+ const original = await new AgentEvalEnvironmentModel(db, otherId).create({
+ config: { connectorBindings: originalBindings },
+ name: 'Other owner',
+ });
+ expect(await model.update(original.id, { config: { connectorBindings: {} } })).toBeUndefined();
+ const [stored] = await db
+ .select()
+ .from(agentEvalEnvironments)
+ .where(eq(agentEvalEnvironments.id, original.id));
+ expect(stored.config.connectorBindings).toEqual(originalBindings);
+ });
+});
diff --git a/packages/database/src/models/agentEval/__tests__/run.projections.test.ts b/packages/database/src/models/agentEval/__tests__/run.projections.test.ts
new file mode 100644
index 00000000000..971f15473e3
--- /dev/null
+++ b/packages/database/src/models/agentEval/__tests__/run.projections.test.ts
@@ -0,0 +1,220 @@
+import type { EvalConnectorSnapshots, EvalRunConfig } from '@lobechat/types';
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agentEvalDatasets, agentEvalRuns, users, workspaces } from '../../../schemas';
+import { AgentEvalRunModel } from '../run';
+
+const db = await getTestDB();
+const owner = 'run-projection-owner';
+const otherOwner = 'run-projection-other-owner';
+const workspaceId = 'run-projection-workspace';
+const otherWorkspaceId = 'run-projection-other-workspace';
+const model = new AgentEvalRunModel(db, owner);
+const caseId = "case_'quoted/{key}";
+let datasetId: string;
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: owner }, { id: otherOwner }]);
+ await db.insert(workspaces).values(
+ [workspaceId, otherWorkspaceId].map((id) => ({
+ id,
+ name: id,
+ primaryOwnerId: owner,
+ slug: id,
+ })),
+ );
+ const [dataset] = await db
+ .insert(agentEvalDatasets)
+ .values({ identifier: 'projection', name: 'Projection', userId: owner })
+ .returning();
+ datasetId = dataset.id;
+});
+
+afterEach(async () => {
+ await db.delete(workspaces).where(inArray(workspaces.id, [workspaceId, otherWorkspaceId]));
+ await db.delete(users).where(inArray(users.id, [owner, otherOwner]));
+});
+
+const caseSnapshots = (): EvalConnectorSnapshots => ({
+ notion: {
+ connectorId: '00000000-0000-4000-8000-000000000001',
+ datasetId,
+ fingerprint: 'sha256:original-contract-fingerprint',
+ manifest: {
+ api: [
+ {
+ description: 'Original detailed contract. '.repeat(2500),
+ name: 'API-post-search',
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ filter: {
+ properties: { value: { enum: ['page', 'data_source'], type: 'string' } },
+ required: ['value'],
+ type: 'object',
+ },
+ query: { description: 'Unicode ζŸ₯θ―’ and exact spacing', type: 'string' },
+ },
+ required: ['query'],
+ type: 'object',
+ },
+ },
+ ],
+ identifier: 'notion',
+ meta: { description: 'Original Notion tools', title: 'Notion' },
+ systemRole: 'Keep the original contract, including this instruction.',
+ type: 'mcp',
+ },
+ transport: 'mcp',
+ },
+});
+
+const baseConfig: EvalRunConfig = {
+ caseSelection: { mode: 'all' },
+ chatConfig: { reasoningEffort: 'high' },
+ executionMode: 'internal',
+ k: 3,
+ maxSteps: 24,
+ model: 'fixture-model',
+ params: { frequency_penalty: 0, temperature: 0.35, top_p: 0.9 },
+ provider: 'fixture-provider',
+ unknownFutureOption: { enabled: false, value: null },
+};
+
+const readStored = async (id: string) => {
+ const [run] = await db.select().from(agentEvalRuns).where(eq(agentEvalRuns.id, id));
+ return run;
+};
+
+describe('AgentEvalRunModel SQL projections', () => {
+ it('keeps the exact current-case frozen contract while 49 other cases do not increase its payload', async () => {
+ const current = caseSnapshots();
+ const run = await model.create({
+ config: { ...baseConfig, connectorSnapshots: { [caseId]: current } },
+ datasetId,
+ });
+ const single = await model.findForCase(run.id, caseId);
+ const allSnapshots = Object.fromEntries([
+ [caseId, current],
+ ...Array.from({ length: 49 }, (_, index) => [`other-case-${index}`, caseSnapshots()]),
+ ]);
+ await model.update(run.id, { config: { ...baseConfig, connectorSnapshots: allSnapshots } });
+ const storedBefore = await readStored(run.id);
+
+ const projected = await model.findForCase(run.id, caseId);
+ const full = await model.findById(run.id);
+
+ expect(projected?.config).toEqual({ ...baseConfig, connectorSnapshots: { [caseId]: current } });
+ expect(projected?.config).toEqual(single?.config);
+ expect(Buffer.byteLength(JSON.stringify(projected?.config))).toBe(
+ Buffer.byteLength(JSON.stringify(single?.config)),
+ );
+ expect(Buffer.byteLength(JSON.stringify(full?.config))).toBeGreaterThan(
+ Buffer.byteLength(JSON.stringify(projected?.config)) * 45,
+ );
+ expect(projected).toEqual({ ...full, config: projected?.config });
+ expect(full?.config?.connectorSnapshots).toEqual(allSnapshots);
+ expect((await model.findSummaryById(run.id))?.config).toEqual(baseConfig);
+ expect(await readStored(run.id)).toEqual(storedBefore);
+ });
+
+ it('returns compact detail and list summaries without changing complete findById or stored evidence', async () => {
+ const config = { ...baseConfig, connectorSnapshots: { [caseId]: caseSnapshots() } };
+ const run = await model.create({
+ config,
+ datasetId,
+ metrics: { averageScore: 0, failedCases: 0, passRate: 0, passedCases: 0, totalCases: 1 },
+ status: 'pending',
+ });
+ const storedBefore = await readStored(run.id);
+
+ const summary = await model.findSummaryById(run.id);
+ const listed = await model.query({ datasetId, limit: 1, status: 'pending' });
+ const full = await model.findById(run.id);
+
+ expect(summary).toEqual({ ...full, config: baseConfig });
+ expect(summary?.hasUnverifiedAttempts).toBe(true);
+ expect(listed).toEqual([summary]);
+ expect(summary?.config).not.toHaveProperty('connectorSnapshots');
+ expect(full?.config).toEqual(config);
+ expect(await readStored(run.id)).toEqual(storedBefore);
+ });
+
+ it.each([
+ { config: null, name: 'SQL null config' },
+ { config: {}, name: 'empty config' },
+ { config: baseConfig, name: 'missing snapshots' },
+ {
+ config: { ...baseConfig, connectorSnapshots: null } as unknown as EvalRunConfig,
+ name: 'explicit null snapshots',
+ },
+ {
+ config: { ...baseConfig, connectorSnapshots: { [caseId]: null } } as unknown as EvalRunConfig,
+ name: 'explicit null case contract',
+ },
+ {
+ config: {
+ ...baseConfig,
+ connectorSnapshots: {
+ [caseId]: { notion: { connectorId: 'legacy-connection', fingerprint: 'legacy' } },
+ },
+ },
+ name: 'legacy snapshot missing manifest and dataset ownership',
+ },
+ ])('preserves $name without inventing an execution contract', async ({ config }) => {
+ const run = await model.create({ config, datasetId });
+ const storedBefore = await readStored(run.id);
+ expect((await model.findForCase(run.id, caseId))?.config).toEqual(config);
+ const { connectorSnapshots: _snapshots, ...expectedSummary } = config ?? {};
+ expect((await model.findSummaryById(run.id))?.config).toEqual(
+ config === null ? null : expectedSummary,
+ );
+ expect(await readStored(run.id)).toEqual(storedBefore);
+ });
+
+ it('does not substitute another case when the requested snapshot is absent', async () => {
+ const run = await model.create({
+ config: { ...baseConfig, connectorSnapshots: { other: caseSnapshots() } },
+ datasetId,
+ });
+ const storedBefore = await readStored(run.id);
+ expect((await model.findForCase(run.id, caseId))?.config).toEqual({
+ ...baseConfig,
+ connectorSnapshots: {},
+ });
+ expect(await readStored(run.id)).toEqual(storedBefore);
+ });
+
+ it('retains personal owner and workspace boundaries for both new reads and list summaries', async () => {
+ const config = { ...baseConfig, connectorSnapshots: { [caseId]: caseSnapshots() } };
+ const personal = await model.create({ config, datasetId });
+ const workspaceModel = new AgentEvalRunModel(db, owner, workspaceId);
+ const team = await workspaceModel.create({ config, datasetId });
+ const otherUserModel = new AgentEvalRunModel(db, otherOwner);
+ const otherTeamModel = new AgentEvalRunModel(db, owner, otherWorkspaceId);
+
+ for (const [reader, hiddenId] of [
+ [otherUserModel, personal.id],
+ [model, team.id],
+ [workspaceModel, personal.id],
+ [otherTeamModel, team.id],
+ ] as const) {
+ expect(await reader.findForCase(hiddenId, caseId)).toBeUndefined();
+ expect(await reader.findSummaryById(hiddenId)).toBeUndefined();
+ }
+ expect(await model.findForCase('missing-run', caseId)).toBeUndefined();
+ expect(await model.findSummaryById('missing-run')).toBeUndefined();
+ expect(await otherUserModel.query()).toEqual([]);
+ expect(await otherTeamModel.query()).toEqual([]);
+ expect((await model.query()).map(({ id }) => id)).toEqual([personal.id]);
+ expect((await workspaceModel.query()).map(({ id }) => id)).toEqual([team.id]);
+ expect((await workspaceModel.findForCase(team.id, caseId))?.config).toEqual(config);
+ expect((await workspaceModel.findSummaryById(team.id))?.config).toEqual(baseConfig);
+ // Existing workspace semantics allow another member to read shared runs.
+ const member = new AgentEvalRunModel(db, otherOwner, workspaceId);
+ expect((await member.findForCase(team.id, caseId))?.config).toEqual(config);
+ expect((await member.findSummaryById(team.id))?.config).toEqual(baseConfig);
+ });
+});
diff --git a/packages/database/src/models/agentEval/__tests__/run.test.ts b/packages/database/src/models/agentEval/__tests__/run.test.ts
index b9e1aa89230..96806caa858 100644
--- a/packages/database/src/models/agentEval/__tests__/run.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/run.test.ts
@@ -140,6 +140,40 @@ describe('AgentEvalRunModel', () => {
});
});
+ it('does not finalize over Stop, while allowing an explicit resume', async () => {
+ const run = await runModel.create({ datasetId, status: 'running' });
+ await runModel.update(run.id, { status: 'aborted' });
+ expect(await runModel.finalize(run.id, { status: 'completed' })).toBeUndefined();
+ expect((await runModel.findById(run.id))?.status).toBe('aborted');
+ await runModel.update(run.id, { status: 'running' });
+ expect(await runModel.finalize(run.id, { status: 'completed' })).toMatchObject({
+ status: 'completed',
+ });
+ });
+
+ it('keeps live progress from overwriting the metrics of a finalized run', async () => {
+ const run = await runModel.create({ datasetId, status: 'running' });
+ await runModel.updateProgress(run.id, {
+ failedCases: 1,
+ passedCases: 0,
+ totalCases: 2,
+ } as never);
+ expect((await runModel.findById(run.id))?.metrics).toMatchObject({ failedCases: 1 });
+ await runModel.finalize(run.id, {
+ metrics: { failedCases: 1, passedCases: 1, totalCases: 2 } as never,
+ status: 'completed',
+ });
+ // A progress write computed before finalization arrives late.
+ expect(
+ await runModel.updateProgress(run.id, {
+ failedCases: 1,
+ passedCases: 0,
+ totalCases: 2,
+ } as never),
+ ).toBeUndefined();
+ expect((await runModel.findById(run.id))?.metrics).toMatchObject({ passedCases: 1 });
+ });
+
describe('query', () => {
beforeEach(async () => {
// Create another dataset
diff --git a/packages/database/src/models/agentEval/__tests__/runEvidence.test.ts b/packages/database/src/models/agentEval/__tests__/runEvidence.test.ts
new file mode 100644
index 00000000000..e85d9389cf5
--- /dev/null
+++ b/packages/database/src/models/agentEval/__tests__/runEvidence.test.ts
@@ -0,0 +1,183 @@
+import type { EvalThreadResult } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ agentEvalBenchmarks,
+ agentEvalDatasets,
+ agentEvalRuns,
+ agentEvalRunTopics,
+ agentEvalTestCases,
+ topics,
+ users,
+} from '../../../schemas';
+import { AgentEvalExperimentModel } from '../experiment';
+import { AgentEvalRunModel } from '../run';
+import { AgentEvalRunTopicModel } from '../runTopic';
+
+const db = await getTestDB();
+const userId = 'run-evidence-test-user';
+const runModel = new AgentEvalRunModel(db, userId);
+const experiments = new AgentEvalExperimentModel(db, userId);
+const passed = (id: string): EvalThreadResult => ({ passed: true, status: 'passed', threadId: id });
+
+beforeEach(async () => {
+ await db.delete(users).where(eq(users.id, userId));
+ await db.insert(users).values({ id: userId });
+});
+afterEach(async () => {
+ await db.delete(users).where(eq(users.id, userId));
+});
+
+const setup = async (attempts?: EvalThreadResult[], skipTopic = false) => {
+ const [benchmark] = await db
+ .insert(agentEvalBenchmarks)
+ .values({
+ identifier: 'evidence',
+ isSystem: false,
+ name: 'Evidence',
+ rubrics: [],
+ userId,
+ })
+ .returning();
+ const [dataset] = await db
+ .insert(agentEvalDatasets)
+ .values({
+ benchmarkId: benchmark.id,
+ identifier: 'evidence',
+ name: 'Evidence',
+ userId,
+ })
+ .returning();
+ const experiment = await experiments.create({ benchmarkIds: [benchmark.id], name: 'Evidence' });
+ // This is the historical bug: summary metrics claim a complete, error-free
+ // run even when its saved attempts contain an infrastructure failure.
+ const metrics = {
+ averageScore: 1,
+ completedCases: 1,
+ errorCases: 0,
+ failedCases: 0,
+ passAllK: 1,
+ passRate: 1,
+ passedCases: 1,
+ totalCases: 1,
+ };
+ const run = await runModel.create({
+ config: { k: 3 },
+ datasetId: dataset.id,
+ experimentId: experiment.id,
+ metrics,
+ status: 'completed',
+ });
+ if (!skipTopic) {
+ const [testCase] = await db
+ .insert(agentEvalTestCases)
+ .values({ content: { input: 'Q' }, datasetId: dataset.id, userId })
+ .returning();
+ const [topic] = await db.insert(topics).values({ title: 'Evidence', userId }).returning();
+ await new AgentEvalRunTopicModel(db, userId).batchCreate([
+ {
+ evalResult: { passAtK: true, passAllK: false, threads: attempts },
+ passed: true,
+ runId: run.id,
+ score: 1,
+ status: 'passed',
+ testCaseId: testCase.id,
+ topicId: topic.id,
+ },
+ ]);
+ }
+ return { experiment, metrics, run };
+};
+
+describe('read-time evidence eligibility', () => {
+ it.each([
+ { name: 'single attempt without a verdict', passed: null, evalResult: {} },
+ {
+ name: 'legacy Judge failure on a passed row',
+ passed: true,
+ evalResult: { errorPhase: 'judge' as const },
+ },
+ ])('$name stays unverified', async ({ passed, evalResult }) => {
+ const { run } = await setup();
+ await runModel.update(run.id, { config: { k: 1 } });
+ await db
+ .update(agentEvalRunTopics)
+ .set({ evalResult, passed })
+ .where(eq(agentEvalRunTopics.runId, run.id));
+ expect((await runModel.findById(run.id))?.hasUnverifiedAttempts).toBe(true);
+ });
+
+ const scenarios: Array<{
+ attempts?: EvalThreadResult[];
+ expected: boolean;
+ name: string;
+ skipTopic?: boolean;
+ }> = [
+ {
+ name: 'legacy mixed execution error',
+ expected: true,
+ attempts: [passed('1'), passed('2'), { passed: false, status: 'error', threadId: '3' }],
+ },
+ {
+ name: 'legacy no-output model-failure label',
+ expected: true,
+ attempts: [
+ passed('1'),
+ passed('2'),
+ { error: 'No assistant output', passed: false, status: 'failed', threadId: '3' },
+ ],
+ },
+ ...[null, 'true', 1].map((value) => ({
+ name: `non-boolean verdict ${String(value)}`,
+ expected: true,
+ attempts: [
+ passed('1'),
+ passed('2'),
+ { status: 'passed', threadId: '3', passed: value } as unknown as EvalThreadResult,
+ ],
+ })),
+ { name: 'missing attempt', expected: true, attempts: [passed('1'), passed('2')] },
+ { name: 'missing run topic', expected: true, skipTopic: true },
+ {
+ name: 'missing boolean verdict',
+ expected: true,
+ attempts: [passed('1'), passed('2'), { status: 'passed', threadId: '3' }],
+ },
+ {
+ name: 'complete valid sample including a model failure',
+ expected: false,
+ attempts: [
+ passed('1'),
+ passed('2'),
+ {
+ error: 'Reached the step limit (20) without a final answer',
+ passed: false,
+ status: 'failed',
+ threadId: '3',
+ },
+ ],
+ },
+ ];
+
+ it.each(scenarios)(
+ '$name is consistently exposed without rewriting history',
+ async ({ attempts, expected, skipTopic }) => {
+ const { experiment, metrics, run } = await setup(attempts, skipTopic);
+ const single = await runModel.findById(run.id);
+ const listed = (await runModel.query()).find((item) => item.id === run.id);
+ const detail = await experiments.findById(experiment.id);
+ const recent = (await experiments.query())
+ .find((item) => item.id === experiment.id)
+ ?.recentRuns?.find((item) => item.id === run.id);
+ for (const result of [single, listed, detail?.runs?.[0], recent]) {
+ expect(result).toBeDefined();
+ expect(result?.hasUnverifiedAttempts).toBe(expected);
+ }
+ const [stored] = await db.select().from(agentEvalRuns).where(eq(agentEvalRuns.id, run.id));
+ expect(stored.metrics).toEqual(metrics);
+ expect(stored).not.toHaveProperty('hasUnverifiedAttempts');
+ },
+ );
+});
diff --git a/packages/database/src/models/agentEval/__tests__/runTopic.test.ts b/packages/database/src/models/agentEval/__tests__/runTopic.test.ts
index 8b32bb6c8a9..1f635e00d87 100644
--- a/packages/database/src/models/agentEval/__tests__/runTopic.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/runTopic.test.ts
@@ -2,12 +2,14 @@ import { eq, sql } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
+import { AgentEvalExecutionRepo } from '../../../repositories/agentEvalExecution';
import {
agentEvalBenchmarks,
agentEvalDatasets,
agentEvalRuns,
agentEvalRunTopics,
agentEvalTestCases,
+ threads,
topics,
users,
} from '../../../schemas';
@@ -128,6 +130,35 @@ afterEach(async () => {
});
describe('AgentEvalRunTopicModel', () => {
+ it.each([undefined, null, '', 'done', 'aborted'])(
+ 'guards completion reason %s without conflating missing and stopped',
+ async (completionReason) => {
+ await runTopicModel.batchCreate([
+ {
+ runId,
+ topicId: topicId1,
+ testCaseId: testCaseId1,
+ status: 'running',
+ evalResult: {
+ executionId: 'current',
+ ...(completionReason !== undefined && { completionReason }),
+ } as any,
+ },
+ ]);
+ const updated = await runTopicModel.updateByRunAndTopic(runId, topicId1, { score: 1 });
+ const merged = await runTopicModel.mergeExecutionResult(runId, topicId1, 'current', {
+ operationId: 'operation',
+ });
+ if (completionReason === 'aborted') {
+ expect(updated).toBeUndefined();
+ expect(merged).toBeUndefined();
+ } else {
+ expect(updated?.score).toBe(1);
+ expect(merged?.evalResult?.operationId).toBe('operation');
+ }
+ },
+ );
+
describe('batchCreate', () => {
it('should create multiple run topics', async () => {
const params = [
@@ -525,7 +556,10 @@ describe('AgentEvalRunTopicModel', () => {
.where(eq(agentEvalRunTopics.topicId, topicId2));
// Timeout = 20 min (1_200_000 ms)
- const rows = await runTopicModel.batchMarkTimeout(runId, 1_200_000);
+ const rows = await new AgentEvalExecutionRepo(serverDB, userId).batchMarkTimeout(
+ runId,
+ 1_200_000,
+ );
expect(rows).toHaveLength(2); // topic1 (30min) and topic2 (25min) > 20min
@@ -551,7 +585,10 @@ describe('AgentEvalRunTopicModel', () => {
.set({ createdAt: sql`NOW() - interval '30 minutes'` })
.where(eq(agentEvalRunTopics.runId, runId));
- const rows = await runTopicModel.batchMarkTimeout(runId, 1_200_000);
+ const rows = await new AgentEvalExecutionRepo(serverDB, userId).batchMarkTimeout(
+ runId,
+ 1_200_000,
+ );
expect(rows).toHaveLength(1); // only topic2 (running), not topic1 (passed)
@@ -581,7 +618,10 @@ describe('AgentEvalRunTopicModel', () => {
.set({ createdAt: sql`NOW() - interval '30 minutes'` })
.where(eq(agentEvalRunTopics.runId, runId));
- const rows = await runTopicModel.batchMarkTimeout(runId, 1_200_000);
+ const rows = await new AgentEvalExecutionRepo(serverDB, userId).batchMarkTimeout(
+ runId,
+ 1_200_000,
+ );
// Only the running topic should be marked
expect(rows).toHaveLength(1);
@@ -602,7 +642,10 @@ describe('AgentEvalRunTopicModel', () => {
{ userId, runId, topicId: topicId2, testCaseId: testCaseId2, status: 'running' },
]);
- const rows = await runTopicModel.batchMarkTimeout(runId, 1_200_000);
+ const rows = await new AgentEvalExecutionRepo(serverDB, userId).batchMarkTimeout(
+ runId,
+ 1_200_000,
+ );
expect(rows).toHaveLength(0);
});
@@ -633,7 +676,10 @@ describe('AgentEvalRunTopicModel', () => {
.update(agentEvalRunTopics)
.set({ createdAt: sql`NOW() - interval '30 minutes'` });
- const rows = await runTopicModel.batchMarkTimeout(runId, 1_200_000);
+ const rows = await new AgentEvalExecutionRepo(serverDB, userId).batchMarkTimeout(
+ runId,
+ 1_200_000,
+ );
expect(rows).toHaveLength(1);
@@ -658,7 +704,7 @@ describe('AgentEvalRunTopicModel', () => {
{ userId, runId, topicId: topic3.id, testCaseId: testCaseId1, status: 'passed' },
]);
- const rows = await runTopicModel.batchMarkAborted(runId);
+ const rows = await new AgentEvalExecutionRepo(serverDB, userId).batchMarkAborted(runId);
expect(rows).toHaveLength(2); // pending + running, not passed
@@ -674,13 +720,59 @@ describe('AgentEvalRunTopicModel', () => {
expect(aborted?.evalResult).toMatchObject({ error: 'Aborted' });
});
+ it('preserves evidence and blocks stale writes until explicit resume', async () => {
+ const evidence = {
+ cost: 1,
+ error: 'original provider error',
+ operationId: 'root',
+ threads: [{ passed: true, status: 'passed' as const, threadId: 'one' }],
+ };
+ await runTopicModel.batchCreate([
+ {
+ runId,
+ topicId: topicId1,
+ testCaseId: testCaseId1,
+ status: 'running',
+ evalResult: evidence,
+ },
+ ]);
+ await new AgentEvalExecutionRepo(serverDB, userId).batchMarkAborted(runId);
+ expect(
+ await runTopicModel.updateByRunAndTopic(runId, topicId1, {
+ status: 'passed',
+ evalResult: { passAllK: true },
+ }),
+ ).toBeUndefined();
+ const stopped = await runTopicModel.findByRunAndTestCase(runId, testCaseId1);
+ expect(stopped?.evalResult).toEqual({
+ ...evidence,
+ completionReason: 'aborted',
+ executionId: expect.any(String),
+ });
+ expect(stopped).toMatchObject({ passed: null, score: null, status: 'error' });
+ expect(
+ await runTopicModel.updateByRunAndTopic(
+ runId,
+ topicId1,
+ { status: 'running', evalResult: null },
+ { allowAborted: true },
+ ),
+ ).toMatchObject({ status: 'running' });
+ expect(
+ await runTopicModel.updateByRunAndTopic(runId, topicId1, {
+ status: 'passed',
+ passed: true,
+ }),
+ ).toMatchObject({ status: 'passed' });
+ });
+
it('should return empty array when no pending/running topics exist', async () => {
await serverDB.insert(agentEvalRunTopics).values([
{ userId, runId, topicId: topicId1, testCaseId: testCaseId1, status: 'passed' },
{ userId, runId, topicId: topicId2, testCaseId: testCaseId2, status: 'failed' },
]);
- const rows = await runTopicModel.batchMarkAborted(runId);
+ const rows = await new AgentEvalExecutionRepo(serverDB, userId).batchMarkAborted(runId);
expect(rows).toHaveLength(0);
});
@@ -706,7 +798,7 @@ describe('AgentEvalRunTopicModel', () => {
},
]);
- const rows = await runTopicModel.batchMarkAborted(runId);
+ const rows = await new AgentEvalExecutionRepo(serverDB, userId).batchMarkAborted(runId);
expect(rows).toHaveLength(1);
@@ -717,6 +809,39 @@ describe('AgentEvalRunTopicModel', () => {
});
});
+ describe('updateThreadMetadata', () => {
+ it('merges attempt metadata and removes the keys it sets to undefined', async () => {
+ await runTopicModel.batchCreate([
+ { runId, topicId: topicId1, testCaseId: testCaseId1, status: 'running' },
+ ]);
+ const [thread] = await serverDB
+ .insert(threads)
+ .values({
+ metadata: { cost: 0.02, judgeError: 'rate limited', status: 'judge_error' } as any,
+ topicId: topicId1,
+ type: 'eval',
+ userId,
+ })
+ .returning();
+
+ expect(
+ await new AgentEvalExecutionRepo(serverDB, userId).updateThreadMetadata(
+ runId,
+ topicId1,
+ thread.id,
+ {
+ judgeError: undefined,
+ passed: true,
+ status: 'passed',
+ },
+ ),
+ ).toEqual({ id: thread.id });
+
+ const [saved] = await serverDB.select().from(threads).where(eq(threads.id, thread.id));
+ expect(saved.metadata).toEqual({ cost: 0.02, passed: true, status: 'passed' });
+ });
+ });
+
describe('deleteByRunAndTestCase', () => {
beforeEach(async () => {
await serverDB.insert(agentEvalRunTopics).values([
diff --git a/packages/database/src/models/agentEval/__tests__/testCase.test.ts b/packages/database/src/models/agentEval/__tests__/testCase.test.ts
index 93642909d4c..5249685c0d8 100644
--- a/packages/database/src/models/agentEval/__tests__/testCase.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/testCase.test.ts
@@ -590,3 +590,66 @@ describe('AgentEvalTestCaseModel', () => {
});
});
});
+
+describe('AgentEvalTestCaseModel system rows', () => {
+ const otherUserId = 'testcase-test-other-user';
+
+ beforeEach(async () => {
+ await serverDB.insert(users).values({ id: otherUserId });
+ });
+
+ it('reads system cases (userId null) next to its own, never another user’s', async () => {
+ await serverDB.insert(agentEvalTestCases).values([
+ {
+ content: { input: 'system' },
+ datasetId,
+ metadata: { caseId: 'sys-1' },
+ sortOrder: 0,
+ userId: null,
+ },
+ {
+ content: { input: 'mine' },
+ datasetId,
+ metadata: { caseId: 'own-1' },
+ sortOrder: 1,
+ userId,
+ },
+ {
+ content: { input: 'theirs' },
+ datasetId,
+ metadata: { caseId: 'other-1' },
+ sortOrder: 2,
+ userId: otherUserId,
+ },
+ ]);
+
+ const visible = await testCaseModel.findByDatasetId(datasetId);
+ expect(visible.map((c) => c.metadata?.caseId)).toEqual(['sys-1', 'own-1']);
+ expect(await testCaseModel.countByDatasetId(datasetId)).toBe(2);
+ expect(await testCaseModel.findByDatasetIdAndCaseId(datasetId, 'sys-1')).toBeDefined();
+ expect(await testCaseModel.findByDatasetIdAndCaseId(datasetId, 'other-1')).toBeUndefined();
+ });
+
+ it('never updates or deletes a system case', async () => {
+ const [system] = await serverDB
+ .insert(agentEvalTestCases)
+ .values({
+ content: { input: 'system' },
+ datasetId,
+ metadata: { caseId: 'sys-1' },
+ userId: null,
+ })
+ .returning();
+
+ expect(
+ await testCaseModel.update(system.id, { metadata: { caseId: 'changed' } }),
+ ).toBeUndefined();
+ await testCaseModel.delete(system.id);
+
+ const [still] = await serverDB
+ .select()
+ .from(agentEvalTestCases)
+ .where(eq(agentEvalTestCases.id, system.id));
+ expect(still.metadata).toEqual({ caseId: 'sys-1' });
+ });
+});
diff --git a/packages/database/src/models/agentEval/benchmark.ts b/packages/database/src/models/agentEval/benchmark.ts
index 674aa23c854..95e7577136b 100644
--- a/packages/database/src/models/agentEval/benchmark.ts
+++ b/packages/database/src/models/agentEval/benchmark.ts
@@ -1,4 +1,4 @@
-import { and, count, desc, eq, getTableColumns, isNull, or, sql } from 'drizzle-orm';
+import { and, count, desc, eq, exists, getTableColumns, isNull, or, sql } from 'drizzle-orm';
import {
agentEvalBenchmarks,
@@ -9,6 +9,8 @@ import {
} from '../../schemas';
import { type LobeChatDatabase } from '../../type';
import { buildWorkspaceWhere } from '../../utils/workspace';
+import { evalRunSummaryConfig } from './run';
+import { activeEvalTestCases } from './testCase';
export class AgentEvalBenchmarkModel {
private userId: string;
@@ -67,6 +69,36 @@ export class AgentEvalBenchmarkModel {
);
};
+ /**
+ * Frees the datasets a benchmark is made of, before the benchmark is deleted:
+ * they stay, in no benchmark, instead of being deleted with it. Only for a
+ * benchmark this account may delete; returns how many were freed.
+ */
+ releaseDatasets = async (id: string) => {
+ const freed = await this.db
+ .update(agentEvalDatasets)
+ .set({ benchmarkId: null, updatedAt: new Date() })
+ .where(
+ and(
+ eq(agentEvalDatasets.benchmarkId, id),
+ exists(
+ this.db
+ .select({ id: agentEvalBenchmarks.id })
+ .from(agentEvalBenchmarks)
+ .where(
+ and(
+ eq(agentEvalBenchmarks.id, id),
+ eq(agentEvalBenchmarks.isSystem, false),
+ this.mutableOwnership(),
+ ),
+ ),
+ ),
+ ),
+ )
+ .returning({ id: agentEvalDatasets.id });
+ return freed.length;
+ };
+
/**
* Query benchmarks (system + user/workspace-created)
* @param includeSystem - Whether to include system benchmarks (default: true)
@@ -100,9 +132,12 @@ export class AgentEvalBenchmarkModel {
.from(agentEvalTestCases)
.innerJoin(agentEvalDatasets, eq(agentEvalTestCases.datasetId, agentEvalDatasets.id))
.where(
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- agentEvalDatasets,
+ and(
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentEvalDatasets,
+ ),
+ activeEvalTestCases(),
),
)
.groupBy(agentEvalDatasets.benchmarkId)
@@ -139,7 +174,10 @@ export class AgentEvalBenchmarkModel {
const benchmarksWithRuns = await Promise.all(
rows.map(async (row) => {
const recentRuns = await this.db
- .select()
+ .select({
+ ...getTableColumns(agentEvalRuns),
+ config: evalRunSummaryConfig,
+ })
.from(agentEvalRuns)
.innerJoin(agentEvalDatasets, eq(agentEvalRuns.datasetId, agentEvalDatasets.id))
.where(
@@ -169,7 +207,7 @@ export class AgentEvalBenchmarkModel {
datasetCount: Number(row.datasetCount),
runCount: Number(row.runCount),
testCaseCount: Number(row.testCaseCount),
- recentRuns: recentRuns.map((r) => r.agent_eval_runs),
+ recentRuns,
};
}),
);
diff --git a/packages/database/src/models/agentEval/dataset.ts b/packages/database/src/models/agentEval/dataset.ts
index 8a2ac55bd07..1358f36ba58 100644
--- a/packages/database/src/models/agentEval/dataset.ts
+++ b/packages/database/src/models/agentEval/dataset.ts
@@ -1,8 +1,16 @@
-import { and, asc, count, desc, eq, inArray, isNull, or } from 'drizzle-orm';
+import type { AgentEvalTestCaseInsert } from '@lobechat/types';
+import { and, asc, count, desc, eq, inArray, isNotNull, isNull, or } from 'drizzle-orm';
+import isEqual from 'fast-deep-equal';
import { agentEvalDatasets, agentEvalTestCases, type NewAgentEvalDataset } from '../../schemas';
import { type LobeChatDatabase } from '../../type';
-import { buildWorkspaceWhere } from '../../utils/workspace';
+import { buildWorkspaceWhere, normalizeWorkspaceId } from '../../utils/workspace';
+import {
+ AgentEvalDatasetWriteError,
+ assertReadableEvalEnvironments,
+ isFixedLobeBenchDataset,
+} from './datasetAccess';
+import { activeEvalTestCases } from './testCase';
interface QueryDatasetsFilters {
benchmarkId?: string;
@@ -10,6 +18,12 @@ interface QueryDatasetsFilters {
sourceExperimentId?: string;
}
+const fixedDatasetMetadata = (metadata?: Record<string, unknown> | null) => ({
+ ...metadata,
+ custom: true,
+ kind: 'lobe-bench',
+});
+
export class AgentEvalDatasetModel {
private userId: string;
private db: LobeChatDatabase;
@@ -18,7 +32,7 @@ export class AgentEvalDatasetModel {
constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
this.db = db;
this.userId = userId;
- this.workspaceId = workspaceId;
+ this.workspaceId = normalizeWorkspaceId(workspaceId) ?? undefined;
}
/** Includes system datasets (`userId IS NULL`) on read. */
@@ -33,27 +47,50 @@ export class AgentEvalDatasetModel {
/** Mutate-only predicate excluding system rows. */
private mutableOwnership = () =>
- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentEvalDatasets);
+ and(
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentEvalDatasets,
+ ),
+ isNotNull(agentEvalDatasets.userId),
+ );
/**
* Create a new dataset
*/
- create = async (params: NewAgentEvalDataset) => {
- const [result] = await this.db
- .insert(agentEvalDatasets)
- .values({ ...params, userId: this.userId, workspaceId: this.workspaceId ?? null })
- .returning();
- return result;
- };
-
- /**
- * Delete a dataset by id
- */
- delete = async (id: string) => {
- return this.db
- .delete(agentEvalDatasets)
- .where(and(eq(agentEvalDatasets.id, id), this.mutableOwnership()));
- };
+ create = async (
+ params: NewAgentEvalDataset,
+ cases?: Omit<AgentEvalTestCaseInsert, 'datasetId' | 'userId' | 'workspaceId'>[],
+ ) =>
+ this.db.transaction(async (tx) => {
+ const fixed = await isFixedLobeBenchDataset(tx, params);
+ const [result] = await tx
+ .insert(agentEvalDatasets)
+ .values({
+ ...params,
+ ...(fixed && { metadata: fixedDatasetMetadata(params.metadata) }),
+ userId: this.userId,
+ workspaceId: this.workspaceId ?? null,
+ })
+ .returning();
+ if (cases?.length) {
+ await assertReadableEvalEnvironments(
+ tx,
+ { userId: this.userId, workspaceId: this.workspaceId },
+ cases.map((testCase) => ({ ...testCase, datasetId: result.id })),
+ );
+ await tx.insert(agentEvalTestCases).values(
+ cases.map((testCase, index) => ({
+ ...testCase,
+ datasetId: result.id,
+ sortOrder: testCase.sortOrder ?? index + 1,
+ userId: this.userId,
+ workspaceId: this.workspaceId ?? null,
+ })),
+ );
+ }
+ return result;
+ });
/**
* Query datasets (system + user/workspace-owned) with test case counts
@@ -94,7 +131,10 @@ export class AgentEvalDatasetModel {
userId: agentEvalDatasets.userId,
})
.from(agentEvalDatasets)
- .leftJoin(agentEvalTestCases, eq(agentEvalDatasets.id, agentEvalTestCases.datasetId))
+ .leftJoin(
+ agentEvalTestCases,
+ and(eq(agentEvalDatasets.id, agentEvalTestCases.datasetId), activeEvalTestCases()),
+ )
.where(and(...conditions))
.groupBy(agentEvalDatasets.id)
.orderBy(desc(agentEvalDatasets.createdAt));
@@ -161,7 +201,7 @@ export class AgentEvalDatasetModel {
const testCases = await this.db
.select()
.from(agentEvalTestCases)
- .where(eq(agentEvalTestCases.datasetId, id))
+ .where(and(eq(agentEvalTestCases.datasetId, id), activeEvalTestCases()))
.orderBy(asc(agentEvalTestCases.sortOrder));
return { ...dataset, testCases };
@@ -171,11 +211,40 @@ export class AgentEvalDatasetModel {
* Update dataset
*/
update = async (id: string, value: Partial<NewAgentEvalDataset>) => {
- const [result] = await this.db
- .update(agentEvalDatasets)
- .set({ ...value, updatedAt: new Date() })
- .where(and(eq(agentEvalDatasets.id, id), this.mutableOwnership()))
- .returning();
- return result;
+ return this.db.transaction(async (tx) => {
+ const [dataset] = await tx
+ .select()
+ .from(agentEvalDatasets)
+ .where(and(eq(agentEvalDatasets.id, id), this.mutableOwnership()))
+ .for('update');
+ if (!dataset) return undefined;
+ const fixed = await isFixedLobeBenchDataset(tx, dataset);
+ if (fixed) {
+ for (const [key, next] of Object.entries(value)) {
+ if (next === undefined || ['benchmarkId', 'description', 'name'].includes(key)) continue;
+ const previous = dataset[key as keyof typeof dataset];
+ const unchanged =
+ key === 'metadata' ? isEqual(next ?? {}, previous ?? {}) : isEqual(next, previous);
+ if (!unchanged) {
+ throw new AgentEvalDatasetWriteError(
+ 'Lobe Bench dataset configuration is fixed; create a new dataset instead',
+ );
+ }
+ }
+ }
+ // Persist the classification on entry, and retain it when moved out, so
+ // changing benchmark or omitting client metadata cannot unfreeze cases.
+ const staysFixed = fixed || (await isFixedLobeBenchDataset(tx, { ...dataset, ...value }));
+ const [result] = await tx
+ .update(agentEvalDatasets)
+ .set({
+ ...value,
+ ...(staysFixed && { metadata: fixedDatasetMetadata(value.metadata ?? dataset.metadata) }),
+ updatedAt: new Date(),
+ })
+ .where(and(eq(agentEvalDatasets.id, id), this.mutableOwnership()))
+ .returning();
+ return result;
+ });
};
}
diff --git a/packages/database/src/models/agentEval/datasetAccess.ts b/packages/database/src/models/agentEval/datasetAccess.ts
new file mode 100644
index 00000000000..3e2273ed6e7
--- /dev/null
+++ b/packages/database/src/models/agentEval/datasetAccess.ts
@@ -0,0 +1,148 @@
+import type { EvalCaseEnvironment } from '@lobechat/types';
+import { and, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';
+
+import {
+ agentEvalBenchmarks,
+ agentEvalDatasets,
+ agentEvalEnvironments,
+ agentEvalTestCases,
+ userConnectors,
+} from '../../schemas';
+import type { Transaction } from '../../type';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+
+export class AgentEvalDatasetWriteError extends Error {
+ constructor(message = 'Dataset not found or not writable') {
+ super(message);
+ this.name = 'AgentEvalDatasetWriteError';
+ }
+}
+
+/** Classify by domain, independently of the dataset's write authorization. */
+export const isFixedLobeBenchDataset = async (
+ tx: Transaction,
+ dataset: { benchmarkId?: string | null; metadata?: Record<string, unknown> | null },
+) => {
+ if (dataset.metadata?.kind === 'lobe-bench') return true;
+ if (!dataset.benchmarkId) return false;
+ const [benchmark] = await tx
+ .select({ metadata: agentEvalBenchmarks.metadata })
+ .from(agentEvalBenchmarks)
+ .where(eq(agentEvalBenchmarks.id, dataset.benchmarkId))
+ .limit(1);
+ return benchmark?.metadata?.kind === 'lobe-bench';
+};
+
+export const assertReadableEvalEnvironments = async (
+ tx: Transaction,
+ scope: { userId: string; workspaceId?: string },
+ cases: Array<{
+ content: { environment?: EvalCaseEnvironment };
+ datasetId: string;
+ environmentId?: string | null;
+ }>,
+) => {
+ const ids = [
+ ...new Set(cases.map(({ environmentId }) => environmentId).filter((id): id is string => !!id)),
+ ];
+ const environments = ids.length
+ ? await tx
+ .select({ config: agentEvalEnvironments.config, id: agentEvalEnvironments.id })
+ .from(agentEvalEnvironments)
+ .where(
+ and(
+ inArray(agentEvalEnvironments.id, ids),
+ or(
+ buildWorkspaceWhere(scope, agentEvalEnvironments),
+ isNull(agentEvalEnvironments.userId),
+ ),
+ ),
+ )
+ .orderBy(agentEvalEnvironments.id)
+ .for('share')
+ : [];
+ if (environments.length !== ids.length) {
+ throw new AgentEvalDatasetWriteError('Environment not found or not readable');
+ }
+ const shared = new Map(environments.map(({ config, id }) => [id, config]));
+ const connections = new Map<string, Set<string>>();
+ for (const testCase of cases) {
+ const configs = [
+ testCase.environmentId ? shared.get(testCase.environmentId) : undefined,
+ testCase.content.environment,
+ ];
+ for (const config of configs) {
+ const bindings = Object.values(config?.connectorBindings ?? {});
+ if (!bindings.length) continue;
+ const ids = connections.get(testCase.datasetId) ?? new Set<string>();
+ for (const { connectorId } of bindings) ids.add(connectorId);
+ connections.set(testCase.datasetId, ids);
+ }
+ }
+ // Validate every reference, including a shared binding shadowed by a case override.
+ // Unbound environments remain reusable; connection identity belongs to one Dataset.
+ for (const [datasetId, ids] of connections) {
+ const rows = await tx
+ .select({ id: userConnectors.id })
+ .from(userConnectors)
+ .where(
+ and(
+ inArray(userConnectors.id, [...ids]),
+ buildWorkspaceWhere(scope, userConnectors),
+ sql`${userConnectors.metadata} -> 'agentEval' ->> 'datasetId' = ${datasetId}`,
+ ),
+ );
+ if (rows.length !== ids.size) {
+ throw new AgentEvalDatasetWriteError(
+ 'Environment connection is unavailable or belongs to another Dataset',
+ );
+ }
+ }
+};
+
+/** Lock parents before checking them, so concurrent initial imports cannot both succeed. */
+export const assertWritableEvalDatasets = async (
+ tx: Transaction,
+ scope: { userId: string; workspaceId?: string },
+ datasetIds: string[],
+) => {
+ const ids = [...new Set(datasetIds)].sort();
+ const datasets = await tx
+ .select()
+ .from(agentEvalDatasets)
+ .where(
+ and(
+ inArray(agentEvalDatasets.id, ids),
+ buildWorkspaceWhere(scope, agentEvalDatasets),
+ isNotNull(agentEvalDatasets.userId),
+ ),
+ )
+ .orderBy(agentEvalDatasets.id)
+ .for('update');
+
+ if (datasets.length !== ids.length) throw new AgentEvalDatasetWriteError();
+ return datasets;
+};
+
+export const assertEvalDatasetCasesMutable = async (
+ tx: Transaction,
+ datasets: Array<{
+ benchmarkId?: string | null;
+ id: string;
+ metadata: Record<string, unknown> | null;
+ }>,
+) => {
+ for (const dataset of datasets) {
+ if (!(await isFixedLobeBenchDataset(tx, dataset))) continue;
+ const [existing] = await tx
+ .select({ id: agentEvalTestCases.id })
+ .from(agentEvalTestCases)
+ .where(eq(agentEvalTestCases.datasetId, dataset.id))
+ .limit(1);
+ if (existing) {
+ throw new AgentEvalDatasetWriteError(
+ 'Lobe Bench dataset cases are fixed after creation; create a new dataset instead',
+ );
+ }
+ }
+};
diff --git a/packages/database/src/models/agentEval/environment.ts b/packages/database/src/models/agentEval/environment.ts
new file mode 100644
index 00000000000..03646420bcd
--- /dev/null
+++ b/packages/database/src/models/agentEval/environment.ts
@@ -0,0 +1,178 @@
+import type {
+ AgentEvalEnvironmentInsert,
+ EvalCaseEnvironment,
+ EvalConnectorBindings,
+} from '@lobechat/types';
+import { and, count, desc, eq, inArray, isNull, or } from 'drizzle-orm';
+
+import { agentEvalEnvironments, agentEvalTestCases } from '../../schemas';
+import { type LobeChatDatabase } from '../../type';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+
+export class AgentEvalEnvironmentBindingError extends Error {
+ constructor() {
+ super(
+ 'Environment connections changed. Reload the environment and manage its connections in the Dataset.',
+ );
+ this.name = 'AgentEvalEnvironmentBindingError';
+ }
+}
+
+/** JSONB key order and an explicit default transport do not change a binding. */
+export const hasSameEvalConnectorBindings = (
+ left: EvalConnectorBindings = {},
+ right: EvalConnectorBindings = {},
+) => {
+ const identity = (bindings: EvalConnectorBindings) =>
+ Object.entries(bindings)
+ .map(([alias, binding]) => [alias, binding.connectorId, binding.transport ?? 'mcp'])
+ .sort();
+ return JSON.stringify(identity(left)) === JSON.stringify(identity(right));
+};
+
+/**
+ * Reusable case environments. Owned like test cases: by the user, or by the
+ * workspace when the model is scoped to one; system environments
+ * (`userId IS NULL`, those of the built-in case sets) are readable by everyone
+ * and changed by no one.
+ */
+export class AgentEvalEnvironmentModel {
+ private userId: string;
+ private db: LobeChatDatabase;
+ private workspaceId?: string;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ }
+
+ private ownership = () =>
+ or(
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentEvalEnvironments,
+ ),
+ isNull(agentEvalEnvironments.userId),
+ );
+
+ /** Mutate-only predicate excluding system rows. */
+ private mutableOwnership = () =>
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentEvalEnvironments,
+ );
+
+ create = async (params: Omit<AgentEvalEnvironmentInsert, 'userId' | 'workspaceId'>) => {
+ const [result] = await this.db
+ .insert(agentEvalEnvironments)
+ .values({ ...params, userId: this.userId, workspaceId: this.workspaceId ?? null })
+ .returning();
+ return result;
+ };
+
+ delete = async (id: string) => {
+ return this.db
+ .delete(agentEvalEnvironments)
+ .where(and(eq(agentEvalEnvironments.id, id), this.mutableOwnership()));
+ };
+
+ findById = async (id: string) => {
+ const [result] = await this.db
+ .select()
+ .from(agentEvalEnvironments)
+ .where(and(eq(agentEvalEnvironments.id, id), this.ownership()))
+ .limit(1);
+ return result;
+ };
+
+ findByIdentifier = async (identifier: string) => {
+ const [result] = await this.db
+ .select()
+ .from(agentEvalEnvironments)
+ .where(and(eq(agentEvalEnvironments.identifier, identifier), this.ownership()))
+ .limit(1);
+ return result;
+ };
+
+ /** Several environments at once (for resolving a batch of cases); unknown ids are skipped. */
+ findByIds = async (ids: string[]) => {
+ const unique = [...new Set(ids)];
+ if (unique.length === 0) return [];
+ return this.db
+ .select()
+ .from(agentEvalEnvironments)
+ .where(and(inArray(agentEvalEnvironments.id, unique), this.ownership()));
+ };
+
+ /** Every environment of the owner, newest first, with the number of cases pointing at it. */
+ query = async () => {
+ const rows = await this.db
+ .select({
+ config: agentEvalEnvironments.config,
+ createdAt: agentEvalEnvironments.createdAt,
+ description: agentEvalEnvironments.description,
+ id: agentEvalEnvironments.id,
+ identifier: agentEvalEnvironments.identifier,
+ metadata: agentEvalEnvironments.metadata,
+ name: agentEvalEnvironments.name,
+ testCaseCount: count(agentEvalTestCases.id).as('testCaseCount'),
+ updatedAt: agentEvalEnvironments.updatedAt,
+ userId: agentEvalEnvironments.userId,
+ workspaceId: agentEvalEnvironments.workspaceId,
+ })
+ .from(agentEvalEnvironments)
+ .leftJoin(agentEvalTestCases, eq(agentEvalTestCases.environmentId, agentEvalEnvironments.id))
+ .where(this.ownership())
+ .groupBy(agentEvalEnvironments.id)
+ .orderBy(desc(agentEvalEnvironments.createdAt));
+ return rows.map((row) => ({ ...row, testCaseCount: Number(row.testCaseCount) }));
+ };
+
+ update = async (
+ id: string,
+ value: Partial<{
+ config: EvalCaseEnvironment;
+ description: string | null;
+ identifier: string | null;
+ metadata: Record<string, unknown> | null;
+ name: string;
+ }>,
+ ) => {
+ return this.db.transaction(async (tx) => {
+ const predicate = and(eq(agentEvalEnvironments.id, id), this.mutableOwnership());
+ const [current] = await tx
+ .select()
+ .from(agentEvalEnvironments)
+ .where(predicate)
+ .limit(1)
+ .for('update');
+ if (!current) return;
+
+ let config = value.config;
+ if (config) {
+ if (
+ config.connectorBindings !== undefined &&
+ !hasSameEvalConnectorBindings(config.connectorBindings, current.config.connectorBindings)
+ )
+ throw new AgentEvalEnvironmentBindingError();
+ // Dataset connection repair takes the same row lock. Merge only after
+ // acquiring it, so an older persona form cannot overwrite repaired bindings.
+ // Stored connections (with their encrypted credentials) are managed by the
+ // Dataset connection API alone; clients only ever see redacted copies.
+ const { connections: _clientCopy, ...rest } = config;
+ config = {
+ ...rest,
+ connectorBindings: current.config.connectorBindings,
+ ...(current.config.connections && { connections: current.config.connections }),
+ };
+ }
+ const [result] = await tx
+ .update(agentEvalEnvironments)
+ .set({ ...value, config, updatedAt: new Date() })
+ .where(predicate)
+ .returning();
+ return result;
+ });
+ };
+}
diff --git a/packages/database/src/models/agentEval/experiment.ts b/packages/database/src/models/agentEval/experiment.ts
index 18f33f8969b..54f45a18da6 100644
--- a/packages/database/src/models/agentEval/experiment.ts
+++ b/packages/database/src/models/agentEval/experiment.ts
@@ -18,7 +18,8 @@ import { type LobeChatDatabase } from '../../type';
import { isUniqueViolation } from '../../utils/uniqueViolation';
import { buildWorkspaceWhere } from '../../utils/workspace';
import { AgentEvalDatasetModel } from './dataset';
-import { AgentEvalRunModel } from './run';
+import { AgentEvalRunModel, evalRunSummaryConfig } from './run';
+import { hasUnverifiedEvalAttempts } from './runEvidence';
const RECENT_RUNS_PER_EXPERIMENT = 5;
@@ -318,6 +319,8 @@ export class AgentEvalExperimentModel {
const rankedRuns = this.db
.select({
...getTableColumns(agentEvalRuns),
+ config: evalRunSummaryConfig.as('config'),
+ hasUnverifiedAttempts: hasUnverifiedEvalAttempts().as('has_unverified_attempts'),
rn: sql<number>`row_number() over (partition by ${agentEvalRuns.experimentId} order by ${agentEvalRuns.createdAt} desc)`.as(
'rn',
),
diff --git a/packages/database/src/models/agentEval/index.ts b/packages/database/src/models/agentEval/index.ts
index 1b3fa080ec5..c37a5985f81 100644
--- a/packages/database/src/models/agentEval/index.ts
+++ b/packages/database/src/models/agentEval/index.ts
@@ -1,5 +1,6 @@
export * from './benchmark';
export * from './dataset';
+export * from './environment';
export * from './experiment';
export * from './run';
export * from './runTopic';
diff --git a/packages/database/src/models/agentEval/run.ts b/packages/database/src/models/agentEval/run.ts
index 27760e838b9..5f25af37fd9 100644
--- a/packages/database/src/models/agentEval/run.ts
+++ b/packages/database/src/models/agentEval/run.ts
@@ -1,8 +1,23 @@
-import { and, count, desc, eq, inArray } from 'drizzle-orm';
+import type { EvalRunConfig } from '@lobechat/types';
+import { and, count, desc, eq, getTableColumns, inArray, ne, notInArray, sql } from 'drizzle-orm';
-import { agentEvalDatasets, agentEvalRuns, type NewAgentEvalRun } from '../../schemas';
+import {
+ agentEvalDatasets,
+ agentEvalRuns,
+ agentEvalRunTopics,
+ type NewAgentEvalRun,
+} from '../../schemas';
import { type LobeChatDatabase } from '../../type';
import { buildWorkspaceWhere } from '../../utils/workspace';
+import { hasUnverifiedEvalAttempts } from './runEvidence';
+
+/** Lists and status checkpoints do not need any case's frozen tool contracts. */
+export const evalRunSummaryConfig = sql<EvalRunConfig | null>`
+ case when jsonb_typeof(${agentEvalRuns.config}) = 'object'
+ then ${agentEvalRuns.config} - 'connectorSnapshots'
+ else ${agentEvalRuns.config}
+ end
+`;
export class AgentEvalRunModel {
private userId: string;
@@ -30,7 +45,7 @@ export class AgentEvalRunModel {
};
/**
- * Query runs with optional filters
+ * Query run summaries with optional filters. Full frozen evidence remains in findById.
*/
query = async (filter?: {
benchmarkId?: string;
@@ -64,7 +79,11 @@ export class AgentEvalRunModel {
}
const query = this.db
- .select()
+ .select({
+ ...getTableColumns(agentEvalRuns),
+ config: evalRunSummaryConfig,
+ hasUnverifiedAttempts: hasUnverifiedEvalAttempts(),
+ })
.from(agentEvalRuns)
.where(and(...conditions))
.orderBy(desc(agentEvalRuns.createdAt), desc(agentEvalRuns.id))
@@ -110,7 +129,48 @@ export class AgentEvalRunModel {
*/
findById = async (id: string) => {
const [result] = await this.db
- .select()
+ .select({
+ ...getTableColumns(agentEvalRuns),
+ hasUnverifiedAttempts: hasUnverifiedEvalAttempts(),
+ })
+ .from(agentEvalRuns)
+ .where(and(eq(agentEvalRuns.id, id), this.ownership()))
+ .limit(1);
+ return result;
+ };
+
+ /** Read one case's frozen contracts in SQL, without transporting the entire dataset. */
+ findForCase = async (id: string, testCaseId: string) => {
+ const [result] = await this.db
+ .select({
+ ...getTableColumns(agentEvalRuns),
+ config: sql<EvalRunConfig | null>`
+ case when jsonb_typeof(${agentEvalRuns.config} -> 'connectorSnapshots') = 'object'
+ then jsonb_set(${agentEvalRuns.config}, '{connectorSnapshots}',
+ case when (${agentEvalRuns.config} -> 'connectorSnapshots') ? ${testCaseId}
+ then jsonb_build_object(${testCaseId}::text,
+ ${agentEvalRuns.config} -> 'connectorSnapshots' -> ${testCaseId}::text)
+ else '{}'::jsonb
+ end, false)
+ else ${agentEvalRuns.config}
+ end
+ `,
+ hasUnverifiedAttempts: hasUnverifiedEvalAttempts(),
+ })
+ .from(agentEvalRuns)
+ .where(and(eq(agentEvalRuns.id, id), this.ownership()))
+ .limit(1);
+ return result;
+ };
+
+ /** Read control/configuration fields without frozen connector contracts. */
+ findSummaryById = async (id: string) => {
+ const [result] = await this.db
+ .select({
+ ...getTableColumns(agentEvalRuns),
+ config: evalRunSummaryConfig,
+ hasUnverifiedAttempts: hasUnverifiedEvalAttempts(),
+ })
.from(agentEvalRuns)
.where(and(eq(agentEvalRuns.id, id), this.ownership()))
.limit(1);
@@ -120,11 +180,74 @@ export class AgentEvalRunModel {
/**
* Update run
*/
- update = async (id: string, value: Partial<NewAgentEvalRun>) => {
+ update = async (
+ id: string,
+ value: Partial<NewAgentEvalRun>,
+ options?: { startedAt: Date | string | null | undefined },
+ ) => {
const [result] = await this.db
.update(agentEvalRuns)
.set({ ...value, updatedAt: new Date() })
- .where(and(eq(agentEvalRuns.id, id), this.ownership()))
+ .where(
+ and(
+ eq(agentEvalRuns.id, id),
+ this.ownership(),
+ options
+ ? sql`${agentEvalRuns.startedAt} IS NOT DISTINCT FROM ${options.startedAt ? new Date(options.startedAt).toISOString() : null}::timestamptz`
+ : undefined,
+ ),
+ )
+ .returning();
+ return result;
+ };
+
+ /**
+ * Live progress counts written as cases end. A progress write computed before
+ * the run was finalized must not land after it: once the run is completed,
+ * failed or aborted, only finalization, rejudging or a rerun change its metrics.
+ */
+ updateProgress = async (
+ id: string,
+ metrics: NewAgentEvalRun['metrics'],
+ options?: { startedAt: Date | string | null | undefined },
+ ) => {
+ const [result] = await this.db
+ .update(agentEvalRuns)
+ .set({ metrics, updatedAt: new Date() })
+ .where(
+ and(
+ eq(agentEvalRuns.id, id),
+ notInArray(agentEvalRuns.status, ['aborted', 'completed', 'failed']),
+ this.ownership(),
+ options
+ ? sql`${agentEvalRuns.startedAt} IS NOT DISTINCT FROM ${options.startedAt ? new Date(options.startedAt).toISOString() : null}::timestamptz`
+ : undefined,
+ ),
+ )
+ .returning();
+ return result;
+ };
+
+ /** Finalization may race with Stop; only an explicit resume can reopen an aborted run. */
+ finalize = async (
+ id: string,
+ value: Pick<NewAgentEvalRun, 'metrics' | 'status'>,
+ options?: { startedAt: Date | string | null | undefined },
+ ) => {
+ const [result] = await this.db
+ .update(agentEvalRuns)
+ .set({ ...value, updatedAt: new Date() })
+ .where(
+ and(
+ eq(agentEvalRuns.id, id),
+ ne(agentEvalRuns.status, 'aborted'),
+ this.ownership(),
+ options
+ ? sql`${agentEvalRuns.startedAt} IS NOT DISTINCT FROM ${options.startedAt ? new Date(options.startedAt).toISOString() : null}::timestamptz`
+ : undefined,
+ sql`NOT EXISTS (SELECT 1 FROM ${agentEvalRunTopics} WHERE ${agentEvalRunTopics.runId} = ${agentEvalRuns.id} AND ${agentEvalRunTopics.status} IN ('pending', 'running'))`,
+ ),
+ )
.returning();
return result;
};
@@ -150,7 +273,11 @@ export class AgentEvalRunModel {
claim = async (id: string) => {
const [result] = await this.db
.update(agentEvalRuns)
- .set({ startedAt: new Date(), status: 'running', updatedAt: new Date() })
+ .set({
+ startedAt: sql`GREATEST(${new Date().toISOString()}::timestamptz, ${agentEvalRuns.startedAt} + interval '1 millisecond')`,
+ status: 'running',
+ updatedAt: new Date(),
+ })
.where(and(eq(agentEvalRuns.id, id), eq(agentEvalRuns.status, 'pending'), this.ownership()))
.returning();
return result;
diff --git a/packages/database/src/models/agentEval/runEvidence.ts b/packages/database/src/models/agentEval/runEvidence.ts
new file mode 100644
index 00000000000..e79b57b1bd7
--- /dev/null
+++ b/packages/database/src/models/agentEval/runEvidence.ts
@@ -0,0 +1,37 @@
+import { sql } from 'drizzle-orm';
+
+import { agentEvalRuns, agentEvalRunTopics } from '../../schemas';
+
+/** Read saved evidence as well as metrics: older summaries hid partially errored attempts. */
+export const hasUnverifiedEvalAttempts = () => sql<boolean>`
+ exists (
+ select 1 from ${agentEvalRunTopics} as evidence
+ where evidence.run_id = ${agentEvalRuns.id}
+ and (
+ coalesce(evidence.status, '') not in ('passed', 'failed')
+ or evidence.passed is null
+ or evidence.eval_result ->> 'errorPhase' = 'judge'
+ or evidence.eval_result ->> 'error' = 'No assistant output'
+ or exists (
+ select 1 from jsonb_array_elements(
+ case when jsonb_typeof(evidence.eval_result -> 'threads') = 'array'
+ then evidence.eval_result -> 'threads' else '[]'::jsonb end
+ ) as attempt
+ where attempt ->> 'status' in ('error', 'timeout', 'judge_error', 'external', 'running', 'pending')
+ or attempt ->> 'error' = 'No assistant output'
+ or attempt ->> 'errorPhase' = 'judge'
+ or coalesce(jsonb_typeof(attempt -> 'passed'), '') <> 'boolean'
+ )
+ or (
+ coalesce((${agentEvalRuns.config} ->> 'k')::integer, 1) > 1
+ and jsonb_array_length(
+ case when jsonb_typeof(evidence.eval_result -> 'threads') = 'array'
+ then evidence.eval_result -> 'threads' else '[]'::jsonb end
+ ) <> (${agentEvalRuns.config} ->> 'k')::integer
+ )
+ )
+ ) or (
+ coalesce((${agentEvalRuns.metrics} ->> 'totalCases')::integer, 0) >
+ (select count(*) from ${agentEvalRunTopics} as coverage where coverage.run_id = ${agentEvalRuns.id})
+ )
+`;
diff --git a/packages/database/src/models/agentEval/runTopic.ts b/packages/database/src/models/agentEval/runTopic.ts
index 1f4d63bf5a6..257f736107a 100644
--- a/packages/database/src/models/agentEval/runTopic.ts
+++ b/packages/database/src/models/agentEval/runTopic.ts
@@ -1,4 +1,4 @@
-import { and, asc, count, desc, eq, lt, or } from 'drizzle-orm';
+import { and, asc, count, desc, eq, or, sql } from 'drizzle-orm';
import {
agentEvalRuns,
@@ -150,41 +150,6 @@ export class AgentEvalRunTopicModel {
return row;
};
- /**
- * Batch mark timed-out RunTopics:
- * Per-row check: created_at + timeoutMs < NOW()
- * Returns the updated rows so callers can compute per-row duration.
- */
- batchMarkAborted = async (runId: string) => {
- return this.db
- .update(agentEvalRunTopics)
- .set({ status: 'error', evalResult: { error: 'Aborted' } })
- .where(
- and(
- this.ownership(),
- eq(agentEvalRunTopics.runId, runId),
- or(eq(agentEvalRunTopics.status, 'pending'), eq(agentEvalRunTopics.status, 'running')),
- ),
- )
- .returning();
- };
-
- batchMarkTimeout = async (runId: string, timeoutMs: number) => {
- const deadline = new Date(Date.now() - timeoutMs);
- return this.db
- .update(agentEvalRunTopics)
- .set({ status: 'timeout' })
- .where(
- and(
- this.ownership(),
- eq(agentEvalRunTopics.runId, runId),
- eq(agentEvalRunTopics.status, 'running'),
- lt(agentEvalRunTopics.createdAt, deadline),
- ),
- )
- .returning();
- };
-
deleteByRunAndTestCase = async (runId: string, testCaseId: string) => {
return this.db
.delete(agentEvalRunTopics)
@@ -224,6 +189,7 @@ export class AgentEvalRunTopicModel {
Partial<AgentEvalRunTopicItem>,
'createdAt' | 'evalResult' | 'passed' | 'score' | 'status'
>,
+ options?: { allowAborted?: boolean; executionId?: string; status?: string },
) => {
const [result] = await this.db
.update(agentEvalRunTopics)
@@ -233,6 +199,39 @@ export class AgentEvalRunTopicModel {
this.ownership(),
eq(agentEvalRunTopics.runId, runId),
eq(agentEvalRunTopics.topicId, topicId),
+ options && 'executionId' in options
+ ? sql`${agentEvalRunTopics.evalResult}->>'executionId' IS NOT DISTINCT FROM ${options.executionId ?? null}::text`
+ : undefined,
+ options?.status ? eq(agentEvalRunTopics.status, options.status as any) : undefined,
+ options?.allowAborted
+ ? undefined
+ : sql`COALESCE(${agentEvalRunTopics.evalResult}->>'completionReason', '') <> 'aborted'`,
+ ),
+ )
+ .returning();
+ return result;
+ };
+
+ /** Merge operation identity without replacing a completion that raced ahead of startup. */
+ mergeExecutionResult = async (
+ runId: string,
+ topicId: string,
+ executionId: string,
+ value: Record<string, unknown>,
+ ) => {
+ const [result] = await this.db
+ .update(agentEvalRunTopics)
+ .set({
+ evalResult: sql`COALESCE(${agentEvalRunTopics.evalResult}, '{}'::jsonb) || ${JSON.stringify(value)}::jsonb`,
+ })
+ .where(
+ and(
+ this.ownership(),
+ eq(agentEvalRunTopics.runId, runId),
+ eq(agentEvalRunTopics.topicId, topicId),
+ sql`${agentEvalRunTopics.evalResult}->>'executionId' = ${executionId}`,
+ sql`COALESCE(${agentEvalRunTopics.evalResult}->>'completionReason', '') <> 'aborted'`,
+ sql`${agentEvalRunTopics.status} IS DISTINCT FROM 'timeout'`,
),
)
.returning();
diff --git a/packages/database/src/models/agentEval/testCase.ts b/packages/database/src/models/agentEval/testCase.ts
index 52d56b8a0d5..f9fb2f29b7f 100644
--- a/packages/database/src/models/agentEval/testCase.ts
+++ b/packages/database/src/models/agentEval/testCase.ts
@@ -1,9 +1,21 @@
import type { EvalTestCaseContent } from '@lobechat/types';
-import { and, count, eq, sql } from 'drizzle-orm';
+import { and, count, eq, isNotNull, isNull, or, sql } from 'drizzle-orm';
import { agentEvalTestCases, type NewAgentEvalTestCase } from '../../schemas';
import { type LobeChatDatabase } from '../../type';
-import { buildWorkspaceWhere } from '../../utils/workspace';
+import { buildWorkspaceWhere, normalizeWorkspaceId } from '../../utils/workspace';
+import {
+ assertEvalDatasetCasesMutable,
+ assertReadableEvalEnvironments,
+ assertWritableEvalDatasets,
+} from './datasetAccess';
+
+export const isRetiredEvalTestCase = (testCase: { metadata?: Record<string, unknown> | null }) =>
+ testCase.metadata?.retired === true;
+
+/** Retired rows remain available by id for historical runs, but leave the runnable catalog. */
+export const activeEvalTestCases = () =>
+ sql`COALESCE(${agentEvalTestCases.metadata} -> 'retired', 'null'::jsonb) <> 'true'::jsonb`;
export class AgentEvalTestCaseModel {
private userId: string;
@@ -13,54 +25,101 @@ export class AgentEvalTestCaseModel {
constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
this.db = db;
this.userId = userId;
- this.workspaceId = workspaceId;
+ this.workspaceId = normalizeWorkspaceId(workspaceId) ?? undefined;
}
+ private scope = () => ({ userId: this.userId, workspaceId: this.workspaceId });
+
+ /**
+ * Rows the actor can read: own/workspace cases and system cases
+ * (`userId IS NULL`, the built-in case sets every user can run).
+ */
private ownership = () =>
- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentEvalTestCases);
+ or(
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentEvalTestCases,
+ ),
+ isNull(agentEvalTestCases.userId),
+ );
+
+ /** Rows the actor can change: own/workspace cases only, never system cases. */
+ private mutableOwnership = () =>
+ and(
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentEvalTestCases,
+ ),
+ isNotNull(agentEvalTestCases.userId),
+ );
/**
* Create a single test case
*/
create = async (params: Omit<NewAgentEvalTestCase, 'userId'>) => {
- let finalParams: NewAgentEvalTestCase = {
- ...params,
- userId: this.userId,
- workspaceId: this.workspaceId ?? null,
- };
-
- if (finalParams.sortOrder === undefined || finalParams.sortOrder === null) {
- const [maxResult] = await this.db
- .select({ max: sql<number>`COALESCE(MAX(${agentEvalTestCases.sortOrder}), 0)` })
- .from(agentEvalTestCases)
- .where(eq(agentEvalTestCases.datasetId, finalParams.datasetId));
-
- finalParams = { ...finalParams, sortOrder: maxResult.max + 1 };
- }
-
- const [result] = await this.db.insert(agentEvalTestCases).values(finalParams).returning();
- return result;
+ return this.db.transaction(async (tx) => {
+ const datasets = await assertWritableEvalDatasets(tx, this.scope(), [params.datasetId]);
+ await assertEvalDatasetCasesMutable(tx, datasets);
+ await assertReadableEvalEnvironments(tx, this.scope(), [params]);
+ let finalParams: NewAgentEvalTestCase = {
+ ...params,
+ userId: this.userId,
+ workspaceId: this.workspaceId ?? null,
+ };
+
+ if (finalParams.sortOrder === undefined || finalParams.sortOrder === null) {
+ const [maxResult] = await tx
+ .select({ max: sql<number>`COALESCE(MAX(${agentEvalTestCases.sortOrder}), 0)` })
+ .from(agentEvalTestCases)
+ .where(eq(agentEvalTestCases.datasetId, finalParams.datasetId));
+
+ finalParams = { ...finalParams, sortOrder: maxResult.max + 1 };
+ }
+
+ const [result] = await tx.insert(agentEvalTestCases).values(finalParams).returning();
+ return result;
+ });
};
/**
* Batch create test cases
*/
batchCreate = async (cases: Omit<NewAgentEvalTestCase, 'userId'>[]) => {
- const withUserId = cases.map((c) => ({
- ...c,
- userId: this.userId,
- workspaceId: this.workspaceId ?? null,
- }));
- return this.db.insert(agentEvalTestCases).values(withUserId).returning();
+ if (cases.length === 0) return [];
+ return this.db.transaction(async (tx) => {
+ const datasets = await assertWritableEvalDatasets(
+ tx,
+ this.scope(),
+ cases.map((c) => c.datasetId),
+ );
+ await assertEvalDatasetCasesMutable(tx, datasets);
+ await assertReadableEvalEnvironments(tx, this.scope(), cases);
+ const withUserId = cases.map((c) => ({
+ ...c,
+ userId: this.userId,
+ workspaceId: this.workspaceId ?? null,
+ }));
+ return tx.insert(agentEvalTestCases).values(withUserId).returning();
+ });
};
/**
* Delete a test case by id
*/
delete = async (id: string) => {
- return this.db
- .delete(agentEvalTestCases)
- .where(and(eq(agentEvalTestCases.id, id), this.ownership()));
+ return this.db.transaction(async (tx) => {
+ const [testCase] = await tx
+ .select()
+ .from(agentEvalTestCases)
+ .where(and(eq(agentEvalTestCases.id, id), this.mutableOwnership()));
+ if (testCase) {
+ const datasets = await assertWritableEvalDatasets(tx, this.scope(), [testCase.datasetId]);
+ await assertEvalDatasetCasesMutable(tx, datasets);
+ }
+ return tx
+ .delete(agentEvalTestCases)
+ .where(and(eq(agentEvalTestCases.id, id), this.mutableOwnership()));
+ });
};
/**
@@ -82,7 +141,9 @@ export class AgentEvalTestCaseModel {
const query = this.db
.select()
.from(agentEvalTestCases)
- .where(and(eq(agentEvalTestCases.datasetId, datasetId), this.ownership()))
+ .where(
+ and(eq(agentEvalTestCases.datasetId, datasetId), this.ownership(), activeEvalTestCases()),
+ )
.orderBy(agentEvalTestCases.sortOrder);
if (limit !== undefined) {
@@ -108,6 +169,7 @@ export class AgentEvalTestCaseModel {
eq(agentEvalTestCases.datasetId, datasetId),
sql`${agentEvalTestCases.metadata} ->> 'caseId' = ${caseId}`,
this.ownership(),
+ activeEvalTestCases(),
),
)
.limit(1);
@@ -121,7 +183,9 @@ export class AgentEvalTestCaseModel {
const result = await this.db
.select({ value: count() })
.from(agentEvalTestCases)
- .where(and(eq(agentEvalTestCases.datasetId, datasetId), this.ownership()));
+ .where(
+ and(eq(agentEvalTestCases.datasetId, datasetId), this.ownership(), activeEvalTestCases()),
+ );
return Number(result[0]?.value) || 0;
};
@@ -130,22 +194,42 @@ export class AgentEvalTestCaseModel {
*/
update = async (
id: string,
- value: Omit<Partial<NewAgentEvalTestCase>, 'content' | 'userId'> & {
+ value: Omit<
+ Partial<NewAgentEvalTestCase>,
+ 'content' | 'datasetId' | 'id' | 'userId' | 'workspaceId'
+ > & {
content?: Partial<EvalTestCaseContent>;
},
) => {
- const { content, ...data } = value;
- const [result] = await this.db
- .update(agentEvalTestCases)
- .set({
- ...data,
- ...(content !== undefined && {
- content: sql`COALESCE(${agentEvalTestCases.content}, '{}'::jsonb) || ${JSON.stringify(content)}::jsonb`,
- }),
- updatedAt: new Date(),
- })
- .where(and(eq(agentEvalTestCases.id, id), this.ownership()))
- .returning();
- return result;
+ return this.db.transaction(async (tx) => {
+ const [testCase] = await tx
+ .select()
+ .from(agentEvalTestCases)
+ .where(and(eq(agentEvalTestCases.id, id), this.mutableOwnership()));
+ if (!testCase) return undefined;
+ const datasets = await assertWritableEvalDatasets(tx, this.scope(), [testCase.datasetId]);
+ await assertEvalDatasetCasesMutable(tx, datasets);
+ await assertReadableEvalEnvironments(tx, this.scope(), [
+ {
+ content: { ...testCase.content, ...value.content },
+ datasetId: testCase.datasetId,
+ environmentId:
+ value.environmentId === undefined ? testCase.environmentId : value.environmentId,
+ },
+ ]);
+ const { content, ...data } = value;
+ const [result] = await tx
+ .update(agentEvalTestCases)
+ .set({
+ ...data,
+ ...(content !== undefined && {
+ content: sql`COALESCE(${agentEvalTestCases.content}, '{}'::jsonb) || ${JSON.stringify(content)}::jsonb`,
+ }),
+ updatedAt: new Date(),
+ })
+ .where(and(eq(agentEvalTestCases.id, id), this.mutableOwnership()))
+ .returning();
+ return result;
+ });
};
}
diff --git a/packages/database/src/models/connector.ts b/packages/database/src/models/connector.ts
index f20837e7f1c..9abd62fe643 100644
--- a/packages/database/src/models/connector.ts
+++ b/packages/database/src/models/connector.ts
@@ -1,9 +1,11 @@
import { and, asc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';
import type { ConnectorCredentials, NewUserConnector, UserConnectorItem } from '../schemas';
-import { ConnectorStatus, userConnectors, userConnectorTools } from '../schemas';
+import { agentEvalDatasets, ConnectorStatus, userConnectors, userConnectorTools } from '../schemas';
import type { LobeChatDatabase } from '../type';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
+import { EvalConnectorUpdateError, normalizeEvalConnectorPatch } from './connectorEval';
+import { connectorAccessScope } from './connectorScope';
interface GateKeeper {
decrypt: (ciphertext: string) => Promise<{ plaintext: string }>;
@@ -31,6 +33,8 @@ export interface PublicConnectorRecord {
isEnabled: boolean;
mcpConnectionType: string | null;
mcpServerUrl: string | null;
+ /** An Agent mount makes a base connection unavailable to other executors. */
+ mountedByAgentId: string | null;
name: string;
sourceType: string;
status: string;
@@ -59,6 +63,21 @@ export class ConnectorModel {
private db: LobeChatDatabase;
private gateKeeper?: GateKeeper;
private workspaceId?: string;
+ private evaluationDatasetId?: string;
+
+ static forEvaluation(
+ db: LobeChatDatabase,
+ userId: string,
+ datasetId: string,
+ workspaceId?: string,
+ gateKeeper?: GateKeeper,
+ ) {
+ if (!datasetId)
+ throw new EvalConnectorUpdateError('A Dataset is required for evaluation connections');
+ const model = new ConnectorModel(db, userId, workspaceId, gateKeeper);
+ model.evaluationDatasetId = datasetId;
+ return model;
+ }
constructor(db: LobeChatDatabase, userId: string, workspaceId?: string, gateKeeper?: GateKeeper) {
this.db = db;
@@ -68,7 +87,11 @@ export class ConnectorModel {
}
private ownership = () =>
- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, userConnectors);
+ connectorAccessScope(
+ this.db,
+ { userId: this.userId, workspaceId: this.workspaceId },
+ this.evaluationDatasetId,
+ );
/**
* Base (non-agent) scope: the current user/workspace scope restricted to rows
@@ -99,6 +122,7 @@ export class ConnectorModel {
isEnabled: userConnectors.isEnabled,
mcpConnectionType: userConnectors.mcpConnectionType,
mcpServerUrl: userConnectors.mcpServerUrl,
+ mountedByAgentId: sql<string | null>`${userConnectors.metadata} ->> 'mountedByAgentId'`,
name: userConnectors.name,
sourceType: userConnectors.sourceType,
status: userConnectors.status,
@@ -123,6 +147,8 @@ export class ConnectorModel {
// caller down at plan time. See the note on `TopicModel`. `''` is a safe
// sentinel β€” a mount reference is always a real agent id, never empty.
const mountedBy = sql`COALESCE(${userConnectors.metadata} ->> 'mountedByAgentId', '')`;
+ // Private Dataset imports are usable only through an exact evaluation binding.
+ // Exclude them before priority selection and credential decryption in ordinary chat.
if (!agentId) {
return and(this.ownership(), isNull(userConnectors.agentId), sql`${mountedBy} = ''`);
}
@@ -162,21 +188,61 @@ export class ConnectorModel {
params: CreateConnectorParams,
gateKeeper: GateKeeper | undefined = this.gateKeeper,
): Promise<UserConnectorItem> => {
- const credentials = params.credentials
- ? await encryptCredentials(params.credentials, gateKeeper)
- : null;
-
- const [result] = await this.db
- .insert(userConnectors)
- .values(
- buildWorkspacePayload(
- { userId: this.userId, workspaceId: this.workspaceId },
- { ...params, credentials },
- ),
- )
- .returning();
+ return this.db.transaction(async (tx) => {
+ if (!this.evaluationDatasetId && params.metadata?.agentEval) {
+ throw new EvalConnectorUpdateError(
+ 'Use the Dataset connection API for evaluation connections',
+ );
+ }
+ if (this.evaluationDatasetId) {
+ const [dataset] = await tx
+ .select({ id: agentEvalDatasets.id })
+ .from(agentEvalDatasets)
+ .where(
+ and(
+ eq(agentEvalDatasets.id, this.evaluationDatasetId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentEvalDatasets,
+ ),
+ ),
+ )
+ .for('share');
+ if (!dataset) throw new EvalConnectorUpdateError('Dataset not found');
+ if (params.credentials && !gateKeeper)
+ throw new EvalConnectorUpdateError('Secure connection storage is unavailable');
+ if (params.agentId || params.metadata?.mountedByAgentId)
+ throw new EvalConnectorUpdateError(
+ 'Evaluation connections cannot be assigned to a normal Agent',
+ );
+ const marker = params.metadata?.agentEval;
+ params = {
+ ...params,
+ metadata: {
+ ...params.metadata,
+ agentEval: {
+ ...(marker && typeof marker === 'object' && !Array.isArray(marker) ? marker : {}),
+ datasetId: this.evaluationDatasetId,
+ },
+ },
+ };
+ }
+ const credentials = params.credentials
+ ? await encryptCredentials(params.credentials, gateKeeper)
+ : null;
+
+ const [result] = await tx
+ .insert(userConnectors)
+ .values(
+ buildWorkspacePayload(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ { ...params, credentials },
+ ),
+ )
+ .returning();
- return result;
+ return result;
+ });
};
/**
@@ -193,7 +259,7 @@ export class ConnectorModel {
.from(userConnectors)
.where(and(eq(userConnectors.id, sourceId), this.ownership()))
.limit(1);
- if (!source) return null;
+ if (!source || source.metadata?.agentEval) return null;
const { id: _id, createdAt: _c, updatedAt: _u, metadata, ...rest } = source;
const cleanedMetadata = metadata
@@ -457,21 +523,41 @@ export class ConnectorModel {
patch: UpdateConnectorParams,
gateKeeper: GateKeeper | undefined = this.gateKeeper,
): Promise<void> => {
- const credentials =
- patch.credentials !== undefined && patch.credentials !== null
- ? await encryptCredentials(patch.credentials, gateKeeper)
- : undefined;
-
- const set = {
- ...patch,
- ...(credentials !== undefined ? { credentials } : {}),
- updatedAt: new Date(),
- };
-
- await this.db
- .update(userConnectors)
- .set(set)
- .where(and(eq(userConnectors.id, id), this.ownership()));
+ await this.db.transaction(async (tx) => {
+ const [current] = await tx
+ .select()
+ .from(userConnectors)
+ .where(and(eq(userConnectors.id, id), this.ownership()))
+ .limit(1)
+ .for('update');
+ if (!current) return;
+ const normalized = await normalizeEvalConnectorPatch(
+ current,
+ patch,
+ gateKeeper?.decrypt.bind(gateKeeper),
+ );
+ if (current.metadata?.agentEval && normalized.credentials && !gateKeeper) {
+ throw new EvalConnectorUpdateError('Secure connection storage is unavailable');
+ }
+ let credentials: string | undefined;
+ if (normalized.credentials !== undefined && normalized.credentials !== null) {
+ try {
+ credentials = await encryptCredentials(normalized.credentials, gateKeeper);
+ } catch (error) {
+ if (current.metadata?.agentEval)
+ throw new EvalConnectorUpdateError('Could not securely store the mock connection');
+ throw error;
+ }
+ }
+ await tx
+ .update(userConnectors)
+ .set({
+ ...normalized,
+ ...(credentials !== undefined ? { credentials } : {}),
+ updatedAt: new Date(),
+ })
+ .where(and(eq(userConnectors.id, id), this.ownership()));
+ });
};
updateStatus = async (id: string, status: ConnectorStatus): Promise<void> => {
diff --git a/packages/database/src/models/connectorEval.ts b/packages/database/src/models/connectorEval.ts
new file mode 100644
index 00000000000..2474aa3872a
--- /dev/null
+++ b/packages/database/src/models/connectorEval.ts
@@ -0,0 +1,179 @@
+import type {
+ ConnectorCredentials,
+ ConnectorMetadata,
+ NewUserConnector,
+ UserConnectorItem,
+} from '../schemas';
+
+type ConnectorPatch = Partial<Omit<NewUserConnector, 'userId' | 'id' | 'createdAt' | 'updatedAt'>>;
+
+export class EvalConnectorUpdateError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'EvalConnectorUpdateError';
+ }
+}
+
+/** Import provenance is server-owned; ordinary connector requests cannot create it. */
+export const withoutEvalConnectorMarker = (
+ metadata: ConnectorMetadata | null | undefined,
+): ConnectorMetadata | null | undefined => {
+ if (!metadata) return metadata;
+ const { agentEval: _agentEval, ...rest } = metadata;
+ return rest;
+};
+
+const validatedHeaders = (value: unknown): Record<string, string> => {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new EvalConnectorUpdateError('Invalid mock connection headers');
+ }
+ const entries = Object.entries(value);
+ if (
+ entries.some(
+ ([key, entry]) =>
+ !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(key) ||
+ typeof entry !== 'string' ||
+ /[\r\n]/.test(entry),
+ )
+ )
+ throw new EvalConnectorUpdateError('Invalid mock connection headers');
+ return Object.fromEntries(entries);
+};
+
+const parseCredentials = (plaintext: string): ConnectorCredentials => {
+ try {
+ const value = JSON.parse(plaintext) as ConnectorCredentials;
+ if (value?.type === 'header')
+ return { headers: validatedHeaders(value.headers), type: 'header' };
+ if (value?.type === 'bearer' && typeof value.token === 'string' && !/[\r\n]/.test(value.token))
+ return value;
+ if (
+ value?.type === 'apikey' &&
+ typeof value.apiKey === 'string' &&
+ !/[\r\n]/.test(value.apiKey)
+ )
+ return value;
+ if (value?.type === 'oauth2' && typeof value.accessToken === 'string') return value;
+ } catch {
+ // Never expose a JSON parse error that could contain a credential value.
+ }
+ throw new EvalConnectorUpdateError('Invalid mock connection credentials');
+};
+
+/** Normalize imported mock edits before encryption; never put their headers in metadata. */
+export const normalizeEvalConnectorPatch = async (
+ current: Pick<UserConnectorItem, 'credentials' | 'metadata' | 'mcpServerUrl'>,
+ patch: ConnectorPatch,
+ decrypt?: (ciphertext: string) => Promise<{ plaintext: string }>,
+): Promise<ConnectorPatch> => {
+ const marker = current.metadata?.agentEval;
+ if (!marker)
+ return {
+ ...patch,
+ ...(patch.metadata === undefined
+ ? {}
+ : { metadata: withoutEvalConnectorMarker(patch.metadata) }),
+ };
+
+ if (patch.agentId || patch.metadata?.mountedByAgentId) {
+ throw new EvalConnectorUpdateError(
+ 'Evaluation connections cannot be assigned to a normal Agent.',
+ );
+ }
+ const result = { ...patch };
+ if (patch.mcpServerUrl != null) {
+ let safeUrl = false;
+ try {
+ const url = new URL(patch.mcpServerUrl);
+ safeUrl =
+ ['http:', 'https:'].includes(url.protocol) &&
+ !url.username &&
+ !url.password &&
+ !url.search &&
+ !url.hash;
+ } catch {
+ // Keep addresses that could contain credentials out of error text.
+ }
+ if (!safeUrl)
+ throw new EvalConnectorUpdateError(
+ 'Use an HTTP MCP address without embedded credentials, query or fragment',
+ );
+ }
+ const headersSubmitted = Object.hasOwn(patch.metadata ?? {}, 'customHeaders');
+ const storedHeaders = current.metadata?.customHeaders;
+ const migrateHeaders =
+ !headersSubmitted && storedHeaders !== undefined && patch.credentials === undefined;
+ const headers = headersSubmitted
+ ? validatedHeaders(patch.metadata?.customHeaders ?? {})
+ : migrateHeaders
+ ? validatedHeaders(storedHeaders)
+ : undefined;
+ if (patch.metadata !== undefined || storedHeaders !== undefined) {
+ const { customHeaders: _headers, ...metadata } =
+ patch.metadata !== undefined ? (patch.metadata ?? {}) : (current.metadata ?? {});
+ result.metadata = { ...metadata, agentEval: marker };
+ }
+ const urlChanged =
+ patch.mcpServerUrl !== undefined && patch.mcpServerUrl !== current.mcpServerUrl;
+ if (
+ urlChanged &&
+ patch.credentials === undefined &&
+ (current.credentials || Object.keys(headers ?? {}).length)
+ ) {
+ throw new EvalConnectorUpdateError(
+ 'Clear or replace authentication when changing a mock connection address',
+ );
+ }
+ // The existing editor resends its header form while explicitly clearing auth on a URL edit.
+ // Treat that clear as authoritative so old header tokens cannot follow the new address.
+ if (urlChanged && patch.credentials === null) {
+ return { ...result, credentials: null, status: 'disconnected', tokenExpiresAt: null };
+ }
+
+ let credentials: ConnectorCredentials | null | undefined;
+ if (patch.credentials !== undefined) {
+ credentials = patch.credentials === null ? null : parseCredentials(patch.credentials);
+ } else if (headers !== undefined && current.credentials) {
+ if (!decrypt) throw new EvalConnectorUpdateError('Secure connection storage is unavailable');
+ try {
+ credentials = parseCredentials((await decrypt(current.credentials)).plaintext);
+ } catch {
+ throw new EvalConnectorUpdateError('Could not securely read the mock connection');
+ }
+ }
+ if (headers !== undefined) {
+ if (credentials?.type === 'oauth2') {
+ if (Object.keys(headers).length)
+ throw new EvalConnectorUpdateError(
+ 'Use OAuth authentication without custom headers for this mock connection',
+ );
+ } else if (credentials?.type === 'bearer' || credentials?.type === 'apikey') {
+ if (Object.keys(headers).length) {
+ const token = credentials.type === 'bearer' ? credentials.token : credentials.apiKey;
+ // A separate bearer credential is authoritative over a case-insensitive Authorization header.
+ credentials = {
+ headers: {
+ ...Object.fromEntries(
+ Object.entries(headers).filter(([key]) => key.toLowerCase() !== 'authorization'),
+ ),
+ Authorization: `Bearer ${token}`,
+ },
+ type: 'header',
+ };
+ }
+ } else {
+ // Header edits replace the complete header set; {} clears it.
+ const combined =
+ credentials?.type === 'header' && patch.credentials !== undefined
+ ? { ...credentials.headers, ...headers }
+ : headers;
+ credentials = Object.keys(combined).length ? { headers: combined, type: 'header' } : null;
+ }
+ }
+ if (credentials !== undefined) {
+ result.credentials = credentials === null ? null : JSON.stringify(credentials);
+ result.status = 'disconnected';
+ if (credentials?.type !== 'oauth2') result.tokenExpiresAt = null;
+ } else if (urlChanged) result.status = 'disconnected';
+ return result;
+};
diff --git a/packages/database/src/models/connectorScope.ts b/packages/database/src/models/connectorScope.ts
new file mode 100644
index 00000000000..6f46f7b68e9
--- /dev/null
+++ b/packages/database/src/models/connectorScope.ts
@@ -0,0 +1,31 @@
+import { and, eq, exists, sql } from 'drizzle-orm';
+
+import { agentEvalDatasets, userConnectors } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+import { buildWorkspaceWhere } from '../utils/workspace';
+
+/** Shared by connection rows and their tool rows; default access is ordinary-only. */
+export const connectorAccessScope = (
+ db: LobeChatDatabase,
+ scope: { userId: string; workspaceId?: string },
+ datasetId?: string,
+) =>
+ and(
+ buildWorkspaceWhere(scope, userConnectors),
+ datasetId
+ ? and(
+ sql`${userConnectors.metadata} -> 'agentEval' ->> 'datasetId' = ${datasetId}`,
+ exists(
+ db
+ .select({ id: agentEvalDatasets.id })
+ .from(agentEvalDatasets)
+ .where(
+ and(
+ eq(agentEvalDatasets.id, datasetId),
+ buildWorkspaceWhere(scope, agentEvalDatasets),
+ ),
+ ),
+ ),
+ )
+ : sql`COALESCE(${userConnectors.metadata} ->> 'agentEval', '') = ''`,
+ );
diff --git a/packages/database/src/models/connectorTool.ts b/packages/database/src/models/connectorTool.ts
index 350a493086f..eb3c24d9c64 100644
--- a/packages/database/src/models/connectorTool.ts
+++ b/packages/database/src/models/connectorTool.ts
@@ -1,4 +1,4 @@
-import { and, asc, eq, inArray, ne, notInArray, sql } from 'drizzle-orm';
+import { and, asc, eq, exists, inArray, ne, notInArray, sql } from 'drizzle-orm';
import type {
ConnectorToolPermission,
@@ -6,9 +6,14 @@ import type {
ToolCRUDType,
UserConnectorToolItem,
} from '../schemas';
-import { ConnectorToolPermission as Permission, userConnectorTools } from '../schemas';
+import {
+ ConnectorToolPermission as Permission,
+ userConnectors,
+ userConnectorTools,
+} from '../schemas';
import type { LobeChatDatabase } from '../type';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
+import { connectorAccessScope } from './connectorScope';
export interface SyncToolInput {
crudType: ToolCRUDType;
@@ -28,6 +33,19 @@ export class ConnectorToolModel {
private userId: string;
private db: LobeChatDatabase;
private workspaceId?: string;
+ private evaluationDatasetId?: string;
+
+ static forEvaluation(
+ db: LobeChatDatabase,
+ userId: string,
+ datasetId: string,
+ workspaceId?: string,
+ ) {
+ if (!datasetId) throw new Error('A Dataset is required for evaluation tools');
+ const model = new ConnectorToolModel(db, userId, workspaceId);
+ model.evaluationDatasetId = datasetId;
+ return model;
+ }
constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
this.db = db;
@@ -36,7 +54,27 @@ export class ConnectorToolModel {
}
private ownership = () =>
- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, userConnectorTools);
+ and(
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ userConnectorTools,
+ ),
+ exists(
+ this.db
+ .select({ id: userConnectors.id })
+ .from(userConnectors)
+ .where(
+ and(
+ eq(userConnectors.id, userConnectorTools.userConnectorId),
+ connectorAccessScope(
+ this.db,
+ { userId: this.userId, workspaceId: this.workspaceId },
+ this.evaluationDatasetId,
+ ),
+ ),
+ ),
+ ),
+ );
/**
* Deterministic tool order: grouped by connector, sorted by toolName within it.
@@ -68,6 +106,20 @@ export class ConnectorToolModel {
*/
upsertMany = async (userConnectorId: string, tools: SyncToolInput[]): Promise<void> => {
if (tools.length === 0) return;
+ const [parent] = await this.db
+ .select({ id: userConnectors.id })
+ .from(userConnectors)
+ .where(
+ and(
+ eq(userConnectors.id, userConnectorId),
+ connectorAccessScope(
+ this.db,
+ { userId: this.userId, workspaceId: this.workspaceId },
+ this.evaluationDatasetId,
+ ),
+ ),
+ );
+ if (!parent) throw new Error('Connection not available');
const values: NewUserConnectorTool[] = tools.map((t) =>
buildWorkspacePayload(
diff --git a/packages/database/src/models/plugin.ts b/packages/database/src/models/plugin.ts
index 3becd7ee4ac..2352f5e7b63 100644
--- a/packages/database/src/models/plugin.ts
+++ b/packages/database/src/models/plugin.ts
@@ -1,5 +1,5 @@
import type { LobeTool } from '@lobechat/types';
-import { and, desc, eq } from 'drizzle-orm';
+import { and, desc, eq, sql } from 'drizzle-orm';
import type { InstalledPluginItem, NewInstalledPlugin } from '../schemas';
import { userInstalledPlugins } from '../schemas';
@@ -23,28 +23,48 @@ export class PluginModel {
userInstalledPlugins,
);
+ // Legacy evaluation installations are quarantined by server-owned provenance.
+ private visible = () =>
+ and(this.ownership(), sql`COALESCE(${userInstalledPlugins.source}, '') <> 'agent-eval'`);
+
create = async (
params: Pick<
NewInstalledPlugin,
'type' | 'identifier' | 'manifest' | 'customParams' | 'settings' | 'source'
>,
) => {
- const [result] = await this.db
- .insert(userInstalledPlugins)
- .values({ ...params, userId: this.userId, workspaceId: this.workspaceId ?? null })
- .onConflictDoUpdate({
- set: { ...params, updatedAt: new Date() },
- target: [userInstalledPlugins.identifier, userInstalledPlugins.userId],
- })
- .returning();
-
- return result;
+ return this.db.transaction(async (tx) => {
+ // Legacy eval installs share this table's (userId, identifier) primary key.
+ // Move only their storage key aside; keep the manifest, address and auth intact.
+ // Model-facing identifiers live in the frozen contract, independently of this key.
+ if (params.source !== 'agent-eval') {
+ await tx
+ .update(userInstalledPlugins)
+ .set({ identifier: `agent-eval:${crypto.randomUUID()}` })
+ .where(
+ and(
+ eq(userInstalledPlugins.userId, this.userId),
+ eq(userInstalledPlugins.identifier, params.identifier),
+ eq(userInstalledPlugins.source, 'agent-eval'),
+ ),
+ );
+ }
+ const [result] = await tx
+ .insert(userInstalledPlugins)
+ .values({ ...params, userId: this.userId, workspaceId: this.workspaceId ?? null })
+ .onConflictDoUpdate({
+ set: { ...params, updatedAt: new Date() },
+ target: [userInstalledPlugins.identifier, userInstalledPlugins.userId],
+ })
+ .returning();
+ return result;
+ });
};
delete = async (id: string) => {
return this.db
.delete(userInstalledPlugins)
- .where(and(eq(userInstalledPlugins.identifier, id), this.ownership()));
+ .where(and(eq(userInstalledPlugins.identifier, id), this.visible()));
};
deleteAll = async () => {
@@ -64,7 +84,7 @@ export class PluginModel {
updatedAt: userInstalledPlugins.updatedAt,
})
.from(userInstalledPlugins)
- .where(this.ownership())
+ .where(this.visible())
.orderBy(desc(userInstalledPlugins.createdAt));
return data.map<LobeTool>((item) => ({
@@ -75,7 +95,7 @@ export class PluginModel {
findById = async (id: string) => {
return this.db.query.userInstalledPlugins.findFirst({
- where: and(eq(userInstalledPlugins.identifier, id), this.ownership()),
+ where: and(eq(userInstalledPlugins.identifier, id), this.visible()),
});
};
@@ -83,6 +103,6 @@ export class PluginModel {
return this.db
.update(userInstalledPlugins)
.set({ ...value, updatedAt: new Date() })
- .where(and(eq(userInstalledPlugins.identifier, id), this.ownership()));
+ .where(and(eq(userInstalledPlugins.identifier, id), this.visible()));
};
}
diff --git a/packages/database/src/models/topic/memoryExtractor.ts b/packages/database/src/models/topic/memoryExtractor.ts
index 4d4a13e7435..fbe3f55fc43 100644
--- a/packages/database/src/models/topic/memoryExtractor.ts
+++ b/packages/database/src/models/topic/memoryExtractor.ts
@@ -1,6 +1,7 @@
import { and, count, eq, gt, gte, lte, ne, or, sql } from 'drizzle-orm';
import { topics } from '../../schemas';
+import { notEvalTopic } from '../../utils/evalTopic';
import { notChannelTopic } from '../../utils/topicVisibility';
import type { TopicModelContext } from './context';
import type { ListTopicsForMemoryExtractorCursor } from './types';
@@ -41,6 +42,8 @@ export const listTopicsForMemoryExtractor = async (
// other members' Channel content, which stays inside the Channel.
ctx.notShareVisitor(),
notChannelTopic(),
+ // Eval dialogue is a test script, not the user's own speech.
+ notEvalTopic(),
options.startDate ? gte(topics.createdAt, options.startDate) : undefined,
options.endDate ? lte(topics.createdAt, options.endDate) : undefined,
options.ignoreExtracted
@@ -70,6 +73,7 @@ export const countTopicsForMemoryExtractor = async (
ctx.ownership(),
ctx.notShareVisitor(),
notChannelTopic(),
+ notEvalTopic(),
options.startDate ? gte(topics.createdAt, options.startDate) : undefined,
options.endDate ? lte(topics.createdAt, options.endDate) : undefined,
options.ignoreExtracted
diff --git a/packages/database/src/models/userMemory/__tests__/query.surface.test.ts b/packages/database/src/models/userMemory/__tests__/query.surface.test.ts
index d4c52f16d14..887a15ed902 100644
--- a/packages/database/src/models/userMemory/__tests__/query.surface.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/query.surface.test.ts
@@ -16,12 +16,19 @@ const functionMembers = (target: object) =>
describe('UserMemoryQueryModel surface', () => {
it('keeps the module runtime exports', () => {
expect(Object.keys(queryModule).sort()).toEqual([
+ 'DEFAULT_HYBRID_SEARCH_LIMIT',
+ 'HYBRID_SEARCH_OVERFETCH_MULTIPLIER',
'USER_MEMORY_LEXICAL_QUERY_CHARACTER_LIMIT',
'UserMemoryQueryModel',
'buildBm25MatchCondition',
+ 'buildRetrievalQuery',
+ 'combineEmbeddings',
+ 'hasSearchFilters',
'normalizeUserMemorySearchQueries',
'scoreHybridCandidates',
+ 'shouldRunSemanticSearch',
'shouldRunUserMemoryLexicalSearch',
+ 'toSearchTags',
]);
expect(queryModule.USER_MEMORY_LEXICAL_QUERY_CHARACTER_LIMIT).toBe(256);
});
diff --git a/packages/database/src/models/userMemory/query/index.ts b/packages/database/src/models/userMemory/query/index.ts
index b0988108665..8b8cc1c7a01 100644
--- a/packages/database/src/models/userMemory/query/index.ts
+++ b/packages/database/src/models/userMemory/query/index.ts
@@ -72,10 +72,20 @@ import {
} from './taxonomy';
import type { SearchLayerKey, UserMemoryHybridSearchAggregatedResult } from './types';
+export { DEFAULT_HYBRID_SEARCH_LIMIT } from './constants';
export { buildBm25MatchCondition } from './lexical';
export { scoreHybridCandidates } from './scoring';
+// The storage-independent parts of the hybrid search, so another store of the
+// same Memory entries (an eval attempt's) ranks them the way the account's are.
+export {
+ hasSearchFilters,
+ HYBRID_SEARCH_OVERFETCH_MULTIPLIER,
+ shouldRunSemanticSearch,
+ toSearchTags,
+} from './searchFilters';
export type {
Bm25MatchFieldGroup,
+ HybridSearchLayerMeta,
LayerBaseMemorySignals,
RankedSearchCandidate,
RecommendationScoreBreakdown,
@@ -83,6 +93,8 @@ export type {
UserMemoryHybridSearchAggregatedResult,
} from './types';
export {
+ buildRetrievalQuery,
+ combineEmbeddings,
normalizeUserMemorySearchQueries,
shouldRunUserMemoryLexicalSearch,
USER_MEMORY_LEXICAL_QUERY_CHARACTER_LIMIT,
diff --git a/packages/database/src/models/userMemory/query/searchFilters.ts b/packages/database/src/models/userMemory/query/searchFilters.ts
index 6454d1e664e..7e1deaefb12 100644
--- a/packages/database/src/models/userMemory/query/searchFilters.ts
+++ b/packages/database/src/models/userMemory/query/searchFilters.ts
@@ -8,7 +8,7 @@ import type { UserMemoryQueryContext } from './context';
import type { LayerBaseMemorySignals, SearchLayerKey } from './types';
import { coerceDate } from './utils';
-const HYBRID_SEARCH_OVERFETCH_MULTIPLIER = 3;
+export const HYBRID_SEARCH_OVERFETCH_MULTIPLIER = 3;
export function getSearchLimit(key: SearchLayerKey, params: SearchMemoryParams) {
return params.topK?.[key] ?? DEFAULT_HYBRID_SEARCH_LIMIT;
diff --git a/packages/database/src/repositories/agentEvalDatasetDeletion/index.test.ts b/packages/database/src/repositories/agentEvalDatasetDeletion/index.test.ts
new file mode 100644
index 00000000000..80477bb5435
--- /dev/null
+++ b/packages/database/src/repositories/agentEvalDatasetDeletion/index.test.ts
@@ -0,0 +1,154 @@
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { AgentEvalDatasetModel } from '../../models/agentEval/dataset';
+import { ConnectorModel } from '../../models/connector';
+import { ConnectorToolModel } from '../../models/connectorTool';
+import {
+ agentEvalDatasets,
+ userConnectors,
+ userConnectorTools,
+ users,
+ workspaces,
+} from '../../schemas';
+import { AgentEvalDatasetDeletionRepo } from './index';
+
+const db = await getTestDB();
+const userId = 'dataset-delete-owner';
+const otherUserId = 'dataset-delete-other';
+const workspaceId = 'dataset-delete-workspace';
+const datasets = new AgentEvalDatasetModel(db, userId);
+const deletion = new AgentEvalDatasetDeletionRepo(db, userId);
+const gateKeeper = {
+ decrypt: async (ciphertext: string) => ({ plaintext: ciphertext.replace(/^sealed:/, '') }),
+ encrypt: async (plaintext: string) => `sealed:${plaintext}`,
+};
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await db.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+});
+afterEach(async () => {
+ await db.delete(agentEvalDatasets);
+ await db.delete(workspaces);
+ await db.delete(users);
+});
+
+const createConnection = (datasetId: string, actorId = userId, workspace?: string) =>
+ ConnectorModel.forEvaluation(db, actorId, datasetId, workspace, gateKeeper).create({
+ credentials: JSON.stringify({ token: 'fixture-private-token', type: 'bearer' }),
+ identifier: `private-${crypto.randomUUID()}`,
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://fixture.test/mcp',
+ name: 'Notion',
+ sourceType: 'custom',
+ status: 'connected',
+ });
+
+describe('Dataset deletion removes its private evaluation connections', () => {
+ it('deletes owned marked credentials and cascades tools while keeping ordinary and other-Dataset rows', async () => {
+ const first = await datasets.create({ identifier: 'first', name: 'First' });
+ const second = await datasets.create({ identifier: 'second', name: 'Second' });
+ const own = await createConnection(first.id);
+ const otherDataset = await createConnection(second.id);
+ const ordinary = await new ConnectorModel(db, userId, undefined, gateKeeper).create({
+ credentials: JSON.stringify({ token: 'ordinary-private-token', type: 'bearer' }),
+ identifier: 'notion',
+ name: 'Notion',
+ sourceType: 'custom',
+ status: 'connected',
+ });
+ const [otherOwner] = await db
+ .insert(userConnectors)
+ .values({
+ credentials: 'sealed:other-owner-secret',
+ identifier: 'foreign-marker',
+ metadata: { agentEval: { datasetId: first.id } },
+ name: 'Other owner',
+ sourceType: 'custom',
+ status: 'connected',
+ userId: otherUserId,
+ })
+ .returning();
+ await ConnectorToolModel.forEvaluation(db, userId, first.id).upsertMany(own.id, [
+ { crudType: 'read', toolName: 'read' },
+ ]);
+ await ConnectorToolModel.forEvaluation(db, userId, second.id).upsertMany(otherDataset.id, [
+ { crudType: 'read', toolName: 'read' },
+ ]);
+ expect(own.credentials).toMatch(/^sealed:/);
+ expect(await db.select().from(userConnectorTools)).toHaveLength(2);
+
+ await deletion.deleteDataset(first.id);
+
+ expect(await datasets.findById(first.id)).toBeUndefined();
+ expect((await db.select().from(userConnectors)).map(({ id }) => id).sort()).toEqual(
+ [ordinary.id, otherDataset.id, otherOwner.id].sort(),
+ );
+ expect(await db.select().from(userConnectorTools)).toMatchObject([
+ { userConnectorId: otherDataset.id },
+ ]);
+ const preserved = await db.select().from(userConnectors);
+ expect(preserved.find(({ id }) => id === ordinary.id)?.credentials).toBe(ordinary.credentials);
+ expect(preserved.find(({ id }) => id === otherDataset.id)?.credentials).toBe(
+ otherDataset.credentials,
+ );
+ expect(preserved.find(({ id }) => id === otherOwner.id)?.credentials).toBe(
+ otherOwner.credentials,
+ );
+ });
+
+ it('does not remove any connection when the Dataset is foreign, missing, or system-owned', async () => {
+ const owned = await datasets.create({ identifier: 'owned', name: 'Owned' });
+ const connection = await createConnection(owned.id);
+ const [system] = await db
+ .insert(agentEvalDatasets)
+ .values({ identifier: 'system', name: 'System', userId: null })
+ .returning();
+ const [systemConnection] = await db
+ .insert(userConnectors)
+ .values({
+ credentials: 'sealed:system-fixture-secret',
+ identifier: 'system-connection',
+ metadata: { agentEval: { datasetId: system.id } },
+ name: 'System connection',
+ sourceType: 'custom',
+ status: 'connected',
+ userId,
+ })
+ .returning();
+ await new AgentEvalDatasetDeletionRepo(db, otherUserId).deleteDataset(owned.id);
+ await deletion.deleteDataset('missing-dataset');
+ await deletion.deleteDataset(system.id);
+ expect((await db.select().from(userConnectors)).map(({ id }) => id).sort()).toEqual(
+ [connection.id, systemConnection.id].sort(),
+ );
+ expect(await datasets.findById(owned.id)).toBeDefined();
+ });
+
+ it('cleans workspace connections across creators only from the authorized workspace scope', async () => {
+ const workspaceDatasets = new AgentEvalDatasetModel(db, userId, workspaceId);
+ const workspaceDeletion = new AgentEvalDatasetDeletionRepo(db, userId, workspaceId);
+ const dataset = await workspaceDatasets.create({ identifier: 'shared', name: 'Shared' });
+ const shared = await createConnection(dataset.id, otherUserId, workspaceId);
+ await ConnectorToolModel.forEvaluation(db, userId, dataset.id, workspaceId).upsertMany(
+ shared.id,
+ [{ crudType: 'read', toolName: 'read' }],
+ );
+ await deletion.deleteDataset(dataset.id);
+ expect(
+ await db.select().from(userConnectors).where(eq(userConnectors.id, shared.id)),
+ ).toHaveLength(1);
+
+ await workspaceDeletion.deleteDataset(dataset.id);
+ expect(await db.select().from(userConnectors)).toEqual([]);
+ expect(await db.select().from(userConnectorTools)).toEqual([]);
+ });
+});
diff --git a/packages/database/src/repositories/agentEvalDatasetDeletion/index.ts b/packages/database/src/repositories/agentEvalDatasetDeletion/index.ts
new file mode 100644
index 00000000000..1dc56d27923
--- /dev/null
+++ b/packages/database/src/repositories/agentEvalDatasetDeletion/index.ts
@@ -0,0 +1,77 @@
+import { and, eq, inArray, isNotNull, sql } from 'drizzle-orm';
+
+import {
+ agentEvalDatasets,
+ agentEvalEnvironments,
+ agentEvalTestCases,
+ userConnectors,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { buildWorkspaceWhere, normalizeWorkspaceId } from '../../utils/workspace';
+
+/**
+ * Deletes a user-owned Dataset together with the private evaluation
+ * connections it marked. Connections are their own aggregate, so the unit of
+ * work lives here rather than in `AgentEvalDatasetModel`.
+ */
+export class AgentEvalDatasetDeletionRepo {
+ private readonly scope: { userId: string; workspaceId?: string };
+
+ constructor(
+ private readonly db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+ ) {
+ this.scope = { userId, workspaceId: normalizeWorkspaceId(workspaceId) ?? undefined };
+ }
+
+ /** Mutate-only predicate excluding system rows. */
+ private mutableOwnership = () =>
+ and(buildWorkspaceWhere(this.scope, agentEvalDatasets), isNotNull(agentEvalDatasets.userId));
+
+ deleteDataset = async (id: string) =>
+ this.db.transaction(async (tx) => {
+ const [dataset] = await tx
+ .select({ id: agentEvalDatasets.id })
+ .from(agentEvalDatasets)
+ .where(and(eq(agentEvalDatasets.id, id), this.mutableOwnership()))
+ .for('update');
+ if (dataset) {
+ // The Dataset marker has no FK. Remove its private credentials in the
+ // same transaction; connection tools cascade through their existing FK.
+ await tx
+ .delete(userConnectors)
+ .where(
+ and(
+ buildWorkspaceWhere(this.scope, userConnectors),
+ sql`${userConnectors.metadata} -> 'agentEval' ->> 'datasetId' = ${dataset.id}`,
+ ),
+ );
+ }
+ const usedEnvironments = dataset
+ ? await tx
+ .selectDistinct({ id: agentEvalTestCases.environmentId })
+ .from(agentEvalTestCases)
+ .where(eq(agentEvalTestCases.datasetId, dataset.id))
+ : [];
+ const result = await tx
+ .delete(agentEvalDatasets)
+ .where(and(eq(agentEvalDatasets.id, id), this.mutableOwnership()));
+ // Environments holding stored connections (and their encrypted credentials)
+ // go with the last Dataset using them, like the Dataset's connector rows.
+ const environmentIds = usedEnvironments.flatMap(({ id }) => (id ? [id] : []));
+ if (environmentIds.length)
+ await tx
+ .delete(agentEvalEnvironments)
+ .where(
+ and(
+ inArray(agentEvalEnvironments.id, environmentIds),
+ buildWorkspaceWhere(this.scope, agentEvalEnvironments),
+ isNotNull(agentEvalEnvironments.userId),
+ sql`${agentEvalEnvironments.config} ? 'connections'`,
+ sql`NOT EXISTS (SELECT 1 FROM ${agentEvalTestCases} WHERE ${agentEvalTestCases.environmentId} = ${agentEvalEnvironments.id})`,
+ ),
+ );
+ return result;
+ });
+}
diff --git a/packages/database/src/repositories/agentEvalDatasetPackage/__tests__/datasetConnectorBindings.test.ts b/packages/database/src/repositories/agentEvalDatasetPackage/__tests__/datasetConnectorBindings.test.ts
new file mode 100644
index 00000000000..dcac2dc111c
--- /dev/null
+++ b/packages/database/src/repositories/agentEvalDatasetPackage/__tests__/datasetConnectorBindings.test.ts
@@ -0,0 +1,244 @@
+import type { AgentEvalDatasetPackage } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { AgentEvalDatasetWriteError } from '../../../models/agentEval/datasetAccess';
+import {
+ agentEvalBenchmarks,
+ agentEvalDatasets,
+ agentEvalEnvironments,
+ agentEvalTestCases,
+ userConnectors,
+ users,
+} from '../../../schemas';
+import { AgentEvalDatasetConnectorRepo } from '../datasetConnectorBindings';
+import { AgentEvalDatasetPackageRepo } from '../index';
+
+const db = await getTestDB();
+const userId = 'binding-owner';
+const otherId = 'binding-other';
+const connector = { connectorId: 'b34a8f4d-349a-41a9-b307-3a8754e8e5a8' };
+const repository = new AgentEvalDatasetConnectorRepo(db, userId);
+const packageRepo = new AgentEvalDatasetPackageRepo(db, userId);
+const pack = (): AgentEvalDatasetPackage => ({
+ cases: [
+ { content: { input: 'One' }, environmentKey: 'shared', key: 'one' },
+ {
+ content: { environment: { mock: { services: ['notion'] } }, input: 'Two' },
+ environmentKey: 'shared',
+ key: 'two',
+ },
+ ],
+ dataset: {
+ evalMode: 'equals',
+ metadata: { release: 'stable-release' },
+ name: 'Connection repair',
+ },
+ environments: [
+ {
+ config: { memory: {}, mock: { services: ['calendar', 'notion'] } },
+ key: 'shared',
+ name: 'Shared',
+ },
+ ],
+ format: 'lobehub-eval-dataset',
+ version: 1,
+});
+const importPackage = async () => {
+ const result = await packageRepo.importPackage({ package: pack(), sha256: 'c'.repeat(64) });
+ await db
+ .insert(userConnectors)
+ .values({
+ id: connector.connectorId,
+ identifier: 'eval-private',
+ name: 'Eval',
+ sourceType: 'custom',
+ status: 'connected',
+ userId,
+ metadata: { agentEval: { datasetId: result.datasetId } },
+ })
+ .onConflictDoNothing();
+ return result;
+};
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: userId }, { id: otherId }]);
+});
+afterEach(async () => {
+ await db.delete(agentEvalTestCases);
+ await db.delete(agentEvalDatasets);
+ await db.delete(agentEvalEnvironments);
+ await db.delete(agentEvalBenchmarks);
+ await db.delete(users);
+});
+
+describe('installed dataset connector bindings', () => {
+ it('rejects a connection from another Dataset even within the same account', async () => {
+ await importPackage();
+ const second = await importPackage();
+ const { requirements } = await repository.getBindings(second.datasetId);
+ await expect(
+ repository.updateBindings(second.datasetId, {
+ environmentBindings: { [requirements[0].key]: { calendar: connector, notion: connector } },
+ }),
+ ).rejects.toThrow('another Dataset');
+ expect((await repository.getBindings(second.datasetId)).requirements[0].bindings).toEqual({});
+ });
+
+ it('reads built-in dataset requirements while keeping built-in datasets and environments read-only', async () => {
+ const { datasetId } = await importPackage();
+ const before = await repository.getBindings(datasetId);
+ const environmentId = before.requirements.find((item) => item.scope === 'environment')!.key;
+ await db
+ .update(agentEvalDatasets)
+ .set({ userId: null })
+ .where(eq(agentEvalDatasets.id, datasetId));
+ await db
+ .update(agentEvalEnvironments)
+ .set({ userId: null })
+ .where(eq(agentEvalEnvironments.id, environmentId));
+ await db
+ .update(agentEvalTestCases)
+ .set({ userId: null })
+ .where(eq(agentEvalTestCases.datasetId, datasetId));
+ expect(
+ (await repository.getBindings(datasetId)).requirements.map((item) => item.services),
+ ).toEqual(before.requirements.map((item) => item.services));
+ await expect(
+ repository.updateBindings(datasetId, {
+ environmentBindings: { [environmentId]: { calendar: connector, notion: connector } },
+ }),
+ ).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ await db.update(agentEvalDatasets).set({ userId }).where(eq(agentEvalDatasets.id, datasetId));
+ await db
+ .update(agentEvalTestCases)
+ .set({ userId })
+ .where(eq(agentEvalTestCases.datasetId, datasetId));
+ await expect(
+ repository.updateBindings(datasetId, {
+ environmentBindings: { [environmentId]: { calendar: connector, notion: connector } },
+ }),
+ ).rejects.toThrow('unavailable');
+ });
+
+ it('repairs Environment bindings while preserving case content and release identity', async () => {
+ const { datasetId } = await importPackage();
+ const before = await repository.getBindings(datasetId);
+ expect(before.requirements.map((item) => [item.scope, item.services])).toEqual([
+ ['environment', ['calendar', 'notion']],
+ ]);
+ const environment = before.requirements[0];
+ await repository.updateBindings(datasetId, {
+ environmentBindings: { [environment.key]: { calendar: connector, notion: connector } },
+ });
+ const result = await repository.getBindings(datasetId);
+ expect(result.requirements[0].bindings).toEqual({ calendar: connector, notion: connector });
+ const [dataset] = await db
+ .select()
+ .from(agentEvalDatasets)
+ .where(eq(agentEvalDatasets.id, datasetId));
+ expect(dataset.metadata?.release).toBe('stable-release');
+ const [storedEnvironment] = await db
+ .select()
+ .from(agentEvalEnvironments)
+ .where(eq(agentEvalEnvironments.id, environment.key));
+ expect(storedEnvironment.config.memory).toEqual({});
+ const cases = await db
+ .select()
+ .from(agentEvalTestCases)
+ .where(eq(agentEvalTestCases.datasetId, datasetId));
+ expect(cases.find((item) => item.content.input === 'Two')?.content.environment).toEqual({
+ mock: { services: ['notion'] },
+ });
+ });
+
+ it('refuses a binding chosen for a case: connections belong to the Environment', async () => {
+ const { datasetId } = await importPackage();
+ const [testCase] = await db
+ .select()
+ .from(agentEvalTestCases)
+ .where(eq(agentEvalTestCases.datasetId, datasetId));
+ await expect(
+ repository.updateBindings(datasetId, {
+ caseBindings: { [testCase.id]: { notion: connector } },
+ }),
+ ).rejects.toThrow('belong to an Environment');
+ });
+
+ it('rejects another account and unknown targets without partially updating valid targets', async () => {
+ const { datasetId } = await importPackage();
+ const foreign = new AgentEvalDatasetConnectorRepo(db, otherId);
+ await expect(foreign.getBindings(datasetId)).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ await expect(foreign.updateBindings(datasetId, {})).rejects.toBeInstanceOf(
+ AgentEvalDatasetWriteError,
+ );
+ const { requirements } = await repository.getBindings(datasetId);
+ await expect(
+ repository.updateBindings(datasetId, {
+ environmentBindings: {
+ [requirements[0].key]: { calendar: connector, notion: connector },
+ unknown: { notion: connector },
+ },
+ }),
+ ).rejects.toThrow('unavailable');
+ expect((await repository.getBindings(datasetId)).requirements[0].bindings).toEqual({});
+ });
+
+ it('refuses to change an environment also used by a different dataset', async () => {
+ const first = await importPackage();
+ const second = await importPackage();
+ const { requirements } = await repository.getBindings(first.datasetId);
+ await db
+ .update(agentEvalTestCases)
+ .set({ environmentId: requirements[0].key })
+ .where(eq(agentEvalTestCases.datasetId, second.datasetId));
+ await expect(
+ repository.updateBindings(first.datasetId, {
+ environmentBindings: { [requirements[0].key]: { calendar: connector, notion: connector } },
+ }),
+ ).rejects.toThrow('shared with another dataset');
+ expect((await repository.getBindings(first.datasetId)).requirements[0].bindings).toEqual({});
+ });
+
+ it('allows repair when the other Dataset only has retired references to the environment', async () => {
+ const first = await importPackage();
+ const second = await importPackage();
+ const { requirements } = await repository.getBindings(first.datasetId);
+ await db
+ .update(agentEvalTestCases)
+ .set({ environmentId: requirements[0].key, metadata: { retired: true } })
+ .where(eq(agentEvalTestCases.datasetId, second.datasetId));
+ await repository.updateBindings(first.datasetId, {
+ environmentBindings: { [requirements[0].key]: { calendar: connector, notion: connector } },
+ });
+ expect((await repository.getBindings(first.datasetId)).requirements[0].bindings).toEqual({
+ calendar: connector,
+ notion: connector,
+ });
+ });
+
+ it('rebinds an Environment to a connection stored in it', async () => {
+ const input = pack();
+ input.connections = {
+ calendar: { name: 'Calendar', url: 'https://mock.test/mcp/a/calendar' },
+ notion: { name: 'Notion', url: 'https://mock.test/mcp/a/notion' },
+ };
+ input.environments[0].connectionBindings = {
+ calendar: { connectionKey: 'calendar', transport: 'lobe-bench' },
+ notion: { connectionKey: 'notion', transport: 'lobe-bench' },
+ };
+ const { datasetId } = await packageRepo.importPackage({
+ package: input,
+ sha256: 'd'.repeat(64),
+ });
+ const [requirement] = (await repository.getBindings(datasetId)).requirements;
+ expect(requirement.bindings.notion.connectorId).toBe(`env:${requirement.key}:notion`);
+ await repository.updateBindings(datasetId, {
+ environmentBindings: { [requirement.key]: requirement.bindings },
+ });
+ expect((await repository.getBindings(datasetId)).requirements[0].bindings).toEqual(
+ requirement.bindings,
+ );
+ });
+});
diff --git a/packages/database/src/repositories/agentEvalDatasetPackage/__tests__/index.test.ts b/packages/database/src/repositories/agentEvalDatasetPackage/__tests__/index.test.ts
new file mode 100644
index 00000000000..8e052a52e76
--- /dev/null
+++ b/packages/database/src/repositories/agentEvalDatasetPackage/__tests__/index.test.ts
@@ -0,0 +1,350 @@
+import type { AgentEvalDatasetPackage } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { AgentEvalDatasetWriteError } from '../../../models/agentEval/datasetAccess';
+import {
+ agentEvalBenchmarks,
+ agentEvalDatasets,
+ agentEvalEnvironments,
+ agentEvalRuns,
+ agentEvalTestCases,
+ userConnectors,
+ users,
+ workspaces,
+} from '../../../schemas';
+import { AgentEvalDatasetPackageImportError, AgentEvalDatasetPackageRepo } from '../index';
+
+const db = await getTestDB();
+const userId = 'package-owner';
+const otherId = 'package-other';
+const workspaceId = 'package-workspace';
+const repo = new AgentEvalDatasetPackageRepo(db, userId);
+const encryptionKey = await crypto.subtle.generateKey({ length: 256, name: 'AES-GCM' }, false, [
+ 'encrypt',
+]);
+const secureRepo = new AgentEvalDatasetPackageRepo(db, userId, undefined, {
+ encrypt: async (plaintext) => {
+ const iv = crypto.getRandomValues(new Uint8Array(12));
+ const ciphertext = await crypto.subtle.encrypt(
+ { iv, name: 'AES-GCM' },
+ encryptionKey,
+ new TextEncoder().encode(plaintext),
+ );
+ return Buffer.from(ciphertext).toString('base64');
+ },
+});
+const pack = (): AgentEvalDatasetPackage => ({
+ cases: [
+ {
+ key: 'one',
+ content: { input: 'Repeat hello', messages: [{ role: 'user', content: 'hello' }] },
+ environmentKey: 'world',
+ evalMode: 'equals',
+ evalConfig: { expected: 'hello' },
+ },
+ ],
+ dataset: { name: 'Synthetic package', evalMode: 'equals' },
+ environments: [{ key: 'world', name: 'Synthetic environment', config: { memory: {} } }],
+ format: 'lobehub-eval-dataset',
+ version: 1,
+});
+const params = () => ({ package: pack(), sha256: 'a'.repeat(64) });
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: userId }, { id: otherId }]);
+ await db
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'Shared', primaryOwnerId: userId, slug: workspaceId });
+});
+afterEach(async () => {
+ await db.delete(agentEvalRuns);
+ await db.delete(agentEvalTestCases);
+ await db.delete(agentEvalDatasets);
+ await db.delete(agentEvalEnvironments);
+ await db.delete(agentEvalBenchmarks);
+ await db.delete(userConnectors);
+ await db.delete(workspaces);
+ await db.delete(users);
+});
+
+describe('dataset package import transaction', () => {
+ it('stores an Environment-only connection, encrypted, in that Environment instead of a connector row', async () => {
+ const input = params();
+ input.package.connections = {
+ private: {
+ credentials: { token: 'synthetic-private-token', type: 'bearer' },
+ name: 'Private mock',
+ url: 'https://private.example/mcp',
+ },
+ unused: { name: 'Unused', url: 'https://unused.example/mcp' },
+ };
+ input.package.environments[0].connectionBindings = {
+ notion: { connectionKey: 'private', transport: 'lobe-bench' },
+ };
+ await secureRepo.importPackage(input);
+ await secureRepo.importPackage(input);
+ expect(await db.select().from(userConnectors)).toHaveLength(0);
+ const environments = await db.select().from(agentEvalEnvironments);
+ expect(environments).toHaveLength(2);
+ expect(environments[0].id).not.toBe(environments[1].id);
+ for (const environment of environments) {
+ expect(environment.config.mock?.services).toEqual(['notion']);
+ expect(environment.config.connectorBindings?.notion).toEqual({
+ connectorId: `env:${environment.id}:notion`,
+ transport: 'lobe-bench',
+ });
+ const stored = environment.config.connections?.notion;
+ expect(stored).toMatchObject({ name: 'Private mock', url: 'https://private.example/mcp' });
+ expect(stored?.credentials).toBeTruthy();
+ expect(stored?.credentials).not.toContain('synthetic-private-token');
+ }
+ const storedContent = JSON.stringify({
+ cases: await db.select().from(agentEvalTestCases),
+ datasets: await db.select().from(agentEvalDatasets),
+ environments,
+ });
+ expect(storedContent).not.toContain('synthetic-private-token');
+ expect(storedContent).not.toContain('unused.example');
+ });
+
+ it('refuses a package where a case binds its own connection', async () => {
+ const input = params();
+ input.package.connections = {
+ direct: { name: 'Direct mock', url: 'https://direct.example/mcp' },
+ };
+ input.package.cases[0].connectionBindings = { notion: { connectionKey: 'direct' } };
+ await expect(secureRepo.importPackage(input)).rejects.toThrow('belong to an Environment');
+ expect(await db.select().from(agentEvalDatasets)).toHaveLength(0);
+ });
+
+ it('rolls back provisioned connections together with a failed dataset import', async () => {
+ const input = params();
+ input.package.connections = {
+ private: { name: 'Private', url: 'https://private.example/mcp' },
+ };
+ input.package.environments[0].connectionBindings = { notion: { connectionKey: 'private' } };
+ input.package.cases[0].environmentKey = 'missing';
+ await expect(secureRepo.importPackage(input)).rejects.toBeInstanceOf(
+ AgentEvalDatasetPackageImportError,
+ );
+ for (const table of [
+ userConnectors,
+ agentEvalBenchmarks,
+ agentEvalDatasets,
+ agentEvalEnvironments,
+ agentEvalTestCases,
+ ]) {
+ expect(await db.select().from(table)).toHaveLength(0);
+ }
+ });
+
+ it('refuses credential imports when encrypted storage cannot be initialized', async () => {
+ const input = params();
+ input.package.connections = {
+ private: {
+ credentials: { token: 'synthetic-private-token', type: 'bearer' },
+ name: 'Private',
+ url: 'https://private.example/mcp',
+ },
+ };
+ input.package.environments[0].connectionBindings = { notion: { connectionKey: 'private' } };
+ await expect(repo.importPackage(input)).rejects.toThrow(
+ 'Secure connection storage is unavailable',
+ );
+ expect(await db.select().from(userConnectors)).toHaveLength(0);
+ expect(await db.select().from(agentEvalDatasets)).toHaveLength(0);
+ });
+ it('shares one environment across every case referencing the same package key', async () => {
+ const shared = params();
+ shared.package.cases.push({ ...shared.package.cases[0], key: 'two' });
+ await repo.importPackage(shared);
+ const environments = await db.select().from(agentEvalEnvironments);
+ const cases = await db.select().from(agentEvalTestCases);
+ expect(environments).toHaveLength(1);
+ expect(cases).toHaveLength(2);
+ expect(cases.every((testCase) => testCase.environmentId === environments[0].id)).toBe(true);
+ });
+ it('imports a dataset of its own, in no benchmark, with fresh environments on every import', async () => {
+ const first = await repo.importPackage(params());
+ const second = await repo.importPackage(params());
+ expect(first.datasetId).not.toBe(second.datasetId);
+ expect(first.benchmarkId).toBeNull();
+ expect(await db.select().from(agentEvalBenchmarks)).toHaveLength(0);
+ const datasets = await db.select().from(agentEvalDatasets);
+ expect(datasets.map((dataset) => dataset.benchmarkId)).toEqual([null, null]);
+ const cases = await db.select().from(agentEvalTestCases);
+ expect(cases).toHaveLength(2);
+ expect(cases[0].environmentId).not.toBe(cases[1].environmentId);
+ expect(cases[0]).toMatchObject({
+ userId,
+ content: pack().cases[0].content,
+ evalConfig: { expected: 'hello' },
+ metadata: { caseId: 'one' },
+ });
+ const [environment] = await db
+ .select()
+ .from(agentEvalEnvironments)
+ .where(eq(agentEvalEnvironments.id, cases[0].environmentId!));
+ expect(environment).toMatchObject({
+ userId,
+ config: { memory: {} },
+ metadata: { packageKey: 'world' },
+ });
+ const [dataset] = await db
+ .select()
+ .from(agentEvalDatasets)
+ .where(eq(agentEvalDatasets.id, first.datasetId));
+ expect(dataset).toMatchObject({
+ userId,
+ metadata: { custom: true, kind: 'lobe-bench', importedPackage: { sha256: params().sha256 } },
+ });
+ });
+
+ it('rolls back the new benchmark, dataset and environments when a case cannot be linked', async () => {
+ const invalid = params();
+ invalid.package.cases[0].environmentKey = 'missing';
+ await expect(repo.importPackage(invalid)).rejects.toBeInstanceOf(
+ AgentEvalDatasetPackageImportError,
+ );
+ for (const table of [
+ agentEvalBenchmarks,
+ agentEvalDatasets,
+ agentEvalEnvironments,
+ agentEvalTestCases,
+ ]) {
+ expect(await db.select().from(table)).toEqual([]);
+ }
+ });
+
+ it('rejects foreign, system, workspace and non-LobeBench personal benchmarks', async () => {
+ const rows = await db
+ .insert(agentEvalBenchmarks)
+ .values([
+ {
+ name: 'Foreign',
+ identifier: 'foreign',
+ userId: otherId,
+ rubrics: [],
+ metadata: { kind: 'lobe-bench' },
+ },
+ {
+ name: 'System',
+ identifier: 'system',
+ userId: null,
+ isSystem: true,
+ rubrics: [],
+ metadata: { kind: 'lobe-bench' },
+ },
+ {
+ name: 'Workspace',
+ identifier: 'workspace',
+ userId,
+ workspaceId,
+ rubrics: [],
+ metadata: { kind: 'lobe-bench' },
+ },
+ { name: 'Ordinary', identifier: 'ordinary', userId, rubrics: [] },
+ ])
+ .returning();
+ for (const row of rows)
+ await expect(repo.importPackage({ ...params(), benchmarkId: row.id })).rejects.toBeInstanceOf(
+ AgentEvalDatasetWriteError,
+ );
+ expect(await db.select().from(agentEvalDatasets)).toEqual([]);
+ });
+
+ it('imports into a collaborator benchmark only in the current workspace', async () => {
+ const [benchmark] = await db
+ .insert(agentEvalBenchmarks)
+ .values({
+ name: 'Shared',
+ identifier: 'shared',
+ userId: otherId,
+ workspaceId,
+ isSystem: false,
+ rubrics: [],
+ metadata: { kind: 'lobe-bench' },
+ })
+ .returning();
+ const result = await new AgentEvalDatasetPackageRepo(db, userId, workspaceId).importPackage({
+ ...params(),
+ benchmarkId: benchmark.id,
+ });
+ const [dataset] = await db
+ .select()
+ .from(agentEvalDatasets)
+ .where(eq(agentEvalDatasets.id, result.datasetId));
+ expect(dataset).toMatchObject({ userId, workspaceId, benchmarkId: benchmark.id });
+ expect((await db.select().from(agentEvalEnvironments))[0]).toMatchObject({
+ userId,
+ workspaceId,
+ });
+ });
+
+ it('accepts an empty ordinary dataset without changing its identity or turning it into LobeBench', async () => {
+ const [dataset] = await db
+ .insert(agentEvalDatasets)
+ .values({
+ name: 'Existing name',
+ identifier: 'ordinary',
+ userId,
+ metadata: { customLabel: 'keep' },
+ })
+ .returning();
+ const result = await repo.importPackage({ ...params(), datasetId: dataset.id });
+ const [updated] = await db
+ .select()
+ .from(agentEvalDatasets)
+ .where(eq(agentEvalDatasets.id, dataset.id));
+ expect(result.datasetId).toBe(dataset.id);
+ expect(updated.name).toBe('Existing name');
+ expect(updated.metadata).toMatchObject({ customLabel: 'keep' });
+ expect(updated.metadata?.kind).toBeUndefined();
+ expect(await db.select().from(agentEvalBenchmarks)).toEqual([]);
+ });
+
+ it('rejects foreign, system, missing and cross-workspace datasets', async () => {
+ const rows = await db
+ .insert(agentEvalDatasets)
+ .values([
+ { name: 'Foreign', identifier: 'foreign', userId: otherId },
+ { name: 'System', identifier: 'system', userId: null },
+ { name: 'Workspace', identifier: 'workspace', userId, workspaceId },
+ ])
+ .returning();
+ for (const id of [...rows.map((row) => row.id), 'missing'])
+ await expect(repo.importPackage({ ...params(), datasetId: id })).rejects.toBeInstanceOf(
+ AgentEvalDatasetWriteError,
+ );
+ expect(await db.select().from(agentEvalTestCases)).toEqual([]);
+ });
+
+ it('preserves existing cases including retired ones instead of replacing them', async () => {
+ const imported = await repo.importPackage(params());
+ await db.update(agentEvalTestCases).set({ metadata: { retired: true } });
+ const before = await db.select().from(agentEvalTestCases);
+ await expect(
+ repo.importPackage({ ...params(), datasetId: imported.datasetId }),
+ ).rejects.toBeInstanceOf(AgentEvalDatasetPackageImportError);
+ expect(await db.select().from(agentEvalTestCases)).toEqual(before);
+ expect(await db.select().from(agentEvalEnvironments)).toHaveLength(1);
+ });
+
+ it('refuses an empty dataset with historical runs without changing the run or dataset', async () => {
+ const [dataset] = await db
+ .insert(agentEvalDatasets)
+ .values({ name: 'Historical', identifier: 'history', userId })
+ .returning();
+ await db
+ .insert(agentEvalRuns)
+ .values({ datasetId: dataset.id, userId, name: 'Historical run' });
+ const before = await db.select().from(agentEvalRuns);
+ await expect(repo.importPackage({ ...params(), datasetId: dataset.id })).rejects.toBeInstanceOf(
+ AgentEvalDatasetPackageImportError,
+ );
+ expect(await db.select().from(agentEvalRuns)).toEqual(before);
+ expect(await db.select().from(agentEvalDatasets)).toEqual([dataset]);
+ });
+});
diff --git a/packages/database/src/repositories/agentEvalDatasetPackage/bindings.test.ts b/packages/database/src/repositories/agentEvalDatasetPackage/bindings.test.ts
new file mode 100644
index 00000000000..afd364978f6
--- /dev/null
+++ b/packages/database/src/repositories/agentEvalDatasetPackage/bindings.test.ts
@@ -0,0 +1,93 @@
+import type { AgentEvalDatasetPackage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { bindDatasetPackage, getPackageConnectionRequirements } from './bindings';
+
+const connection = { connectorId: 'b34a8f4d-349a-41a9-b307-3a8754e8e5a8' };
+const pack = (): AgentEvalDatasetPackage => ({
+ cases: [
+ { content: { input: 'Read a page' }, environmentKey: 'shared', key: 'one' },
+ {
+ content: { environment: { mock: { services: ['notion'] } }, input: 'Schedule a meeting' },
+ environmentKey: 'shared',
+ key: 'two',
+ },
+ ],
+ dataset: { evalMode: 'equals', name: 'Synthetic connection package' },
+ environments: [
+ { config: { mock: { services: ['notion', 'calendar'] } }, key: 'shared', name: 'Shared mock' },
+ ],
+ format: 'lobehub-eval-dataset',
+ version: 1,
+});
+
+describe('dataset connection bindings', () => {
+ it('imports unbound Environment requirements so connections can be configured after import', () => {
+ const original = pack();
+ expect(bindDatasetPackage(original)).toEqual(original);
+ expect(getPackageConnectionRequirements(original)).toEqual([
+ {
+ key: 'shared',
+ name: 'Shared mock',
+ providedServices: [],
+ scope: 'environment',
+ services: ['calendar', 'notion'],
+ },
+ ]);
+ });
+
+ it('attaches an Environment selection and leaves the cases’ own settings unchanged', () => {
+ const original = pack();
+ const bound = bindDatasetPackage(original, {
+ environmentBindings: { shared: { calendar: connection, notion: connection } },
+ });
+ expect(bound.environments[0].config).toEqual({
+ connectorBindings: { calendar: connection, notion: connection },
+ mock: { services: ['notion', 'calendar'] },
+ });
+ expect(bound.cases).toEqual(original.cases);
+ expect(original.environments[0].config).not.toHaveProperty('connectorBindings');
+ });
+
+ it('stores package connections in the Environment that uses them', () => {
+ const input = pack();
+ input.connections = { mock: { name: 'Mock', url: 'https://mock.test/mcp/a/notion' } };
+ input.environments[0].connectionBindings = {
+ notion: { connectionKey: 'mock', transport: 'lobe-bench' },
+ };
+ const stored = { credentials: 'sealed', name: 'Mock', url: 'https://mock.test/mcp/a/notion' };
+ const bound = bindDatasetPackage(input, undefined, {
+ connections: new Map([['mock', stored]]),
+ environmentIds: new Map([['shared', 'envShared']]),
+ });
+ expect(bound.environments[0].config.connections).toEqual({ notion: stored });
+ expect(bound.environments[0].config.connectorBindings).toEqual({
+ notion: { connectorId: 'env:envShared:notion', transport: 'lobe-bench' },
+ });
+ });
+
+ it('rejects missing or additional aliases, unknown Environments and any case selection', () => {
+ for (const selected of [
+ { environmentBindings: { shared: { notion: connection } } },
+ {
+ environmentBindings: {
+ shared: { calendar: connection, files: connection, notion: connection },
+ },
+ },
+ { environmentBindings: { unknown: { notion: connection } } },
+ { caseBindings: { two: { notion: connection } } },
+ ])
+ expect(() => bindDatasetPackage(pack(), selected)).toThrow();
+ });
+
+ it('refuses a case that binds its own connection or uses a service its Environment lacks', () => {
+ const ownBinding = pack();
+ ownBinding.connections = { mock: { name: 'Mock', url: 'https://mock.test/mcp/a/notion' } };
+ ownBinding.cases[1].connectionBindings = { notion: { connectionKey: 'mock' } };
+ expect(() => bindDatasetPackage(ownBinding)).toThrow('belong to an Environment');
+
+ const extraService = pack();
+ extraService.cases[1].content.environment = { toolForwarding: { files: {} } };
+ expect(() => bindDatasetPackage(extraService)).toThrow('its Environment provides');
+ });
+});
diff --git a/packages/database/src/repositories/agentEvalDatasetPackage/bindings.ts b/packages/database/src/repositories/agentEvalDatasetPackage/bindings.ts
new file mode 100644
index 00000000000..d72ac97b305
--- /dev/null
+++ b/packages/database/src/repositories/agentEvalDatasetPackage/bindings.ts
@@ -0,0 +1,198 @@
+import type {
+ AgentEvalDatasetPackage,
+ AgentEvalDatasetPackageBindings,
+ AgentEvalDatasetPackageConnectionBindings,
+ AgentEvalDatasetPackageConnectionRequirement,
+ EvalCaseEnvironment,
+ EvalConnectorBindings,
+ EvalEnvironmentConnection,
+} from '@lobechat/types';
+import { environmentConnectionId } from '@lobechat/types';
+
+import { AgentEvalDatasetPackageImportError } from './errors';
+
+export const environmentMockServices = (environment?: EvalCaseEnvironment | null): string[] =>
+ [
+ ...new Set([
+ ...(environment?.mock?.services ?? []),
+ ...Object.keys(environment?.toolForwarding ?? {}),
+ ]),
+ ].sort();
+
+export const effectiveMockServices = (
+ shared?: EvalCaseEnvironment | null,
+ own?: EvalCaseEnvironment | null,
+): string[] =>
+ [
+ ...new Set([
+ ...(own?.mock?.services ?? shared?.mock?.services ?? []),
+ ...Object.keys(shared?.toolForwarding ?? {}),
+ ...Object.keys(own?.toolForwarding ?? {}),
+ ]),
+ ].sort();
+
+const withDeclaredServices = (
+ config: EvalCaseEnvironment | undefined,
+ references?: AgentEvalDatasetPackageConnectionBindings,
+ shared?: EvalCaseEnvironment,
+): EvalCaseEnvironment | undefined => {
+ if (!references || Object.keys(references).length === 0) return config;
+ return {
+ ...config,
+ mock: {
+ services: [
+ ...new Set([
+ ...(config?.mock?.services ?? shared?.mock?.services ?? []),
+ ...Object.keys(references),
+ ]),
+ ].sort(),
+ },
+ };
+};
+
+/**
+ * A connection belongs to an Environment, never to one case: a case only
+ * chooses which of its Environment's services it uses (`mock.services`).
+ */
+export const assertEnvironmentOnlyConnections = (pack: AgentEvalDatasetPackage) => {
+ const offered = new Map(
+ pack.environments.map((environment) => [
+ environment.key,
+ new Set([
+ ...environmentMockServices(environment.config),
+ ...Object.keys(environment.connectionBindings ?? {}),
+ ]),
+ ]),
+ );
+ for (const testCase of pack.cases) {
+ if (Object.keys(testCase.connectionBindings ?? {}).length > 0)
+ throw new AgentEvalDatasetPackageImportError(
+ 'Mock connections belong to an Environment. A case cannot bind its own; list the services it uses in its Environment instead.',
+ );
+ const services = environmentMockServices(testCase.content.environment);
+ if (services.length === 0) continue;
+ const available = testCase.environmentKey ? offered.get(testCase.environmentKey) : undefined;
+ if (!available || services.some((service) => !available.has(service)))
+ throw new AgentEvalDatasetPackageImportError(
+ 'A case can only use mock services its Environment provides.',
+ );
+ }
+};
+
+export const getPackageConnectionRequirements = (
+ pack: AgentEvalDatasetPackage,
+): AgentEvalDatasetPackageConnectionRequirement[] =>
+ pack.environments
+ .map((environment) => ({
+ key: environment.key,
+ name: environment.name,
+ providedServices: Object.keys(environment.connectionBindings ?? {}).sort(),
+ scope: 'environment' as const,
+ services: environmentMockServices(
+ withDeclaredServices(environment.config, environment.connectionBindings),
+ ),
+ }))
+ .filter((requirement) => requirement.services.length > 0);
+
+/** Supplied selections are complete; omitting a scope keeps embedded or unbound requirements. */
+export const assertCompleteConnectorBindings = (
+ services: string[],
+ bindings: EvalConnectorBindings,
+) => {
+ const aliases = Object.keys(bindings).sort();
+ if (
+ services.length !== aliases.length ||
+ services.some((service, index) => service !== aliases[index])
+ ) {
+ throw new AgentEvalDatasetPackageImportError(
+ 'Select one mock connection for every required service, without additional services',
+ );
+ }
+};
+
+export const validatePackageConnectionSelections = (
+ pack: AgentEvalDatasetPackage,
+ selections: AgentEvalDatasetPackageBindings = {},
+) => {
+ assertEnvironmentOnlyConnections(pack);
+ if (Object.keys(selections.caseBindings ?? {}).length > 0)
+ throw new AgentEvalDatasetPackageImportError(
+ 'Mock connections belong to an Environment. Choose them for the Environment, not for a case.',
+ );
+ const requirements = getPackageConnectionRequirements(pack);
+ for (const [key, bindings] of Object.entries(selections.environmentBindings ?? {})) {
+ const requirement = requirements.find((item) => item.key === key);
+ if (!requirement) {
+ throw new AgentEvalDatasetPackageImportError('The selected package environment is unknown');
+ }
+ assertCompleteConnectorBindings(requirement.services, bindings);
+ }
+};
+
+/** The package connections the import stores: those Environments it does not rebind use. */
+export const getReferencedPackageConnections = (
+ pack: AgentEvalDatasetPackage,
+ selections: AgentEvalDatasetPackageBindings = {},
+): string[] => [
+ ...new Set(
+ pack.environments.flatMap((environment) =>
+ Object.hasOwn(selections.environmentBindings ?? {}, environment.key)
+ ? []
+ : Object.values(environment.connectionBindings ?? {}).map(
+ (binding) => binding.connectionKey,
+ ),
+ ),
+ ),
+];
+
+/**
+ * Binds a package for import. Every package connection is stored, encrypted,
+ * in the Environment that uses it (`config.connections`) and bound by its
+ * `env:<environmentId>:<service>` id; an Environment the importer rebinds keeps
+ * the connections chosen for it. Cases keep their own settings unchanged.
+ */
+export const bindDatasetPackage = (
+ pack: AgentEvalDatasetPackage,
+ selections: AgentEvalDatasetPackageBindings = {},
+ inline?: {
+ /** The encrypted connections, by package connection key. */
+ connections: ReadonlyMap<string, EvalEnvironmentConnection>;
+ /** The id each Environment row will get, by package key. */
+ environmentIds: ReadonlyMap<string, string>;
+ },
+) => {
+ validatePackageConnectionSelections(pack, selections);
+ const environments = pack.environments.map((environment) => {
+ const config = withDeclaredServices(environment.config, environment.connectionBindings) ?? {};
+ if (Object.hasOwn(selections.environmentBindings ?? {}, environment.key)) {
+ const bindings = selections.environmentBindings![environment.key];
+ return {
+ ...environment,
+ config: { ...config, ...(Object.keys(bindings).length && { connectorBindings: bindings }) },
+ };
+ }
+ const environmentId = inline?.environmentIds.get(environment.key);
+ const references = Object.entries(environment.connectionBindings ?? {});
+ if (references.length === 0) return { ...environment, config };
+ if (!environmentId)
+ throw new AgentEvalDatasetPackageImportError('A package mock connection is unavailable');
+ const connections: Record<string, EvalEnvironmentConnection> = {};
+ const connectorBindings: EvalConnectorBindings = {};
+ for (const [alias, reference] of references) {
+ const connection = inline?.connections.get(reference.connectionKey);
+ if (!connection)
+ throw new AgentEvalDatasetPackageImportError('A package mock connection is unavailable');
+ connections[alias] = connection;
+ connectorBindings[alias] = {
+ connectorId: environmentConnectionId(environmentId, alias),
+ ...(reference.transport && { transport: reference.transport }),
+ };
+ }
+ return {
+ ...environment,
+ id: environmentId,
+ config: { ...config, connections, connectorBindings },
+ };
+ });
+ return { ...pack, environments };
+};
diff --git a/packages/database/src/repositories/agentEvalDatasetPackage/connections.ts b/packages/database/src/repositories/agentEvalDatasetPackage/connections.ts
new file mode 100644
index 00000000000..491f7eb252f
--- /dev/null
+++ b/packages/database/src/repositories/agentEvalDatasetPackage/connections.ts
@@ -0,0 +1,46 @@
+import type {
+ AgentEvalDatasetPackage,
+ AgentEvalDatasetPackageBindings,
+ EvalEnvironmentConnection,
+} from '@lobechat/types';
+
+import { getReferencedPackageConnections, validatePackageConnectionSelections } from './bindings';
+import { AgentEvalDatasetPackageImportError } from './errors';
+
+export interface EvalPackageCredentialEncryptor {
+ encrypt: (plaintext: string) => Promise<string>;
+}
+
+/**
+ * Encrypts the package connections the import stores in Environments, before
+ * entering the import transaction; no network and no plaintext persistence.
+ */
+export const preparePackageConnections = async (
+ pack: AgentEvalDatasetPackage,
+ selections: AgentEvalDatasetPackageBindings | undefined,
+ encryptor?: EvalPackageCredentialEncryptor,
+) => {
+ validatePackageConnectionSelections(pack, selections);
+ const connections = new Map<string, EvalEnvironmentConnection>();
+ for (const key of getReferencedPackageConnections(pack, selections)) {
+ const definition = Object.hasOwn(pack.connections ?? {}, key)
+ ? pack.connections?.[key]
+ : undefined;
+ if (!definition)
+ throw new AgentEvalDatasetPackageImportError('A package mock connection is missing');
+ let credentials: string | null = null;
+ if (definition.credentials) {
+ if (!encryptor)
+ throw new AgentEvalDatasetPackageImportError('Secure connection storage is unavailable');
+ try {
+ credentials = await encryptor.encrypt(JSON.stringify(definition.credentials));
+ } catch {
+ throw new AgentEvalDatasetPackageImportError(
+ 'Could not securely store the mock connection',
+ );
+ }
+ }
+ connections.set(key, { credentials, name: definition.name, url: definition.url });
+ }
+ return connections;
+};
diff --git a/packages/database/src/repositories/agentEvalDatasetPackage/datasetConnectorBindings.ts b/packages/database/src/repositories/agentEvalDatasetPackage/datasetConnectorBindings.ts
new file mode 100644
index 00000000000..06ea1865081
--- /dev/null
+++ b/packages/database/src/repositories/agentEvalDatasetPackage/datasetConnectorBindings.ts
@@ -0,0 +1,212 @@
+import type {
+ AgentEvalDatasetConnectorRequirement,
+ AgentEvalDatasetPackageBindings,
+} from '@lobechat/types';
+import { parseEnvironmentConnectionId } from '@lobechat/types';
+import { and, eq, inArray, isNotNull, isNull, ne, or, sql } from 'drizzle-orm';
+
+import {
+ AgentEvalDatasetWriteError,
+ assertWritableEvalDatasets,
+} from '../../models/agentEval/datasetAccess';
+import { activeEvalTestCases } from '../../models/agentEval/testCase';
+import {
+ agentEvalDatasets,
+ agentEvalEnvironments,
+ agentEvalTestCases,
+ userConnectors,
+} from '../../schemas';
+import type { LobeChatDatabase, Transaction } from '../../type';
+import { buildWorkspaceWhere, normalizeWorkspaceId } from '../../utils/workspace';
+import { AgentEvalEnvironmentConnectionRepo } from '../agentEvalEnvironmentConnection';
+import { assertCompleteConnectorBindings, environmentMockServices } from './bindings';
+import { AgentEvalDatasetPackageImportError } from './errors';
+
+/** Connection repair changes local bindings only, preserving dataset content and release identity. */
+export class AgentEvalDatasetConnectorRepo {
+ private readonly scope: { userId: string; workspaceId?: string };
+
+ constructor(
+ private readonly db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+ ) {
+ this.scope = { userId, workspaceId: normalizeWorkspaceId(workspaceId) ?? undefined };
+ }
+
+ private read = async (
+ db: LobeChatDatabase | Transaction,
+ datasetId: string,
+ includeSystem = false,
+ lockEnvironments = false,
+ ) => {
+ const [dataset] = await db
+ .select({ id: agentEvalDatasets.id })
+ .from(agentEvalDatasets)
+ .where(
+ and(
+ eq(agentEvalDatasets.id, datasetId),
+ includeSystem
+ ? or(
+ buildWorkspaceWhere(this.scope, agentEvalDatasets),
+ isNull(agentEvalDatasets.userId),
+ )
+ : and(
+ buildWorkspaceWhere(this.scope, agentEvalDatasets),
+ isNotNull(agentEvalDatasets.userId),
+ ),
+ ),
+ )
+ .limit(1);
+ if (!dataset) throw new AgentEvalDatasetWriteError();
+ const cases = await db
+ .select()
+ .from(agentEvalTestCases)
+ .where(
+ and(
+ eq(agentEvalTestCases.datasetId, datasetId),
+ includeSystem
+ ? or(
+ buildWorkspaceWhere(this.scope, agentEvalTestCases),
+ isNull(agentEvalTestCases.userId),
+ )
+ : and(
+ buildWorkspaceWhere(this.scope, agentEvalTestCases),
+ isNotNull(agentEvalTestCases.userId),
+ ),
+ activeEvalTestCases(),
+ ),
+ );
+ const ids = [
+ ...new Set(
+ cases.flatMap((testCase) => (testCase.environmentId ? [testCase.environmentId] : [])),
+ ),
+ ];
+ const environmentQuery = db
+ .select()
+ .from(agentEvalEnvironments)
+ .where(
+ and(
+ inArray(agentEvalEnvironments.id, ids),
+ includeSystem
+ ? or(
+ buildWorkspaceWhere(this.scope, agentEvalEnvironments),
+ isNull(agentEvalEnvironments.userId),
+ )
+ : and(
+ buildWorkspaceWhere(this.scope, agentEvalEnvironments),
+ isNotNull(agentEvalEnvironments.userId),
+ ),
+ ),
+ )
+ .orderBy(agentEvalEnvironments.id);
+ const environments = ids.length
+ ? await (lockEnvironments ? environmentQuery.for('update') : environmentQuery)
+ : [];
+ return { cases, environments };
+ };
+
+ /** Connections are chosen per Environment; a case only picks which of its services it uses. */
+ private requirements = (
+ rows: Awaited<ReturnType<AgentEvalDatasetConnectorRepo['read']>>,
+ ): AgentEvalDatasetConnectorRequirement[] =>
+ rows.environments
+ .map((environment) => ({
+ bindings: environment.config.connectorBindings ?? {},
+ key: environment.id,
+ name: environment.name,
+ scope: 'environment' as const,
+ services: environmentMockServices(environment.config),
+ }))
+ .filter((requirement) => requirement.services.length > 0);
+
+ getBindings = async (datasetId: string) => ({
+ requirements: this.requirements(await this.read(this.db, datasetId, true)),
+ });
+
+ updateBindings = async (datasetId: string, selections: AgentEvalDatasetPackageBindings) =>
+ this.db.transaction(async (tx) => {
+ await assertWritableEvalDatasets(tx, this.scope, [datasetId]);
+ // Serialize binding with case assignment before checking cross-Dataset references.
+ const rows = await this.read(tx, datasetId, false, true);
+ const requirements = this.requirements(rows);
+ if (Object.keys(selections.caseBindings ?? {}).length > 0)
+ throw new AgentEvalDatasetPackageImportError(
+ 'Mock connections belong to an Environment. Choose them for the Environment, not for a case.',
+ );
+ for (const [scope, selected] of [['environment', selections.environmentBindings]] as const)
+ for (const [id, bindings] of Object.entries(selected ?? {})) {
+ const requirement = requirements.find((item) => item.scope === scope && item.key === id);
+ if (!requirement)
+ throw new AgentEvalDatasetPackageImportError(
+ 'The selected dataset environment or case is unavailable',
+ );
+ assertCompleteConnectorBindings(requirement.services, bindings);
+ if (scope === 'environment') {
+ const [otherReference] = await tx
+ .select({ id: agentEvalTestCases.id })
+ .from(agentEvalTestCases)
+ .where(
+ and(
+ eq(agentEvalTestCases.environmentId, id),
+ ne(agentEvalTestCases.datasetId, datasetId),
+ activeEvalTestCases(),
+ ),
+ )
+ .limit(1);
+ if (otherReference)
+ throw new AgentEvalDatasetPackageImportError(
+ 'This environment is shared with another dataset. Copy the environment before changing its connections.',
+ );
+ }
+ }
+ const connectionIds = [
+ ...new Set(
+ Object.values(selections.environmentBindings ?? {}).flatMap((bindings) =>
+ Object.values(bindings).map((binding) => binding.connectorId),
+ ),
+ ),
+ ];
+ // Connections stored in this Dataset's Environments are named by `env:` ids.
+ const storedIds = connectionIds.filter((id) => parseEnvironmentConnectionId(id));
+ const rowIds = connectionIds.filter((id) => !parseEnvironmentConnectionId(id));
+ const stored = new AgentEvalEnvironmentConnectionRepo(
+ this.db,
+ this.scope.userId,
+ this.scope.workspaceId,
+ );
+ for (const id of storedIds)
+ if (!(await stored.find(datasetId, id, tx as unknown as LobeChatDatabase)))
+ throw new AgentEvalDatasetPackageImportError(
+ 'A connection is unavailable or belongs to another Dataset',
+ );
+ if (rowIds.length) {
+ const connections = await tx
+ .select({ id: userConnectors.id })
+ .from(userConnectors)
+ .where(
+ and(
+ inArray(userConnectors.id, rowIds),
+ buildWorkspaceWhere(this.scope, userConnectors),
+ sql`${userConnectors.metadata} -> 'agentEval' ->> 'datasetId' = ${datasetId}`,
+ ),
+ );
+ if (connections.length !== rowIds.length)
+ throw new AgentEvalDatasetPackageImportError(
+ 'A connection is unavailable or belongs to another Dataset',
+ );
+ }
+ for (const environment of rows.environments) {
+ const bindings = selections.environmentBindings?.[environment.id];
+ if (!bindings) continue;
+ await tx
+ .update(agentEvalEnvironments)
+ .set({
+ config: { ...environment.config, connectorBindings: bindings },
+ updatedAt: new Date(),
+ })
+ .where(eq(agentEvalEnvironments.id, environment.id));
+ }
+ return { success: true as const };
+ });
+}
diff --git a/packages/database/src/repositories/agentEvalDatasetPackage/errors.ts b/packages/database/src/repositories/agentEvalDatasetPackage/errors.ts
new file mode 100644
index 00000000000..9a1f5763f35
--- /dev/null
+++ b/packages/database/src/repositories/agentEvalDatasetPackage/errors.ts
@@ -0,0 +1 @@
+export class AgentEvalDatasetPackageImportError extends Error {}
diff --git a/packages/database/src/repositories/agentEvalDatasetPackage/index.ts b/packages/database/src/repositories/agentEvalDatasetPackage/index.ts
new file mode 100644
index 00000000000..90d1115ad7c
--- /dev/null
+++ b/packages/database/src/repositories/agentEvalDatasetPackage/index.ts
@@ -0,0 +1,197 @@
+import type { AgentEvalDatasetPackage, AgentEvalDatasetPackageBindings } from '@lobechat/types';
+import { and, eq, isNotNull } from 'drizzle-orm';
+
+import {
+ AgentEvalDatasetWriteError,
+ assertWritableEvalDatasets,
+ isFixedLobeBenchDataset,
+} from '../../models/agentEval/datasetAccess';
+import {
+ agentEvalBenchmarks,
+ agentEvalDatasets,
+ agentEvalEnvironments,
+ agentEvalRuns,
+ agentEvalTestCases,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { buildWorkspaceWhere, normalizeWorkspaceId } from '../../utils/workspace';
+import { bindDatasetPackage } from './bindings';
+import { type EvalPackageCredentialEncryptor, preparePackageConnections } from './connections';
+import { AgentEvalDatasetPackageImportError } from './errors';
+
+export { AgentEvalDatasetPackageImportError } from './errors';
+
+/** Imports a complete package in one transaction, without mutating any existing cases or results. */
+export class AgentEvalDatasetPackageRepo {
+ private readonly workspaceId?: string;
+
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ workspaceId?: string,
+ private readonly credentialEncryptor?: EvalPackageCredentialEncryptor,
+ ) {
+ this.workspaceId = normalizeWorkspaceId(workspaceId) ?? undefined;
+ }
+
+ importPackage = async (params: {
+ benchmarkId?: string;
+ bindings?: AgentEvalDatasetPackageBindings;
+ datasetId?: string;
+ name?: string;
+ package: AgentEvalDatasetPackage;
+ sha256: string;
+ }) => {
+ const connections = await preparePackageConnections(
+ params.package,
+ params.bindings,
+ this.credentialEncryptor,
+ );
+ // Environment ids are fixed up front: a connection stored in an Environment
+ // is bound by an id that names that Environment.
+ const assignedEnvironmentIds = new Map(
+ params.package.environments.map((environment) => [environment.key, crypto.randomUUID()]),
+ );
+ const pack = bindDatasetPackage(params.package, params.bindings, {
+ connections,
+ environmentIds: assignedEnvironmentIds,
+ });
+ return this.db.transaction(async (tx) => {
+ const scope = { userId: this.userId, workspaceId: this.workspaceId };
+ const ownership = { userId: this.userId, workspaceId: this.workspaceId ?? null };
+ let benchmarkId: string | null = null;
+ let datasetId: string;
+ const source = {
+ format: pack.format,
+ sha256: params.sha256,
+ version: pack.version,
+ };
+ const metadata = {
+ ...pack.dataset.metadata,
+ importedPackage: source,
+ release: pack.dataset.metadata?.release ?? `sha256:${params.sha256}`,
+ };
+
+ if (params.datasetId) {
+ const [dataset] = await assertWritableEvalDatasets(tx, scope, [params.datasetId]);
+ const [existingCase] = await tx
+ .select({ id: agentEvalTestCases.id })
+ .from(agentEvalTestCases)
+ .where(eq(agentEvalTestCases.datasetId, dataset.id))
+ .limit(1);
+ const [existingRun] = await tx
+ .select({ id: agentEvalRuns.id })
+ .from(agentEvalRuns)
+ .where(eq(agentEvalRuns.datasetId, dataset.id))
+ .limit(1);
+ if (existingCase || existingRun) {
+ throw new AgentEvalDatasetPackageImportError(
+ 'Import a ZIP package into a new or empty dataset without runs. Existing cases and results are preserved.',
+ );
+ }
+ const fixed = await isFixedLobeBenchDataset(tx, dataset);
+ await tx
+ .update(agentEvalDatasets)
+ .set({
+ description: pack.dataset.description ?? dataset.description,
+ evalConfig: pack.dataset.evalConfig ?? dataset.evalConfig,
+ evalMode: pack.dataset.evalMode ?? dataset.evalMode,
+ metadata: {
+ ...dataset.metadata,
+ ...metadata,
+ ...(fixed && { custom: true, kind: 'lobe-bench' }),
+ },
+ name: params.name ?? dataset.name,
+ updatedAt: new Date(),
+ })
+ .where(eq(agentEvalDatasets.id, dataset.id));
+ datasetId = dataset.id;
+ benchmarkId = dataset.benchmarkId;
+ } else {
+ if (params.benchmarkId) {
+ const [benchmark] = await tx
+ .select()
+ .from(agentEvalBenchmarks)
+ .where(
+ and(
+ eq(agentEvalBenchmarks.id, params.benchmarkId),
+ buildWorkspaceWhere(scope, agentEvalBenchmarks),
+ isNotNull(agentEvalBenchmarks.userId),
+ eq(agentEvalBenchmarks.isSystem, false),
+ ),
+ )
+ .for('update');
+ if (!benchmark || benchmark.metadata?.kind !== 'lobe-bench') {
+ throw new AgentEvalDatasetWriteError(
+ 'Choose a LobeBench benchmark owned by your account or workspace',
+ );
+ }
+ benchmarkId = benchmark.id;
+ }
+ // Without a target an import only imports: a dataset in no benchmark. A
+ // benchmark is made separately, of datasets, with its judge and run rules.
+ const [dataset] = await tx
+ .insert(agentEvalDatasets)
+ .values({
+ ...ownership,
+ benchmarkId,
+ description: pack.dataset.description,
+ evalConfig: pack.dataset.evalConfig,
+ evalMode: pack.dataset.evalMode,
+ identifier: `import-${crypto.randomUUID()}`,
+ metadata: { ...metadata, custom: true, kind: 'lobe-bench' },
+ name: params.name ?? pack.dataset.name,
+ })
+ .returning({ id: agentEvalDatasets.id });
+ datasetId = dataset.id;
+ }
+
+ // Package keys are local references, never existing database IDs or unique identifiers.
+ const environments = pack.environments.length
+ ? await tx
+ .insert(agentEvalEnvironments)
+ .values(
+ pack.environments.map((environment) => ({
+ ...ownership,
+ config: environment.config,
+ id: assignedEnvironmentIds.get(environment.key)!,
+ description: environment.description,
+ metadata: { importedPackage: source, packageKey: environment.key },
+ name: environment.name,
+ })),
+ )
+ .returning({ id: agentEvalEnvironments.id, metadata: agentEvalEnvironments.metadata })
+ : [];
+ const environmentIds = new Map(
+ environments.map((environment) => [environment.metadata?.packageKey, environment.id]),
+ );
+ const cases = pack.cases.map((testCase, index) => {
+ const environmentId = testCase.environmentKey
+ ? environmentIds.get(testCase.environmentKey)
+ : undefined;
+ if (testCase.environmentKey && !environmentId) {
+ throw new AgentEvalDatasetPackageImportError(
+ 'The package references an unknown environment',
+ );
+ }
+ return {
+ ...ownership,
+ content: testCase.content,
+ datasetId,
+ environmentId,
+ evalConfig: testCase.evalConfig,
+ evalMode: testCase.evalMode,
+ metadata: {
+ ...testCase.metadata,
+ caseId: testCase.key,
+ importedPackage: source,
+ source: 'zip',
+ },
+ sortOrder: testCase.sortOrder ?? index + 1,
+ };
+ });
+ await tx.insert(agentEvalTestCases).values(cases);
+ return { benchmarkId, count: cases.length, datasetId, environmentCount: environments.length };
+ });
+ };
+}
diff --git a/packages/database/src/repositories/agentEvalEnvironmentConnection/index.test.ts b/packages/database/src/repositories/agentEvalEnvironmentConnection/index.test.ts
new file mode 100644
index 00000000000..40161c8f930
--- /dev/null
+++ b/packages/database/src/repositories/agentEvalEnvironmentConnection/index.test.ts
@@ -0,0 +1,142 @@
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { AgentEvalDatasetModel } from '../../models/agentEval/dataset';
+import { agentEvalDatasets, agentEvalEnvironments, agentEvalTestCases, users } from '../../schemas';
+import { AgentEvalDatasetDeletionRepo } from '../agentEvalDatasetDeletion';
+import { AgentEvalEnvironmentConnectionError, AgentEvalEnvironmentConnectionRepo } from './index';
+
+const db = await getTestDB();
+const userId = 'stored-connection-owner';
+const otherUserId = 'stored-connection-other';
+const datasets = new AgentEvalDatasetModel(db, userId);
+const repo = new AgentEvalEnvironmentConnectionRepo(db, userId);
+
+const manifest = {
+ api: [{ description: 'Read mail', name: 'read', parameters: { properties: {}, type: 'object' } }],
+ identifier: 'gmail',
+ meta: { title: 'Gmail' },
+ type: 'mcp',
+};
+
+/** An Environment holding a stored gmail connection, bound by its own `env:` id. */
+const createEnvironment = async (owner: string | null, id: string = crypto.randomUUID()) => {
+ await db.insert(agentEvalEnvironments).values({
+ config: {
+ connections: {
+ gmail: {
+ credentials: 'sealed:{"token":"t","type":"bearer"}',
+ name: 'Gmail',
+ url: 'https://mock.test/mcp/ds/gmail',
+ },
+ },
+ connectorBindings: { gmail: { connectorId: `env:${id}:gmail`, transport: 'lobe-bench' } },
+ mock: { services: ['gmail'] },
+ toolManifests: { gmail: manifest },
+ },
+ id,
+ name: 'Shared world',
+ userId: owner,
+ } as never);
+ return id;
+};
+
+const useEnvironment = (datasetId: string, environmentId: string, owner = userId) =>
+ db.insert(agentEvalTestCases).values({
+ content: { input: 'Check my mail' },
+ datasetId,
+ environmentId,
+ userId: owner,
+ });
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+afterEach(async () => {
+ await db.delete(agentEvalDatasets);
+ await db.delete(agentEvalEnvironments);
+ await db.delete(users);
+});
+
+describe('connections stored in Environments', () => {
+ it('reaches a stored connection only through a Dataset whose cases use its Environment', async () => {
+ const used = await datasets.create({ identifier: 'used', name: 'Used' });
+ const other = await datasets.create({ identifier: 'other', name: 'Other' });
+ const environmentId = await createEnvironment(userId);
+ await useEnvironment(used.id, environmentId);
+
+ const found = await repo.find(used.id, `env:${environmentId}:gmail`);
+ expect(found).toMatchObject({
+ connection: { url: 'https://mock.test/mcp/ds/gmail' },
+ environmentId,
+ mutable: true,
+ service: 'gmail',
+ toolManifest: manifest,
+ transport: 'lobe-bench',
+ });
+ expect(await repo.find(other.id, `env:${environmentId}:gmail`)).toBeUndefined();
+ expect(await repo.find(used.id, `env:${environmentId}:slack`)).toBeUndefined();
+ expect(await repo.listForDataset(used.id)).toHaveLength(1);
+ expect(await repo.listForDataset(other.id)).toHaveLength(0);
+ });
+
+ it('does not reach another account’s Environment', async () => {
+ const mine = await datasets.create({ identifier: 'mine', name: 'Mine' });
+ const environmentId = await createEnvironment(otherUserId);
+ await useEnvironment(mine.id, environmentId);
+ expect(await repo.find(mine.id, `env:${environmentId}:gmail`)).toBeUndefined();
+ });
+
+ it('changes the address and keeps the credentials unless new ones are given', async () => {
+ const dataset = await datasets.create({ identifier: 'edit', name: 'Edit' });
+ const environmentId = await createEnvironment(userId);
+ await useEnvironment(dataset.id, environmentId);
+
+ await repo.update(dataset.id, `env:${environmentId}:gmail`, {
+ url: 'https://moved.test/mcp/ds/gmail',
+ });
+ const [row] = await db
+ .select()
+ .from(agentEvalEnvironments)
+ .where(eq(agentEvalEnvironments.id, environmentId));
+ expect(row.config.connections?.gmail).toEqual({
+ credentials: 'sealed:{"token":"t","type":"bearer"}',
+ name: 'Gmail',
+ url: 'https://moved.test/mcp/ds/gmail',
+ });
+ });
+
+ it('refuses to change a built-in Environment or one another Dataset also uses', async () => {
+ const first = await datasets.create({ identifier: 'first', name: 'First' });
+ const second = await datasets.create({ identifier: 'second', name: 'Second' });
+ const builtIn = await createEnvironment(null);
+ await useEnvironment(first.id, builtIn);
+ await expect(
+ repo.update(first.id, `env:${builtIn}:gmail`, { url: 'https://x.test/mcp/a/gmail' }),
+ ).rejects.toBeInstanceOf(AgentEvalEnvironmentConnectionError);
+
+ const shared = await createEnvironment(userId);
+ await useEnvironment(first.id, shared);
+ await useEnvironment(second.id, shared);
+ await expect(
+ repo.update(first.id, `env:${shared}:gmail`, { url: 'https://x.test/mcp/a/gmail' }),
+ ).rejects.toThrow('shared with another dataset');
+ });
+
+ it('deletes an Environment holding stored connections with the last Dataset using it', async () => {
+ const deletion = new AgentEvalDatasetDeletionRepo(db, userId);
+ const first = await datasets.create({ identifier: 'first', name: 'First' });
+ const second = await datasets.create({ identifier: 'second', name: 'Second' });
+ const own = await createEnvironment(userId);
+ const shared = await createEnvironment(userId);
+ await useEnvironment(first.id, own);
+ await useEnvironment(first.id, shared);
+ await useEnvironment(second.id, shared);
+
+ await deletion.deleteDataset(first.id);
+ const remaining = (await db.select().from(agentEvalEnvironments)).map(({ id }) => id);
+ expect(remaining).not.toContain(own);
+ expect(remaining).toContain(shared);
+ });
+});
diff --git a/packages/database/src/repositories/agentEvalEnvironmentConnection/index.ts b/packages/database/src/repositories/agentEvalEnvironmentConnection/index.ts
new file mode 100644
index 00000000000..e95b73bfffe
--- /dev/null
+++ b/packages/database/src/repositories/agentEvalEnvironmentConnection/index.ts
@@ -0,0 +1,178 @@
+import type {
+ EvalCaseEnvironment,
+ EvalEnvironmentConnection,
+ EvalToolManifest,
+} from '@lobechat/types';
+import { environmentConnectionId, parseEnvironmentConnectionId } from '@lobechat/types';
+import { and, eq, inArray, isNull, ne, or } from 'drizzle-orm';
+
+import { agentEvalEnvironments, agentEvalTestCases } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { buildWorkspaceWhere, normalizeWorkspaceId } from '../../utils/workspace';
+
+export class AgentEvalEnvironmentConnectionError extends Error {}
+
+export interface StoredEnvironmentConnection {
+ connection: EvalEnvironmentConnection;
+ /** The `env:<environmentId>:<service>` id bindings use for it. */
+ connectorId: string;
+ environmentId: string;
+ /** Whether the account may change it (a built-in Environment is read-only). */
+ mutable: boolean;
+ service: string;
+ /** The frozen contract the Environment offers for this service. */
+ toolManifest?: EvalToolManifest;
+ transport?: 'mcp' | 'lobe-bench';
+}
+
+/**
+ * Mock connections stored in Environments (`config.connections`) instead of
+ * connector rows. A connection is reachable from a Dataset only through an
+ * Environment one of the Dataset's cases uses, and only when the Environment's
+ * own binding names it, so an id cannot be replayed against another Dataset.
+ */
+export class AgentEvalEnvironmentConnectionRepo {
+ private readonly scope: { userId: string; workspaceId?: string };
+
+ constructor(
+ private readonly db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+ ) {
+ this.scope = { userId, workspaceId: normalizeWorkspaceId(workspaceId) ?? undefined };
+ }
+
+ /** The account's own Environments and built-in ones (no owner). */
+ private readable = () =>
+ or(
+ buildWorkspaceWhere(this.scope, agentEvalEnvironments),
+ isNull(agentEvalEnvironments.userId),
+ );
+
+ private environmentsOfDataset = async (
+ datasetId: string,
+ environmentId?: string,
+ db: LobeChatDatabase = this.db,
+ ) => {
+ const used = db
+ .selectDistinct({ id: agentEvalTestCases.environmentId })
+ .from(agentEvalTestCases)
+ .where(
+ and(
+ eq(agentEvalTestCases.datasetId, datasetId),
+ environmentId ? eq(agentEvalTestCases.environmentId, environmentId) : undefined,
+ ),
+ );
+ return db
+ .select({
+ config: agentEvalEnvironments.config,
+ id: agentEvalEnvironments.id,
+ userId: agentEvalEnvironments.userId,
+ })
+ .from(agentEvalEnvironments)
+ .where(and(inArray(agentEvalEnvironments.id, used), this.readable()));
+ };
+
+ private stored = (environment: {
+ config: EvalCaseEnvironment;
+ id: string;
+ userId: string | null;
+ }): StoredEnvironmentConnection[] =>
+ Object.entries(environment.config.connections ?? {}).flatMap(([service, connection]) => {
+ const connectorId = environmentConnectionId(environment.id, service);
+ const binding = environment.config.connectorBindings?.[service];
+ if (binding?.connectorId !== connectorId) return [];
+ return [
+ {
+ connection,
+ connectorId,
+ environmentId: environment.id,
+ mutable: environment.userId !== null,
+ service,
+ ...(environment.config.toolManifests?.[service] && {
+ toolManifest: environment.config.toolManifests[service],
+ }),
+ ...(binding.transport && { transport: binding.transport }),
+ },
+ ];
+ });
+
+ /** The stored connection an `env:` id names, if this Dataset may use it. */
+ find = async (
+ datasetId: string,
+ connectorId: string,
+ db: LobeChatDatabase = this.db,
+ ): Promise<StoredEnvironmentConnection | undefined> => {
+ const parsed = parseEnvironmentConnectionId(connectorId);
+ if (!parsed) return;
+ const [environment] = await this.environmentsOfDataset(datasetId, parsed.environmentId, db);
+ return environment
+ ? this.stored(environment).find((item) => item.connectorId === connectorId)
+ : undefined;
+ };
+
+ /** Every stored connection the Dataset's cases can use. */
+ listForDataset = async (datasetId: string): Promise<StoredEnvironmentConnection[]> =>
+ (await this.environmentsOfDataset(datasetId)).flatMap(this.stored);
+
+ /**
+ * Changes a stored connection's address, name or encrypted credentials.
+ * `credentials: undefined` keeps them. Refused for a built-in Environment
+ * and for one another Dataset also uses.
+ */
+ update = async (
+ datasetId: string,
+ connectorId: string,
+ patch: { credentials?: string | null; name?: string; url: string },
+ ) =>
+ this.db.transaction(async (tx) => {
+ const current = await this.find(datasetId, connectorId, tx as unknown as LobeChatDatabase);
+ if (!current) throw new AgentEvalEnvironmentConnectionError('Dataset connection not found');
+ if (!current.mutable)
+ throw new AgentEvalEnvironmentConnectionError('A built-in connection cannot be changed');
+ const [shared] = await tx
+ .select({ id: agentEvalTestCases.id })
+ .from(agentEvalTestCases)
+ .where(
+ and(
+ eq(agentEvalTestCases.environmentId, current.environmentId),
+ ne(agentEvalTestCases.datasetId, datasetId),
+ ),
+ )
+ .limit(1);
+ if (shared)
+ throw new AgentEvalEnvironmentConnectionError(
+ 'This environment is shared with another dataset. Copy the environment before changing its connections.',
+ );
+ const [row] = await tx
+ .select({ config: agentEvalEnvironments.config })
+ .from(agentEvalEnvironments)
+ .where(
+ and(
+ eq(agentEvalEnvironments.id, current.environmentId),
+ buildWorkspaceWhere(this.scope, agentEvalEnvironments),
+ ),
+ )
+ .limit(1)
+ .for('update');
+ const existing = row?.config.connections?.[current.service];
+ if (!row || !existing)
+ throw new AgentEvalEnvironmentConnectionError('Dataset connection not found');
+ const next: EvalEnvironmentConnection = {
+ credentials: patch.credentials === undefined ? existing.credentials : patch.credentials,
+ name: patch.name ?? existing.name,
+ url: patch.url,
+ };
+ await tx
+ .update(agentEvalEnvironments)
+ .set({
+ config: {
+ ...row.config,
+ connections: { ...row.config.connections, [current.service]: next },
+ },
+ updatedAt: new Date(),
+ })
+ .where(eq(agentEvalEnvironments.id, current.environmentId));
+ return { id: connectorId };
+ });
+}
diff --git a/packages/database/src/repositories/agentEvalExecution/__tests__/index.test.ts b/packages/database/src/repositories/agentEvalExecution/__tests__/index.test.ts
new file mode 100644
index 00000000000..4d63e138e92
--- /dev/null
+++ b/packages/database/src/repositories/agentEvalExecution/__tests__/index.test.ts
@@ -0,0 +1,227 @@
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ agentEvalDatasets,
+ agentEvalRuns,
+ agentEvalRunTopics,
+ agentEvalTestCases,
+ threads,
+ topics,
+ users,
+ workspaces,
+} from '../../../schemas';
+import { AgentEvalExecutionRepo } from '../index';
+
+const db = await getTestDB();
+const owner = 'eval-execution-owner';
+const other = 'eval-execution-other';
+const workspace = 'eval-execution-workspace';
+const foreignWorkspace = 'eval-execution-foreign-workspace';
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: owner }, { id: other }]);
+ await db.insert(workspaces).values([
+ { id: workspace, name: 'Execution', primaryOwnerId: owner, slug: workspace },
+ {
+ id: foreignWorkspace,
+ name: 'Foreign execution',
+ primaryOwnerId: other,
+ slug: foreignWorkspace,
+ },
+ ]);
+});
+
+afterEach(async () => {
+ await db.delete(workspaces).where(eq(workspaces.id, workspace));
+ await db.delete(workspaces).where(eq(workspaces.id, foreignWorkspace));
+ await db.delete(users).where(eq(users.id, owner));
+ await db.delete(users).where(eq(users.id, other));
+});
+
+const setup = async (
+ options: {
+ parentWorkspace?: string;
+ runOwner?: string;
+ runWorkspace?: string;
+ threadOwner?: string;
+ threadWorkspace?: string;
+ } = {},
+) => {
+ const [dataset] = await db
+ .insert(agentEvalDatasets)
+ .values({
+ identifier: 'execution',
+ name: 'Execution',
+ userId: owner,
+ })
+ .returning();
+ const [testCase] = await db
+ .insert(agentEvalTestCases)
+ .values({
+ content: { input: 'Question' },
+ datasetId: dataset.id,
+ userId: owner,
+ })
+ .returning();
+ const [run] = await db
+ .insert(agentEvalRuns)
+ .values({
+ datasetId: dataset.id,
+ status: 'aborted',
+ userId: options.runOwner ?? owner,
+ workspaceId: options.runWorkspace ?? null,
+ })
+ .returning();
+ const [topic] = await db
+ .insert(topics)
+ .values({ userId: owner, workspaceId: options.parentWorkspace ?? null })
+ .returning();
+ await db.insert(agentEvalRunTopics).values({
+ evalResult: { executionId: 'old' },
+ runId: run.id,
+ status: 'error',
+ testCaseId: testCase.id,
+ topicId: topic.id,
+ userId: owner,
+ workspaceId: options.parentWorkspace ?? null,
+ });
+ const [thread] = await db
+ .insert(threads)
+ .values({
+ metadata: { executionId: 'old', status: 'error' },
+ topicId: topic.id,
+ type: 'eval',
+ userId: options.threadOwner ?? owner,
+ workspaceId: options.threadWorkspace ?? null,
+ })
+ .returning();
+ return { run, testCase, thread, topic };
+};
+
+const claim = (chain: Awaited<ReturnType<typeof setup>>, workspaceId?: string, threaded = false) =>
+ new AgentEvalExecutionRepo(db, owner, workspaceId).claimExecution({
+ executionId: 'new',
+ expectedExecutionId: 'old',
+ resume: true,
+ runId: chain.run.id,
+ testCaseId: chain.testCase.id,
+ topicId: chain.topic.id,
+ ...(threaded && { threadId: chain.thread.id }),
+ });
+
+const expectUnchanged = async (chain: Awaited<ReturnType<typeof setup>>) => {
+ const [run] = await db.select().from(agentEvalRuns).where(eq(agentEvalRuns.id, chain.run.id));
+ const [parent] = await db
+ .select()
+ .from(agentEvalRunTopics)
+ .where(eq(agentEvalRunTopics.runId, chain.run.id));
+ const [thread] = await db.select().from(threads).where(eq(threads.id, chain.thread.id));
+ expect(run.status).toBe('aborted');
+ expect(parent).toMatchObject({ status: 'error', evalResult: { executionId: 'old' } });
+ expect(thread.metadata).toEqual({ executionId: 'old', status: 'error' });
+};
+
+describe('AgentEvalExecutionRepo ownership', () => {
+ it('rejects an owned association whose run belongs to another user', async () => {
+ const chain = await setup({ runOwner: other });
+ expect(await claim(chain)).toBeUndefined();
+ await expectUnchanged(chain);
+ });
+
+ it('rejects a run in another workspace even when its association matches', async () => {
+ const chain = await setup({ parentWorkspace: workspace, runWorkspace: foreignWorkspace });
+ expect(await claim(chain, workspace)).toBeUndefined();
+ await expectUnchanged(chain);
+ });
+
+ it('rejects a foreign thread under an otherwise owned run and topic', async () => {
+ const chain = await setup({ threadOwner: other });
+ expect(await claim(chain, undefined, true)).toBeUndefined();
+ await expectUnchanged(chain);
+ });
+
+ it('allows a workspace member to resume a run and thread created by a different member', async () => {
+ const chain = await setup({
+ parentWorkspace: workspace,
+ runOwner: other,
+ runWorkspace: workspace,
+ threadOwner: other,
+ threadWorkspace: workspace,
+ });
+ expect(await claim(chain, workspace, true)).toBeDefined();
+ const [run] = await db.select().from(agentEvalRuns).where(eq(agentEvalRuns.id, chain.run.id));
+ const [thread] = await db.select().from(threads).where(eq(threads.id, chain.thread.id));
+ expect(run.status).toBe('running');
+ expect(thread.metadata).toMatchObject({ executionId: 'new', status: 'running' });
+ });
+
+ it('does not accept another generation after the first resume has claimed it', async () => {
+ const chain = await setup();
+ expect(await claim(chain)).toBeDefined();
+ expect(await claim(chain)).toBeUndefined();
+ });
+});
+
+describe('AgentEvalExecutionRepo pass@k allocation', () => {
+ const pendingChain = async (options: Parameters<typeof setup>[0] = {}) => {
+ const chain = await setup(options);
+ await db.delete(threads).where(eq(threads.id, chain.thread.id));
+ await db
+ .update(agentEvalRuns)
+ .set({ status: 'running' })
+ .where(eq(agentEvalRuns.id, chain.run.id));
+ await db
+ .update(agentEvalRunTopics)
+ .set({ status: 'pending' })
+ .where(eq(agentEvalRunTopics.runId, chain.run.id));
+ return chain;
+ };
+ const prepare = (
+ chain: Awaited<ReturnType<typeof setup>>,
+ workspaceId?: string,
+ expectedExecutionId = 'old',
+ ) =>
+ new AgentEvalExecutionRepo(db, owner, workspaceId).prepareThreadExecutions({
+ expectedExecutionId,
+ k: 2,
+ runId: chain.run.id,
+ testCaseId: chain.testCase.id,
+ topicId: chain.topic.id,
+ });
+
+ it('rejects a parent association whose run is outside the workspace', async () => {
+ const chain = await pendingChain({
+ parentWorkspace: workspace,
+ runWorkspace: foreignWorkspace,
+ });
+ expect(await prepare(chain, workspace)).toBeUndefined();
+ expect(await db.select().from(threads).where(eq(threads.topicId, chain.topic.id))).toEqual([]);
+ });
+
+ it('rejects a stale parent generation without allocating threads', async () => {
+ const chain = await pendingChain();
+ expect(await prepare(chain, undefined, 'stale')).toBeUndefined();
+ expect(await db.select().from(threads).where(eq(threads.topicId, chain.topic.id))).toEqual([]);
+ });
+
+ it('reuses a single attempt set in an authorized workspace with the stable parent owner', async () => {
+ const chain = await pendingChain({ parentWorkspace: workspace, runWorkspace: workspace });
+ const repo = new AgentEvalExecutionRepo(db, other, workspace);
+ const input = {
+ expectedExecutionId: 'old',
+ k: 2,
+ runId: chain.run.id,
+ testCaseId: chain.testCase.id,
+ topicId: chain.topic.id,
+ };
+ const first = await repo.prepareThreadExecutions(input);
+ const retried = await repo.prepareThreadExecutions(input);
+ expect(first?.threadIds).toHaveLength(2);
+ expect(retried?.threadIds).toEqual(first?.threadIds);
+ const saved = await db.select().from(threads).where(eq(threads.topicId, chain.topic.id));
+ expect(saved).toHaveLength(2);
+ expect(saved.every((row) => row.userId === owner && row.workspaceId === workspace)).toBe(true);
+ });
+});
diff --git a/packages/database/src/repositories/agentEvalExecution/index.ts b/packages/database/src/repositories/agentEvalExecution/index.ts
new file mode 100644
index 00000000000..ac627bb5676
--- /dev/null
+++ b/packages/database/src/repositories/agentEvalExecution/index.ts
@@ -0,0 +1,591 @@
+import { and, eq, inArray, lt, or, sql } from 'drizzle-orm';
+
+import {
+ agentEvalRuns,
+ agentEvalRunTopics,
+ agentEvalTestCases,
+ threads,
+ topics,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+
+/** A queued case given a slot that has not started within this long gets its slot back. */
+export const QUEUED_DISPATCH_STALE_MS = 5 * 60_000;
+
+/** Coordinates the run, case and attempt generations under one transaction. */
+export class AgentEvalExecutionRepo {
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {}
+
+ private ownership = () =>
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentEvalRunTopics);
+
+ /**
+ * Atomically stop active cases and retain their partial attempt evidence.
+ */
+ private markStopped = async (runId: string, timeoutMs?: number) => {
+ const reason = timeoutMs === undefined ? 'aborted' : 'timeout';
+ const executionId = crypto.randomUUID();
+ return this.db.transaction(async (tx) => {
+ const stopped = await tx
+ .update(agentEvalRunTopics)
+ .set({
+ evalResult: sql`COALESCE(${agentEvalRunTopics.evalResult}, '{}'::jsonb) || jsonb_build_object(
+ 'completionReason', ${reason}::text, 'executionId', ${executionId}::text,
+ 'error', COALESCE(${agentEvalRunTopics.evalResult}->>'error', ${reason === 'aborted' ? 'Aborted' : 'Timed out'}::text)
+ )`,
+ passed: null,
+ score: null,
+ status: reason === 'aborted' ? 'error' : 'timeout',
+ })
+ .where(
+ and(
+ this.ownership(),
+ eq(agentEvalRunTopics.runId, runId),
+ timeoutMs === undefined
+ ? or(
+ eq(agentEvalRunTopics.status, 'pending'),
+ eq(agentEvalRunTopics.status, 'running'),
+ )
+ : and(
+ eq(agentEvalRunTopics.status, 'running'),
+ lt(agentEvalRunTopics.createdAt, new Date(Date.now() - timeoutMs)),
+ ),
+ ),
+ )
+ .returning();
+ if (timeoutMs === undefined)
+ await tx
+ .update(agentEvalRuns)
+ .set({ status: 'aborted' })
+ .where(
+ and(
+ eq(agentEvalRuns.id, runId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentEvalRuns,
+ ),
+ ),
+ );
+ // Completed attempts are already in thread metadata while their siblings
+ // run. Snapshot them under the same parent lock so Stop keeps that proof.
+ if (stopped.length === 0) return stopped;
+ const allAttempts = await tx
+ .select()
+ .from(threads)
+ .where(
+ and(
+ inArray(
+ threads.topicId,
+ stopped.map((row) => row.topicId),
+ ),
+ eq(threads.type, 'eval'),
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, threads),
+ ),
+ );
+ for (const row of stopped) {
+ const attempts = allAttempts.filter((attempt) => attempt.topicId === row.topicId);
+ if (attempts.length === 0) continue;
+ for (const attempt of attempts) {
+ if (attempt.metadata?.completedAt) continue;
+ attempt.metadata = {
+ ...attempt.metadata,
+ completedAt: new Date().toISOString(),
+ executionId: crypto.randomUUID(),
+ error: reason === 'aborted' ? 'Aborted' : 'Timed out',
+ status: reason === 'aborted' ? 'error' : 'timeout',
+ };
+ await tx
+ .update(threads)
+ .set({ metadata: attempt.metadata })
+ .where(
+ and(
+ eq(threads.id, attempt.id),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ threads,
+ ),
+ ),
+ );
+ }
+ const results = attempts.map((attempt) => ({
+ ...row.evalResult?.threads?.find((result) => result.threadId === attempt.id),
+ ...attempt.metadata,
+ threadId: attempt.id,
+ }));
+ row.evalResult = { ...row.evalResult, threads: results };
+ await tx
+ .update(agentEvalRunTopics)
+ .set({ evalResult: row.evalResult })
+ .where(
+ and(
+ this.ownership(),
+ eq(agentEvalRunTopics.runId, runId),
+ eq(agentEvalRunTopics.topicId, row.topicId),
+ ),
+ );
+ }
+ return stopped;
+ });
+ };
+
+ batchMarkAborted = (runId: string) => this.markStopped(runId);
+
+ batchMarkTimeout = (runId: string, timeoutMs: number) => this.markStopped(runId, timeoutMs);
+
+ /**
+ * Hand a run's waiting cases the slots its concurrency limit leaves free. The
+ * run row is locked, so two cases finishing together cannot give out one slot
+ * twice. A case holds a slot while running, or while still pending after a
+ * dispatch younger than `staleMs` (its trigger has not reached it yet); an
+ * older dispatch that never started is handed out again.
+ */
+ claimQueuedCases = async (
+ runId: string,
+ maxConcurrency: number,
+ staleMs = QUEUED_DISPATCH_STALE_MS,
+ ): Promise<string[]> =>
+ this.db.transaction(async (tx) => {
+ const [run] = await tx
+ .select({ status: agentEvalRuns.status })
+ .from(agentEvalRuns)
+ .where(
+ and(
+ eq(agentEvalRuns.id, runId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentEvalRuns,
+ ),
+ ),
+ )
+ .for('update');
+ if (!run || !['pending', 'running'].includes(run.status ?? '')) return [];
+
+ const rows = await tx
+ .select({
+ evalResult: agentEvalRunTopics.evalResult,
+ status: agentEvalRunTopics.status,
+ testCaseId: agentEvalRunTopics.testCaseId,
+ })
+ .from(agentEvalRunTopics)
+ .leftJoin(agentEvalTestCases, eq(agentEvalTestCases.id, agentEvalRunTopics.testCaseId))
+ .where(and(this.ownership(), eq(agentEvalRunTopics.runId, runId)))
+ // Waiting cases start in the dataset's order.
+ .orderBy(
+ sql`${agentEvalTestCases.sortOrder} ASC NULLS LAST`,
+ agentEvalRunTopics.testCaseId,
+ );
+ const now = Date.now();
+ const dispatched = (row: (typeof rows)[number]) => {
+ const at = Date.parse(row.evalResult?.dispatchedAt ?? '');
+ return Number.isFinite(at) && now - at < staleMs;
+ };
+ const busy = rows.filter(
+ (row) => row.status === 'running' || (row.status === 'pending' && dispatched(row)),
+ ).length;
+ const free = Math.floor(maxConcurrency) - busy;
+ if (free <= 0) return [];
+ const picked = rows
+ .filter((row) => row.status === 'pending' && !dispatched(row))
+ .slice(0, free)
+ .map((row) => row.testCaseId);
+ if (picked.length === 0) return [];
+
+ const stamp = JSON.stringify({ dispatchedAt: new Date(now).toISOString() });
+ await tx
+ .update(agentEvalRunTopics)
+ .set({
+ evalResult: sql`COALESCE(${agentEvalRunTopics.evalResult}, '{}'::jsonb) || ${stamp}::jsonb`,
+ })
+ .where(
+ and(
+ this.ownership(),
+ eq(agentEvalRunTopics.runId, runId),
+ eq(agentEvalRunTopics.status, 'pending'),
+ inArray(agentEvalRunTopics.testCaseId, picked),
+ ),
+ );
+ return picked;
+ });
+
+ /** Give back the slots of cases whose start could not be triggered. */
+ releaseQueuedCases = async (runId: string, testCaseIds: string[]) => {
+ if (testCaseIds.length === 0) return;
+ await this.db
+ .update(agentEvalRunTopics)
+ .set({ evalResult: sql`${agentEvalRunTopics.evalResult} - 'dispatchedAt'` })
+ .where(
+ and(
+ this.ownership(),
+ eq(agentEvalRunTopics.runId, runId),
+ eq(agentEvalRunTopics.status, 'pending'),
+ inArray(agentEvalRunTopics.testCaseId, testCaseIds),
+ ),
+ );
+ };
+
+ /**
+ * Allocate and bind a pass@k attempt set atomically. Retried dispatches read
+ * that same set; a failure before commit leaves the parent pending and no
+ * orphan threads. The lock order matches Stop and execution claims.
+ */
+ prepareThreadExecutions = async (params: {
+ expectedExecutionId?: string;
+ k: number;
+ runId: string;
+ sourceMessageId?: string;
+ testCaseId: string;
+ topicId: string;
+ }) =>
+ this.db.transaction(async (tx) => {
+ const [parent] = await tx
+ .select()
+ .from(agentEvalRunTopics)
+ .where(
+ and(
+ this.ownership(),
+ eq(agentEvalRunTopics.runId, params.runId),
+ eq(agentEvalRunTopics.topicId, params.topicId),
+ eq(agentEvalRunTopics.testCaseId, params.testCaseId),
+ ),
+ )
+ .for('update');
+ if (
+ !parent ||
+ !['pending', 'running'].includes(parent.status ?? '') ||
+ parent.evalResult?.completionReason === 'aborted' ||
+ parent.evalResult?.executionId !== params.expectedExecutionId
+ )
+ return undefined;
+ const [run] = await tx
+ .select()
+ .from(agentEvalRuns)
+ .where(
+ and(
+ eq(agentEvalRuns.id, params.runId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentEvalRuns,
+ ),
+ ),
+ )
+ .for('update');
+ if (!run || run.status === 'aborted') return undefined;
+ const [topic] = await tx
+ .select({ id: topics.id })
+ .from(topics)
+ .where(
+ and(
+ eq(topics.id, params.topicId),
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),
+ ),
+ );
+ if (!topic) return undefined;
+
+ let threadIds = parent.evalResult?.threads?.map((attempt) => attempt.threadId);
+ if (parent.status === 'pending') {
+ if (threadIds?.length) throw new Error('Pending case already has an attempt set');
+ const created = await tx
+ .insert(threads)
+ .values(
+ Array.from({ length: params.k }, () => ({
+ metadata: {
+ executionId: crypto.randomUUID(),
+ status: 'pending',
+ testCaseId: params.testCaseId,
+ },
+ sourceMessageId: params.sourceMessageId,
+ status: 'active' as const,
+ topicId: params.topicId,
+ type: 'eval' as const,
+ userId: parent.userId,
+ workspaceId: parent.workspaceId,
+ })),
+ )
+ .returning({ id: threads.id });
+ threadIds = created.map((thread) => thread.id);
+ await tx
+ .update(agentEvalRunTopics)
+ .set({
+ // The timeout counts from here, as for a single attempt: a case that
+ // waited for a slot must not start already overdue.
+ createdAt: new Date(),
+ evalResult: {
+ ...parent.evalResult,
+ threads: threadIds.map((threadId) => ({ status: 'running' as const, threadId })),
+ },
+ status: 'running',
+ })
+ .where(
+ and(
+ this.ownership(),
+ eq(agentEvalRunTopics.runId, params.runId),
+ eq(agentEvalRunTopics.topicId, params.topicId),
+ ),
+ );
+ }
+ if (!threadIds || threadIds.length !== params.k)
+ throw new Error('Running case has an incomplete attempt set');
+ const attempts = await tx
+ .select()
+ .from(threads)
+ .where(
+ and(
+ inArray(threads.id, threadIds),
+ eq(threads.topicId, params.topicId),
+ eq(threads.type, 'eval'),
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, threads),
+ ),
+ );
+ if (attempts.length !== threadIds.length)
+ throw new Error('Running case has missing attempts');
+ return {
+ pendingThreads: attempts
+ .filter(
+ (attempt) =>
+ attempt.metadata?.status === 'pending' &&
+ !attempt.metadata.startedAt &&
+ !attempt.metadata.completedAt,
+ )
+ .map((attempt) => ({
+ executionId: attempt.metadata?.executionId as string | undefined,
+ threadId: attempt.id,
+ })),
+ threadIds,
+ };
+ });
+
+ /** Claim exactly one generation before creating an operation or resuming it. */
+ claimExecution = async (params: {
+ executionId: string;
+ expectedExecutionId?: string;
+ resume?: boolean;
+ runId: string;
+ testCaseId: string;
+ threadId?: string;
+ topicId: string;
+ }) =>
+ this.db.transaction(async (tx) => {
+ const [parent] = await tx
+ .select()
+ .from(agentEvalRunTopics)
+ .where(
+ and(
+ this.ownership(),
+ eq(agentEvalRunTopics.runId, params.runId),
+ eq(agentEvalRunTopics.topicId, params.topicId),
+ eq(agentEvalRunTopics.testCaseId, params.testCaseId),
+ ),
+ )
+ .for('update');
+ if (!parent) return undefined;
+ const [run] = await tx
+ .select()
+ .from(agentEvalRuns)
+ .where(
+ and(
+ eq(agentEvalRuns.id, params.runId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentEvalRuns,
+ ),
+ ),
+ )
+ .for('update');
+ if (!run || (!params.resume && run.status === 'aborted')) return undefined;
+ const now = new Date(Math.max(Date.now(), (run.startedAt?.getTime() ?? 0) + 1));
+ if (params.resume && parent.evalResult?.executionId !== params.expectedExecutionId)
+ return undefined;
+ if (params.threadId) {
+ const [thread] = await tx
+ .select()
+ .from(threads)
+ .where(
+ and(
+ eq(threads.id, params.threadId),
+ eq(threads.topicId, params.topicId),
+ eq(threads.type, 'eval'),
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, threads),
+ ),
+ );
+ if (!thread) return undefined;
+ const meta = thread.metadata ?? {};
+ const previous = parent.evalResult?.threads?.find(
+ (item) => item.threadId === params.threadId,
+ );
+ if (params.resume) {
+ if (
+ !['error', 'timeout'].includes(String(meta.status ?? previous?.status)) &&
+ parent.status !== 'timeout'
+ )
+ return undefined;
+ } else if (
+ meta.startedAt ||
+ meta.completedAt ||
+ meta.executionId !== params.expectedExecutionId ||
+ parent.evalResult?.completionReason === 'aborted'
+ )
+ return undefined;
+ const result = {
+ executionId: params.executionId,
+ status: 'running' as const,
+ threadId: params.threadId,
+ };
+ const next = (parent.evalResult?.threads ?? []).map((item) =>
+ item.threadId === params.threadId ? result : item,
+ );
+ if (!next.some((item) => item.threadId === params.threadId)) next.push(result);
+ await tx
+ .update(threads)
+ .set({
+ metadata: {
+ executionId: params.executionId,
+ startedAt: now.toISOString(),
+ status: 'running',
+ testCaseId: params.testCaseId,
+ },
+ })
+ .where(
+ and(
+ eq(threads.id, thread.id),
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, threads),
+ ),
+ );
+ await tx
+ .update(agentEvalRunTopics)
+ .set({
+ ...(params.resume && {
+ createdAt: now,
+ evalResult: { executionId: params.executionId, threads: next },
+ passed: null,
+ score: null,
+ }),
+ status: 'running',
+ })
+ .where(
+ and(
+ eq(agentEvalRunTopics.runId, params.runId),
+ eq(agentEvalRunTopics.topicId, params.topicId),
+ this.ownership(),
+ ),
+ );
+ if (params.resume)
+ await tx
+ .update(agentEvalRuns)
+ .set({ startedAt: now, status: 'running' })
+ .where(
+ and(
+ eq(agentEvalRuns.id, params.runId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentEvalRuns,
+ ),
+ ),
+ );
+ return { parent, thread };
+ }
+ if (
+ params.resume
+ ? !['error', 'timeout'].includes(parent.status ?? '')
+ : parent.status !== 'pending'
+ )
+ return undefined;
+ if (!params.resume && parent.evalResult?.executionId !== params.expectedExecutionId)
+ return undefined;
+ await tx
+ .update(agentEvalRunTopics)
+ .set({
+ createdAt: now,
+ evalResult: { executionId: params.executionId },
+ passed: null,
+ score: null,
+ status: 'running',
+ })
+ .where(
+ and(
+ eq(agentEvalRunTopics.runId, params.runId),
+ eq(agentEvalRunTopics.topicId, params.topicId),
+ this.ownership(),
+ ),
+ );
+ if (params.resume)
+ await tx
+ .update(agentEvalRuns)
+ .set({ startedAt: now, status: 'running' })
+ .where(
+ and(
+ eq(agentEvalRuns.id, params.runId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentEvalRuns,
+ ),
+ ),
+ );
+ return { parent, thread: undefined };
+ });
+
+ /** Merge attempt evidence atomically; late callbacks cannot revive a stopped/deleted attempt. */
+ updateThreadMetadata = async (
+ runId: string,
+ topicId: string,
+ threadId: string,
+ metadata: Record<string, unknown>,
+ options?: { executionId?: string },
+ ) => {
+ return this.db.transaction(async (tx) => {
+ // Serialize with Stop's UPDATE of the parent row, including callbacks that
+ // started evaluating before Stop but only now have a result to persist.
+ const [parent] = await tx
+ .select()
+ .from(agentEvalRunTopics)
+ .where(
+ and(
+ this.ownership(),
+ eq(agentEvalRunTopics.runId, runId),
+ eq(agentEvalRunTopics.topicId, topicId),
+ ),
+ )
+ .for('update');
+ if (
+ !parent ||
+ parent.evalResult?.completionReason === 'aborted' ||
+ parent.status === 'timeout'
+ ) {
+ return undefined;
+ }
+ // JSON drops `undefined`, so a plain merge would keep a value the caller
+ // cleared (a re-judged attempt's earlier judge error); remove those keys.
+ const cleared = Object.keys(metadata).filter((key) => metadata[key] === undefined);
+ const stored = sql`COALESCE(${threads.metadata}, '{}'::jsonb)`;
+ const kept =
+ cleared.length > 0
+ ? sql`(${stored} - ARRAY[${sql.join(
+ cleared.map((key) => sql`${key}`),
+ sql`, `,
+ )}]::text[])`
+ : stored;
+ const [result] = await tx
+ .update(threads)
+ .set({
+ metadata: sql`${kept} || ${JSON.stringify(metadata)}::jsonb`,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(threads.id, threadId),
+ eq(threads.topicId, topicId),
+ options
+ ? sql`${threads.metadata}->>'executionId' IS NOT DISTINCT FROM ${options.executionId ?? null}::text`
+ : undefined,
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, threads),
+ ),
+ )
+ .returning({ id: threads.id });
+ return result;
+ });
+ };
+}
diff --git a/packages/database/src/schemas/agentEvals.ts b/packages/database/src/schemas/agentEvals.ts
index 4a25c3e9441..6a535904c5d 100644
--- a/packages/database/src/schemas/agentEvals.ts
+++ b/packages/database/src/schemas/agentEvals.ts
@@ -43,6 +43,7 @@ const evalModes = [
'javascript',
'python',
'llm-rubric',
+ 'rule-checklist',
'factuality',
'answer-relevance',
'similar',
@@ -387,7 +388,20 @@ export const agentEvalRunTopics = pgTable(
.notNull(),
status: text('status', {
- enum: ['pending', 'running', 'passed', 'failed', 'error', 'timeout', 'external', 'completed'],
+ // `judge_error`: the attempt ran, but grading it failed (judge model,
+ // config or parse error). Its answer, memory and cost are kept; it is
+ // re-judged, never re-executed, and counted apart from `failed`.
+ enum: [
+ 'pending',
+ 'running',
+ 'passed',
+ 'failed',
+ 'error',
+ 'timeout',
+ 'external',
+ 'completed',
+ 'judge_error',
+ ],
}),
score: real('score'),
diff --git a/packages/database/src/utils/agentConnectors.ts b/packages/database/src/utils/agentConnectors.ts
index 5ec3b5d1c38..cf32354a3b7 100644
--- a/packages/database/src/utils/agentConnectors.ts
+++ b/packages/database/src/utils/agentConnectors.ts
@@ -11,11 +11,15 @@ interface AgentConnectorHandoverParams {
type Db = LobeChatDatabase | Transaction;
+// Dataset connections never follow normal Agent ownership or scope transfers.
+const ordinaryConnection = () => sql`COALESCE(${userConnectors.metadata} ->> 'agentEval', '') = ''`;
+
/** Agent-OWNED connector rows on these agents attributed to someone other than the recipient. */
const foreignAgentScopedRows = (params: AgentConnectorHandoverParams) =>
and(
inArray(userConnectors.agentId, params.agentIds),
ne(userConnectors.userId, params.recipientId),
+ ordinaryConnection(),
);
/** Base rows another member owns that are MOUNTED by these agents (the Linked flow). */
@@ -23,6 +27,7 @@ const foreignMountedRows = (params: AgentConnectorHandoverParams) =>
and(
inArray(sql`${userConnectors.metadata} ->> 'mountedByAgentId'`, params.agentIds),
ne(userConnectors.userId, params.recipientId),
+ ordinaryConnection(),
);
/**
@@ -136,7 +141,7 @@ export const rehomeAgentConnectorsForScopeTransfer = async (
const scopedRows = await db
.update(userConnectors)
.set({ userId: targetUserId, workspaceId: targetWorkspaceId })
- .where(inArray(userConnectors.agentId, agentIds))
+ .where(and(inArray(userConnectors.agentId, agentIds), ordinaryConnection()))
.returning({ id: userConnectors.id });
if (scopedRows.length > 0) {
@@ -160,7 +165,12 @@ export const rehomeAgentConnectorsForScopeTransfer = async (
await db
.update(userConnectors)
.set({ metadata: sql`${userConnectors.metadata} - 'mountedByAgentId'` })
- .where(inArray(sql`${userConnectors.metadata} ->> 'mountedByAgentId'`, agentIds));
+ .where(
+ and(
+ inArray(sql`${userConnectors.metadata} ->> 'mountedByAgentId'`, agentIds),
+ ordinaryConnection(),
+ ),
+ );
};
/**
diff --git a/packages/database/src/utils/evalTopic.ts b/packages/database/src/utils/evalTopic.ts
new file mode 100644
index 00000000000..4ea924d7067
--- /dev/null
+++ b/packages/database/src/utils/evalTopic.ts
@@ -0,0 +1,6 @@
+import { sql } from 'drizzle-orm';
+
+import { topics } from '../schemas/topic';
+
+/** Keep synthetic eval dialogue out of the account's automatic Memory history. */
+export const notEvalTopic = () => sql`COALESCE(${topics.trigger}, '') <> 'eval'`;
diff --git a/packages/eval-rubric/__tests__/judgeError.test.ts b/packages/eval-rubric/__tests__/judgeError.test.ts
new file mode 100644
index 00000000000..a5c5d0b1efb
--- /dev/null
+++ b/packages/eval-rubric/__tests__/judgeError.test.ts
@@ -0,0 +1,216 @@
+import type { EvalBenchmarkRubric } from '@lobechat/types';
+import { describe, expect, it, vi } from 'vitest';
+
+import { evaluate, match } from '../src';
+import type { JudgeObject, MatchContext } from '../src/matchers/types';
+
+const rubric = (type: EvalBenchmarkRubric['type']): EvalBenchmarkRubric => ({
+ config: { criteria: 'Must: Answer the question.' },
+ id: type,
+ name: type,
+ type,
+ weight: 1,
+});
+
+const judgeTypes = ['answer-relevance', 'llm-rubric', 'rule-checklist'] as const;
+const params = (type: (typeof judgeTypes)[number]) => ({
+ actual: 'The candidate answer',
+ expected: 'The expected answer',
+ input: 'The question',
+ rubric: rubric(type),
+});
+
+describe.each(judgeTypes)('%s Judge failure isolation', (type) => {
+ it('marks unavailable and unconfigured judges without throwing', async () => {
+ const generateObject = vi.fn<NonNullable<MatchContext['generateObject']>>();
+ expect(await match(params(type))).toHaveProperty('judgeError', 'LLM judge not available');
+ expect(await match(params(type), { generateObject })).toHaveProperty(
+ 'judgeError',
+ 'No judge model configured',
+ );
+ expect(generateObject).not.toHaveBeenCalled();
+ });
+
+ it('marks an exhausted provider failure', async () => {
+ const generateObject = vi.fn().mockRejectedValue(new Error('Provider unavailable'));
+ const result = await match(params(type), {
+ generateObject,
+ judgeMaxAttempts: 2,
+ judgeModel: 'judge',
+ });
+ expect(result).toMatchObject({
+ judgeError: 'LLM judge failed: Provider unavailable',
+ passed: false,
+ });
+ });
+
+ it.each([null, {}, { score: '0' }, { score: Number.NaN }, { score: 0 }])(
+ 'marks malformed response %j',
+ async (response) => {
+ const result = await match(params(type), {
+ generateObject: vi.fn().mockResolvedValue(response),
+ judgeMaxAttempts: 1,
+ judgeModel: 'judge',
+ });
+ expect(result.judgeError).toEqual(expect.any(String));
+ expect(result.passed).toBe(false);
+ },
+ );
+
+ it('keeps a valid zero verdict distinct from Judge failure', async () => {
+ const response: JudgeObject =
+ type === 'rule-checklist'
+ ? {
+ rules: [{ index: 1, reason: 'The answer is wrong.', verdict: 'violated' }],
+ summary: 'Not satisfied.',
+ }
+ : { reason: 'The answer is wrong.', score: 0 };
+ const result = await match(params(type), {
+ generateObject: vi.fn().mockResolvedValue(response),
+ judgeModel: 'judge',
+ });
+ expect(result).toMatchObject({ passed: false, score: 0 });
+ expect(result.judgeError).toBeUndefined();
+ });
+});
+
+describe('checklist response contract', () => {
+ const validRow = { index: 1, reason: 'No evidence.', verdict: 'unverifiable' };
+
+ // Each `rules` is the whole array the judge returned. (A bare array table
+ // would be spread into arguments, so the callback would see only its first
+ // element and never the empty or duplicated lists.)
+ it.each([
+ { rules: [] },
+ { rules: [null] },
+ { rules: [{ ...validRow, index: 0 }] },
+ { rules: [{ ...validRow, index: '1' }] },
+ { rules: [{ ...validRow, index: 2 }] },
+ { rules: [{ reason: 'No evidence.', verdict: 'unverifiable' }] },
+ { rules: [{ index: 1, verdict: 'satisfied' }] },
+ { rules: [{ ...validRow, verdict: 'unknown' }] },
+ { rules: [validRow, validRow] },
+ ])('marks missing or invalid rule verdicts $rules', async ({ rules }) => {
+ const result = await match(params('rule-checklist'), {
+ generateObject: vi.fn().mockResolvedValue({ rules, summary: '' }),
+ judgeMaxAttempts: 1,
+ judgeModel: 'judge',
+ });
+ expect(result.judgeError).toEqual(expect.any(String));
+ expect(result.passed).toBe(false);
+ });
+
+ it('keeps an explicit unverifiable verdict valid', async () => {
+ const result = await match(params('rule-checklist'), {
+ generateObject: vi.fn().mockResolvedValue({ rules: [validRow], summary: '' }),
+ judgeModel: 'judge',
+ });
+ expect(result).toMatchObject({ passed: false, score: 0 });
+ expect(result.judgeError).toBeUndefined();
+ expect(result.verdicts?.[0].verdict).toBe('unverifiable');
+ });
+
+ it('rejects a response missing its required summary', async () => {
+ const result = await match(params('rule-checklist'), {
+ generateObject: vi.fn().mockResolvedValue({ rules: [validRow] }),
+ judgeMaxAttempts: 1,
+ judgeModel: 'judge',
+ });
+ expect(result.judgeError).toEqual(expect.any(String));
+ });
+
+ it('requires every rule once while accepting reordered one-based verdicts', async () => {
+ const request = params('rule-checklist');
+ request.rubric.config = { criteria: 'Must: First.\nMust: Second.' };
+ const generateObject = vi.fn();
+ const context = { generateObject, judgeMaxAttempts: 1, judgeModel: 'judge' };
+ for (const rules of [[validRow], [validRow, validRow]]) {
+ generateObject.mockResolvedValue({ rules, summary: '' });
+ expect((await match(request, context)).judgeError).toEqual(expect.any(String));
+ }
+ generateObject.mockResolvedValue({
+ rules: [{ ...validRow, index: 2 }, validRow],
+ summary: 'Insufficient evidence for both.',
+ });
+ const result = await match(request, context);
+ expect(result.judgeError).toBeUndefined();
+ expect(result.verdicts?.map((item) => item.rule)).toEqual(['Must: First.', 'Must: Second.']);
+ });
+
+ it('marks an empty checklist as a grading configuration failure', async () => {
+ const request = params('rule-checklist');
+ request.rubric.config = { criteria: 'Must: ' };
+ const generateObject = vi.fn();
+ const result = await match(request, { generateObject, judgeModel: 'judge' });
+ expect(result.judgeError).toBe('No checklist rules configured');
+ expect(generateObject).not.toHaveBeenCalled();
+ });
+
+ it('retries malformed verdicts and clears the error after recovery', async () => {
+ const generateObject = vi
+ .fn()
+ .mockResolvedValueOnce({ rules: [], summary: '' })
+ .mockResolvedValueOnce({
+ rules: [{ ...validRow, verdict: 'satisfied' }],
+ summary: 'Recovered.',
+ });
+ const result = await match(params('rule-checklist'), { generateObject, judgeModel: 'judge' });
+ expect(generateObject).toHaveBeenCalledTimes(2);
+ expect(result).toMatchObject({ passed: true, score: 1 });
+ expect(result.judgeError).toBeUndefined();
+ });
+});
+
+describe('evaluation Judge failure propagation', () => {
+ it('reports missing grading configuration', async () => {
+ const result = await evaluate({
+ actual: 'Answer',
+ rubrics: [],
+ testCase: { input: 'Question' },
+ });
+ expect(result.judgeError).toBe('No rubrics configured');
+ });
+
+ it('keeps rubric diagnostics and fails closed when another rubric scores highly', async () => {
+ const result = await evaluate(
+ {
+ actual: 'Answer',
+ rubrics: [{ ...rubric('equals'), weight: 9 }, rubric('llm-rubric')],
+ testCase: { expected: 'Answer', input: 'Question' },
+ },
+ { passThreshold: 0.6 },
+ );
+ expect(result.score).toBe(0.9);
+ expect(result.passed).toBe(false);
+ expect(result.judgeError).toContain('LLM judge not available');
+ expect(result.rubricResults[1].judgeError).toBe('LLM judge not available');
+ });
+
+ it.each([true, false])(
+ 'preserves an error alongside a successful any-of candidate (%s)',
+ async (errorFirst) => {
+ const generateObject = vi.fn();
+ if (errorFirst) {
+ generateObject
+ .mockRejectedValueOnce(new Error('Judge unavailable'))
+ .mockResolvedValueOnce({ reason: 'Match', score: 1 });
+ } else {
+ generateObject
+ .mockResolvedValueOnce({ reason: 'Match', score: 1 })
+ .mockRejectedValueOnce(new Error('Judge unavailable'));
+ }
+ const result = await evaluate(
+ {
+ actual: 'Answer',
+ rubrics: [rubric('llm-rubric')],
+ testCase: { expected: '["A","B"]', input: 'Question' },
+ },
+ { matchContext: { generateObject, judgeMaxAttempts: 1, judgeModel: 'judge' } },
+ );
+ expect(generateObject).toHaveBeenCalledTimes(2);
+ expect(result.passed).toBe(false);
+ expect(result.judgeError).toContain('Judge unavailable');
+ expect(result.rubricResults[0].judgeError).toContain('Judge unavailable');
+ },
+ );
+});
diff --git a/packages/eval-rubric/src/evaluate.ts b/packages/eval-rubric/src/evaluate.ts
index 14c717f2da8..ca2cf918ba6 100644
--- a/packages/eval-rubric/src/evaluate.ts
+++ b/packages/eval-rubric/src/evaluate.ts
@@ -1,9 +1,16 @@
-import type { AnswerExtractor, EvalBenchmarkRubric, EvalTestCaseContent } from '@lobechat/types';
+import type {
+ AnswerExtractor,
+ EvalBenchmarkRubric,
+ EvalRuleVerdict,
+ EvalTestCaseContent,
+} from '@lobechat/types';
import { extract } from './extractors';
import { match, type MatchContext, type MatchResult } from './matchers';
export interface EvaluateResult {
+ /** Any grading failure makes this evaluation incomplete; do not use its score as a verdict. */
+ judgeError?: string;
passed: boolean;
reason?: string;
rubricResults: RubricResult[];
@@ -11,10 +18,12 @@ export interface EvaluateResult {
}
export interface RubricResult {
+ judgeError?: string;
passed: boolean;
reason?: string;
rubricId: string;
score: number;
+ verdicts?: EvalRuleVerdict[];
}
export interface EvaluateOptions {
@@ -63,13 +72,22 @@ export const evaluate = async (
},
];
} else {
- return { passed: false, reason: 'No rubrics configured', rubricResults: [], score: 0 };
+ return {
+ judgeError: 'No rubrics configured',
+ passed: false,
+ reason: 'No rubrics configured',
+ rubricResults: [],
+ score: 0,
+ };
}
}
const rubricResults: RubricResult[] = [];
let totalWeight = 0;
let weightedScore = 0;
+ // A gating rubric (rule checklist) fails the case on its own: the threshold
+ // only applies to scored rubrics.
+ let gateFailed = false;
for (const rubric of rubrics) {
// Step 1: Extract answer if extractor is configured
@@ -95,7 +113,11 @@ export const evaluate = async (
);
}
const best = results.reduce((a, b) => (a.score >= b.score ? a : b));
- result = best;
+ // A successful alternative cannot hide a Judge outage on another candidate.
+ const judgeError = results
+ .flatMap((item) => (item.judgeError ? [item.judgeError] : []))
+ .join('\n');
+ result = judgeError ? { ...best, judgeError, passed: false } : best;
} else {
result = await match(
{ input: testCase.input, actual: extracted, expected, rubric },
@@ -104,20 +126,27 @@ export const evaluate = async (
}
rubricResults.push({
+ ...(result.judgeError && { judgeError: result.judgeError }),
passed: result.passed,
reason: result.reason,
rubricId: rubric.id,
score: result.score,
+ ...(result.verdicts && { verdicts: result.verdicts }),
});
+ if (result.gating && !result.passed) gateFailed = true;
totalWeight += rubric.weight;
weightedScore += result.score * rubric.weight;
}
const score = totalWeight > 0 ? weightedScore / totalWeight : 0;
- const passed = score >= passThreshold;
+ const judgeError = rubricResults
+ .flatMap((result) => (result.judgeError ? [`${result.rubricId}: ${result.judgeError}`] : []))
+ .join('\n');
+ const passed = !judgeError && score >= passThreshold && !gateFailed;
return {
+ ...(judgeError && { judgeError }),
passed,
rubricResults,
score,
diff --git a/packages/eval-rubric/src/matchers/__tests__/llmRubric.test.ts b/packages/eval-rubric/src/matchers/__tests__/llmRubric.test.ts
index 4e17f827528..222de6f165b 100644
--- a/packages/eval-rubric/src/matchers/__tests__/llmRubric.test.ts
+++ b/packages/eval-rubric/src/matchers/__tests__/llmRubric.test.ts
@@ -72,8 +72,44 @@ describe('matchLLMRubric', () => {
expect(result.score).toBe(0.5);
});
- it('should clamp score to [0, 1]', async () => {
- mockGenerateObject.mockResolvedValue({ reason: 'overflow', score: 1.5 });
+ it.each([-1, 1.5, 7])(
+ 'should mark out-of-range score %s as a Judge error after retries',
+ async (score) => {
+ mockGenerateObject.mockResolvedValue({ reason: 'Out of range', score });
+
+ const result = await matchLLMRubric({
+ actual: 'x',
+ context: { ...context, judgeMaxAttempts: 2 },
+ rubric: rubric({ criteria: 'test' }),
+ });
+
+ expect(result.passed).toBe(false);
+ expect(result.judgeError).toBe('LLM judge returned an out-of-range score');
+ expect(mockGenerateObject).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ it.each([-1, 7])(
+ 'should recover from out-of-range score %s with a valid retry',
+ async (score) => {
+ mockGenerateObject
+ .mockResolvedValueOnce({ reason: 'Out of range', score })
+ .mockResolvedValueOnce({ reason: 'Recovered', score: 0.8 });
+
+ const result = await matchLLMRubric({
+ actual: 'x',
+ context,
+ rubric: rubric({ criteria: 'test' }),
+ });
+
+ expect(result).toMatchObject({ passed: true, reason: 'Recovered', score: 0.8 });
+ expect(result.judgeError).toBeUndefined();
+ expect(mockGenerateObject).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ it.each([0, 1])('should accept the valid score boundary %s', async (score) => {
+ mockGenerateObject.mockResolvedValue({ reason: 'Valid boundary', score });
const result = await matchLLMRubric({
actual: 'x',
@@ -81,7 +117,9 @@ describe('matchLLMRubric', () => {
rubric: rubric({ criteria: 'test' }),
});
- expect(result.score).toBe(1);
+ expect(result).toMatchObject({ passed: score === 1, score });
+ expect(result.judgeError).toBeUndefined();
+ expect(mockGenerateObject).toHaveBeenCalledTimes(1);
});
it('should return score 0 when generateObject is not available', async () => {
@@ -227,6 +265,33 @@ describe('matchLLMRubric', () => {
expect(userMsg.content).toContain('How do I deploy?');
});
+ it('should give the judge the execution evidence when provided', async () => {
+ mockGenerateObject.mockResolvedValue({ reason: 'ok', score: 1 });
+
+ await matchLLMRubric({
+ actual: 'Saved your workout habits.',
+ context: {
+ ...context,
+ judgeEvidence: 'Tool calls:\n1. lobe-user-memory.addPreferenceMemory',
+ },
+ rubric: rubric({ criteria: 'Must call the memory tool to save the habits' }),
+ });
+
+ const payload = mockGenerateObject.mock.calls[0][0];
+ const userMsg = payload.messages.find((m) => m.role === 'user')!;
+ expect(userMsg.content).toContain('[Evidence]');
+ expect(userMsg.content).toContain('lobe-user-memory.addPreferenceMemory');
+ });
+
+ it('should omit the evidence section when there is none', async () => {
+ mockGenerateObject.mockResolvedValue({ reason: 'ok', score: 1 });
+
+ await matchLLMRubric({ actual: 'Hi', context, rubric: rubric({ criteria: 'Greets' }) });
+
+ const userMsg = mockGenerateObject.mock.calls[0][0].messages.find((m) => m.role === 'user')!;
+ expect(userMsg.content).not.toContain('[Evidence]');
+ });
+
it('should omit input section when not provided', async () => {
mockGenerateObject.mockResolvedValue({ reason: 'ok', score: 1 });
diff --git a/packages/eval-rubric/src/matchers/__tests__/ruleChecklist.test.ts b/packages/eval-rubric/src/matchers/__tests__/ruleChecklist.test.ts
new file mode 100644
index 00000000000..50a76fa6716
--- /dev/null
+++ b/packages/eval-rubric/src/matchers/__tests__/ruleChecklist.test.ts
@@ -0,0 +1,283 @@
+import type { EvalBenchmarkRubric } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { matchRuleChecklist, parseChecklistRules } from '../ruleChecklist';
+import type { GenerateObjectPayload, JudgeObject, MatchContext } from '../types';
+
+const CRITERIA = [
+ 'Must: Submit exactly one paper market buy order for 10 shares of O.',
+ 'Must: Report both order IDs',
+ '(paper_order_001, paper_order_002).',
+ 'Must not: Say the stop order filled.',
+].join('\n');
+
+const rubric = (config: any = { criteria: CRITERIA }): EvalBenchmarkRubric => ({
+ config,
+ id: 'rules',
+ name: 'rules',
+ type: 'rule-checklist',
+ weight: 1,
+});
+
+describe('parseChecklistRules', () => {
+ it('splits Must / Must not lines and keeps continuation lines with their rule', () => {
+ expect(parseChecklistRules(CRITERIA)).toEqual([
+ { kind: 'must', text: 'Submit exactly one paper market buy order for 10 shares of O.' },
+ { kind: 'must', text: 'Report both order IDs (paper_order_001, paper_order_002).' },
+ { kind: 'must-not', text: 'Say the stop order filled.' },
+ ]);
+ });
+
+ it('accepts bullets, numbering and either colon', () => {
+ expect(parseChecklistRules('- Must: keep it\n2) MUST NOT: drop it')).toEqual([
+ { kind: 'must', text: 'keep it' },
+ { kind: 'must-not', text: 'drop it' },
+ ]);
+ });
+
+ it('treats criteria without rule lines as one rule', () => {
+ expect(parseChecklistRules('Grade the attempt against the rules of the case.')).toEqual([
+ { kind: 'rule', text: 'Grade the attempt against the rules of the case.' },
+ ]);
+ });
+});
+
+describe('matchRuleChecklist', () => {
+ const generateObject = vi.fn<(payload: GenerateObjectPayload) => Promise<JudgeObject>>();
+ const context: MatchContext = {
+ generateObject,
+ judgeEvidence:
+ 'Tool calls, in order:\n1. alpaca.submit_order({...}) -> {"id":"paper_order_001"}',
+ judgeModel: 'judge-model',
+ };
+
+ beforeEach(() => generateObject.mockReset());
+
+ it('passes only when every rule is satisfied and scores the share of satisfied rules', async () => {
+ generateObject.mockResolvedValue({
+ rules: [
+ { index: 1, reason: 'One buy order in the evidence.', verdict: 'satisfied' },
+ { index: 2, reason: 'Both ids reported.', verdict: 'satisfied' },
+ { index: 3, reason: 'Nothing says the stop filled.', verdict: 'satisfied' },
+ ],
+ summary: 'Clean execution.',
+ });
+
+ const result = await matchRuleChecklist({ actual: 'Done.', context, rubric: rubric() });
+
+ expect(result).toMatchObject({ gating: true, passed: true, score: 1 });
+ expect(result.verdicts).toHaveLength(3);
+ expect(result.reason).toContain('Clean execution.');
+ expect(result.reason).toContain('1. βœ“ Must: Submit exactly one paper market buy order');
+ });
+
+ it('fails the case on a single violated rule, however high the score', async () => {
+ generateObject.mockResolvedValue({
+ rules: [
+ { index: 1, reason: 'ok', verdict: 'satisfied' },
+ { index: 2, reason: 'ok', verdict: 'satisfied' },
+ { index: 3, reason: 'The output says the stop "filled".', verdict: 'violated' },
+ ],
+ summary: 'Mostly right.',
+ });
+
+ const result = await matchRuleChecklist({ actual: 'Stop filled.', context, rubric: rubric() });
+
+ expect(result.passed).toBe(false);
+ expect(result.score).toBe(0.667);
+ expect(result.reason).toContain(
+ '3. βœ— Must not: Say the stop order filled. β€” The output says the stop "filled".',
+ );
+ expect(result.verdicts?.[2]).toEqual({
+ reason: 'The output says the stop "filled".',
+ rule: 'Must not: Say the stop order filled.',
+ verdict: 'violated',
+ });
+ });
+
+ it('counts an explicit unverifiable rule as not satisfied', async () => {
+ generateObject.mockResolvedValue({
+ rules: [
+ { index: 1, reason: 'ok', verdict: 'satisfied' },
+ { index: 2, reason: 'Evidence is insufficient.', verdict: 'unverifiable' },
+ { index: 3, reason: 'Evidence does not show the order ids.', verdict: 'unverifiable' },
+ ],
+ summary: '',
+ });
+
+ const result = await matchRuleChecklist({ actual: 'Done.', context, rubric: rubric() });
+
+ expect(result.passed).toBe(false);
+ expect(result.judgeError).toBeUndefined();
+ expect(result.verdicts?.map((v) => v.verdict)).toEqual([
+ 'satisfied',
+ 'unverifiable',
+ 'unverifiable',
+ ]);
+ });
+
+ it('shows the judge the numbered rules, the output and the evidence', async () => {
+ generateObject.mockResolvedValue({ rules: [], summary: '' });
+
+ await matchRuleChecklist({ actual: 'Done.', context, input: 'Buy 10 O', rubric: rubric() });
+
+ const prompt = generateObject.mock.calls[0][0].messages[1].content;
+ expect(prompt).toContain('[Rules]\n1. Must: Submit exactly one paper market buy order');
+ expect(prompt).toContain('3. Must not: Say the stop order filled.');
+ expect(prompt).toContain('[Input]\nBuy 10 O');
+ expect(prompt).toContain('[Output]\nDone.');
+ expect(prompt).toContain('[Evidence]');
+ expect(prompt).toContain('alpaca.submit_order');
+ expect(generateObject.mock.calls[0][0].model).toBe('judge-model');
+ });
+
+ it('shows an expected behaviour as a reference, never as one more rule', async () => {
+ generateObject.mockResolvedValue({ rules: [], summary: '' });
+
+ await matchRuleChecklist({
+ actual: 'Done.',
+ context,
+ expected: 'Buy, then place a stop and report both ids.',
+ rubric: rubric(),
+ });
+
+ const [system, user] = generateObject.mock.calls[0][0].messages;
+ expect(user.content).toContain('[Reference]\nBuy, then place a stop and report both ids.');
+ expect(user.content).not.toContain('[Expected]');
+ // Three rules from the criteria; the reference adds none.
+ const rulesBlock = user.content.split('\n\n')[0];
+ expect(rulesBlock.split('\n').slice(1)).toHaveLength(3);
+ expect(system.content).toContain('it is not a rule');
+ });
+
+ it('tells the judge a failed call with no effect does not count as doing the action', async () => {
+ generateObject.mockResolvedValue({ rules: [], summary: '' });
+
+ await matchRuleChecklist({ actual: 'Done.', context, rubric: rubric() });
+
+ const [system] = generateObject.mock.calls[0][0].messages;
+ expect(system.content).toContain('A tool call that failed and had no effect');
+ });
+
+ it('retries a judge answer without verdicts, then fails', async () => {
+ generateObject.mockResolvedValue({ reason: 'fine', score: 1 });
+
+ const result = await matchRuleChecklist({
+ actual: 'Done.',
+ context: { ...context, judgeMaxAttempts: 2 },
+ rubric: rubric(),
+ });
+
+ expect(generateObject).toHaveBeenCalledTimes(2);
+ expect(result).toMatchObject({
+ gating: true,
+ passed: false,
+ reason: 'LLM judge did not return rule verdicts: its answer had no list of rule verdicts',
+ score: 0,
+ });
+ });
+
+ it('limits the judge answer to one verdict per rule', async () => {
+ generateObject.mockResolvedValue({
+ rules: [{ index: 1, reason: 'Done.', verdict: 'satisfied' }],
+ summary: 'Done.',
+ });
+
+ await matchRuleChecklist({
+ actual: 'Done.',
+ context,
+ rubric: rubric({ criteria: 'Must: Create the agent, then schedule it.' }),
+ });
+
+ const { messages, schema } = generateObject.mock.calls[0][0];
+ const rules = (schema.properties as any).rules;
+ expect(rules).toMatchObject({ maxItems: 1, minItems: 1 });
+ expect(rules.items.properties.index).toMatchObject({ maximum: 1, minimum: 1 });
+ expect(messages.at(-1)!.content).toContain('exactly 1 verdict');
+ });
+
+ // A judge that splits one long rule into two verdicts, or sends broken JSON,
+ // used to get the same prompt again and repeat the mistake on every attempt.
+ it('tells the judge what was wrong when it retries', async () => {
+ generateObject
+ .mockResolvedValueOnce({
+ rules: [
+ { index: 1, reason: 'Agent created.', verdict: 'satisfied' },
+ { index: 2, reason: 'Threshold explained.', verdict: 'satisfied' },
+ ],
+ summary: 'Done.',
+ })
+ .mockRejectedValueOnce(new Error('Invalid structured output: invalid JSON in tool arguments'))
+ .mockResolvedValueOnce({
+ rules: [{ index: 1, reason: 'Agent created and scheduled.', verdict: 'satisfied' }],
+ summary: 'Done.',
+ });
+
+ const result = await matchRuleChecklist({
+ actual: 'Done.',
+ context,
+ rubric: rubric({ criteria: 'Must: Create the agent, then schedule it.' }),
+ });
+
+ expect(result).toMatchObject({ passed: true, score: 1 });
+ const prompts = generateObject.mock.calls.map(([payload]) => payload.messages.at(-1)!.content);
+ expect(prompts[0]).not.toContain('previous answer');
+ expect(prompts[1]).toContain('previous answer had 2 verdicts for 1 rule');
+ expect(prompts[2]).toContain('previous answer was not valid JSON');
+ });
+
+ it('asks again when a rule that is not met comes back with no reason', async () => {
+ generateObject
+ .mockResolvedValueOnce({
+ rules: [{ index: 1, reason: '', verdict: 'violated' }],
+ summary: 'Done.',
+ })
+ .mockResolvedValueOnce({
+ rules: [
+ { index: 1, reason: 'The schedule fires at 16:30, not 16:00.', verdict: 'violated' },
+ ],
+ summary: 'Wrong time.',
+ });
+
+ const result = await matchRuleChecklist({
+ actual: 'Done.',
+ context,
+ rubric: rubric({ criteria: 'Must: Schedule the job at 16:00.' }),
+ });
+
+ expect(generateObject).toHaveBeenCalledTimes(2);
+ expect(result.reason).toContain('fires at 16:30');
+ expect(generateObject.mock.calls[1][0].messages.at(-1)!.content).toContain(
+ 'gave rule 1 a "violated" verdict with an empty reason',
+ );
+ });
+
+ it('tells the judge how to read success messages, sourced figures and counts', async () => {
+ generateObject.mockResolvedValue({
+ rules: [{ index: 1, reason: 'Done.', verdict: 'satisfied' }],
+ summary: 'Done.',
+ });
+
+ await matchRuleChecklist({
+ actual: 'Done.',
+ context,
+ rubric: rubric({ criteria: 'Must: Do it.' }),
+ });
+
+ const system = generateObject.mock.calls[0][0].messages[0].content;
+ expect(system).toContain('is not proof the change took effect');
+ expect(system).toContain('must appear in a tool result');
+ expect(system).toContain('count them');
+ expect(system).toContain('make the verdict match it');
+ });
+
+ it('fails without a judge', async () => {
+ const result = await matchRuleChecklist({ actual: 'Done.', rubric: rubric() });
+
+ expect(result).toMatchObject({
+ gating: true,
+ passed: false,
+ reason: 'LLM judge not available',
+ });
+ });
+});
diff --git a/packages/eval-rubric/src/matchers/index.ts b/packages/eval-rubric/src/matchers/index.ts
index 96a9688beaa..f24a32baf16 100644
--- a/packages/eval-rubric/src/matchers/index.ts
+++ b/packages/eval-rubric/src/matchers/index.ts
@@ -11,6 +11,7 @@ import { matchLLMEq } from './llmEq';
import { matchLLMRubric } from './llmRubric';
import { matchNumeric } from './numeric';
import { matchRegex } from './regex';
+import { matchRuleChecklist } from './ruleChecklist';
import { matchStartsWith } from './startsWith';
import type { MatchContext, MatchResult } from './types';
@@ -72,6 +73,10 @@ export const match = async (
return matchLLMRubric({ actual, context, expected, input, rubric });
}
+ case 'rule-checklist': {
+ return matchRuleChecklist({ actual, context, expected, input, rubric });
+ }
+
case 'json-schema': {
return matchJsonSchema(actual, config);
}
diff --git a/packages/eval-rubric/src/matchers/judgeError.ts b/packages/eval-rubric/src/matchers/judgeError.ts
new file mode 100644
index 00000000000..912fb391a23
--- /dev/null
+++ b/packages/eval-rubric/src/matchers/judgeError.ts
@@ -0,0 +1,9 @@
+import type { MatchResult } from './types';
+
+/** A missing verdict is a grading failure, not evidence that the candidate failed. */
+export const judgeErrorResult = (reason: string): MatchResult => ({
+ judgeError: reason,
+ passed: false,
+ reason,
+ score: 0,
+});
diff --git a/packages/eval-rubric/src/matchers/llmEq.ts b/packages/eval-rubric/src/matchers/llmEq.ts
index 671d5296ef3..b2afadb1f8f 100644
--- a/packages/eval-rubric/src/matchers/llmEq.ts
+++ b/packages/eval-rubric/src/matchers/llmEq.ts
@@ -1,5 +1,6 @@
import type { EvalBenchmarkRubric, RubricConfigLLM } from '@lobechat/types';
+import { judgeErrorResult } from './judgeError';
import type { MatchContext, MatchResult } from './types';
const DEFAULT_SYSTEM_ROLE = [
@@ -51,14 +52,14 @@ export const matchLLMEq = async (
context?: MatchContext,
): Promise<MatchResult> => {
if (!context?.generateObject) {
- return { passed: false, reason: 'LLM judge not available', score: 0 };
+ return judgeErrorResult('LLM judge not available');
}
- const cfg = rubric.config as RubricConfigLLM;
+ const cfg = (rubric.config ?? {}) as RubricConfigLLM;
const model = cfg.model || context.judgeModel;
- if (!model) {
- return { passed: false, reason: 'No judge model configured', score: 0 };
+ if (typeof model !== 'string' || !model.trim()) {
+ return judgeErrorResult('No judge model configured');
}
try {
@@ -72,7 +73,10 @@ export const matchLLMEq = async (
schema: JUDGE_SCORE_SCHEMA,
});
- const score = result?.score === 1 ? 1 : 0;
+ if ((result?.score !== 0 && result?.score !== 1) || typeof result?.reason !== 'string') {
+ return judgeErrorResult('LLM judge did not return a valid binary score and reason');
+ }
+ const score = result.score;
return {
passed: score === 1,
@@ -80,10 +84,8 @@ export const matchLLMEq = async (
score,
};
} catch (error) {
- return {
- passed: false,
- reason: `LLM judge failed: ${error instanceof Error ? error.message : String(error)}`,
- score: 0,
- };
+ return judgeErrorResult(
+ `LLM judge failed: ${error instanceof Error ? error.message : String(error)}`,
+ );
}
};
diff --git a/packages/eval-rubric/src/matchers/llmRubric.ts b/packages/eval-rubric/src/matchers/llmRubric.ts
index 498d461de5d..94368698648 100644
--- a/packages/eval-rubric/src/matchers/llmRubric.ts
+++ b/packages/eval-rubric/src/matchers/llmRubric.ts
@@ -1,5 +1,6 @@
import type { EvalBenchmarkRubric, RubricConfigLLM } from '@lobechat/types';
+import { judgeErrorResult } from './judgeError';
import type { MatchContext, MatchResult } from './types';
const DEFAULT_SYSTEM_ROLE = [
@@ -28,6 +29,7 @@ function buildJudgeUserPrompt(
actual: string,
expected: string | undefined,
input: string | undefined,
+ evidence: string | undefined,
): string {
const parts = [`[Criteria]\n${criteria}`];
// Surface the task input (e.g. the prompt/draft/context the output responds
@@ -37,6 +39,13 @@ function buildJudgeUserPrompt(
parts.push(`[Input]\n${input}`);
}
parts.push(`[Output]\n${actual}`);
+ // The output is only the final reply. Criteria about what the agent did (call
+ // a tool, save something) can only be judged from the actions themselves.
+ if (evidence) {
+ parts.push(
+ `[Evidence]\nWhat the AI did while producing the output. Use it for criteria about actions or resulting state.\n${evidence}`,
+ );
+ }
if (expected) {
parts.push(`[Expected]\n${expected}`);
}
@@ -59,20 +68,26 @@ export const matchLLMRubric = async ({
rubric,
}: MatchLLMRubricParams): Promise<MatchResult> => {
if (!context?.generateObject) {
- return { passed: false, reason: 'LLM judge not available', score: 0 };
+ return judgeErrorResult('LLM judge not available');
}
- const cfg = rubric.config as RubricConfigLLM;
+ const cfg = (rubric.config ?? {}) as RubricConfigLLM;
+ if (cfg.criteria !== undefined && typeof cfg.criteria !== 'string') {
+ return judgeErrorResult('Invalid judge criteria');
+ }
const criteria = cfg.criteria || 'Evaluate whether the output is correct and helpful.';
const model = cfg.model || context.judgeModel;
- if (!model) {
- return { passed: false, reason: 'No judge model configured', score: 0 };
+ if (typeof model !== 'string' || !model.trim()) {
+ return judgeErrorResult('No judge model configured');
}
const messages = [
{ content: cfg.systemRole || DEFAULT_SYSTEM_ROLE, role: 'system' as const },
- { content: buildJudgeUserPrompt(criteria, actual, expected, input), role: 'user' as const },
+ {
+ content: buildJudgeUserPrompt(criteria, actual, expected, input, context.judgeEvidence),
+ role: 'user' as const,
+ },
];
const threshold = rubric.threshold ?? 0.6;
const maxAttempts = Math.max(1, context.judgeMaxAttempts ?? 3);
@@ -80,11 +95,7 @@ export const matchLLMRubric = async ({
// Retry transient judge flakes β€” a thrown error or a malformed response with no
// usable score. The judge occasionally returns no parseable score under load;
// a single bad sample shouldn't auto-fail an otherwise-good output.
- let lastResult: MatchResult = {
- passed: false,
- reason: 'LLM judge did not return a score',
- score: 0,
- };
+ let lastResult = judgeErrorResult('LLM judge did not return a score');
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const result = await context.generateObject({
@@ -96,18 +107,23 @@ export const matchLLMRubric = async ({
// Note: a valid score can be 0 (output fully fails the criteria), so check
// the type rather than truthiness β€” `!result.score` would drop real zeros.
- if (typeof result?.score === 'number' && Number.isFinite(result.score)) {
- const score = Math.max(0, Math.min(1, result.score));
- return { passed: score >= threshold, reason: result.reason, score };
+ if (typeof result?.score !== 'number' || !Number.isFinite(result.score)) {
+ lastResult = judgeErrorResult('LLM judge did not return a score');
+ continue;
}
-
- lastResult = { passed: false, reason: 'LLM judge did not return a score', score: 0 };
+ if (result.score < 0 || result.score > 1) {
+ lastResult = judgeErrorResult('LLM judge returned an out-of-range score');
+ continue;
+ }
+ if (typeof result.reason !== 'string') {
+ lastResult = judgeErrorResult('LLM judge did not return a reason');
+ continue;
+ }
+ return { passed: result.score >= threshold, reason: result.reason, score: result.score };
} catch (error) {
- lastResult = {
- passed: false,
- reason: `LLM judge failed: ${error instanceof Error ? error.message : String(error)}`,
- score: 0,
- };
+ lastResult = judgeErrorResult(
+ `LLM judge failed: ${error instanceof Error ? error.message : String(error)}`,
+ );
}
}
diff --git a/packages/eval-rubric/src/matchers/ruleChecklist.ts b/packages/eval-rubric/src/matchers/ruleChecklist.ts
new file mode 100644
index 00000000000..6278dcea118
--- /dev/null
+++ b/packages/eval-rubric/src/matchers/ruleChecklist.ts
@@ -0,0 +1,289 @@
+import type { EvalBenchmarkRubric, EvalRuleVerdict, RubricConfigLLM } from '@lobechat/types';
+
+import { judgeErrorResult } from './judgeError';
+import type { MatchContext, MatchResult } from './types';
+
+/**
+ * Rule checklist.
+ *
+ * The criteria are a list of `Must:` / `Must not:` rules and the judge decides
+ * every rule on its own instead of blending them into one score. The case
+ * passes only when every rule is satisfied; the score is the share of rules
+ * satisfied, kept for ranking and diagnosis. There is no threshold: a 0.9 is a
+ * failed case with one rule missed, not a pass.
+ */
+
+const DEFAULT_SYSTEM_ROLE = [
+ 'You are a strict auditor. An AI agent attempted a task; grade the attempt against a checklist of rules, one rule at a time.',
+ '',
+ 'Base every verdict on what the [Output] says and on what the [Evidence] shows the agent actually did. A claim in the output that the evidence does not support is not satisfied. Do not solve the task yourself and do not reward effort.',
+ '',
+ 'Verdicts:',
+ '- "satisfied": the output or the evidence shows the rule was met.',
+ '- "violated": the output or the evidence shows the rule was broken, or a "Must" rule was not done.',
+ '- "unverifiable": the materials show neither. Use it only when nothing in the output or the evidence bears on the rule; when they show the rule met or broken, say so.',
+ 'A "Must not" rule is satisfied when nothing in the output or the evidence breaks it.',
+ 'A tool call that failed and had no effect does not count as doing the action: judge rules about how many times something was done by the calls that succeeded.',
+ '',
+ 'How to read the evidence:',
+ '- A result that says "success" is not proof the change took effect. Check that it names the record, field and value the rule is about; a result showing another field or no change means the action was not done.',
+ '- Figures, names and facts the output presents as found (market sizes, rates, prices, IDs, quotes) must appear in a tool result. A figure credited to a source whose result failed, was empty or was never read is not supported.',
+ '- When a rule names a number (exactly three links, five items, one event), count them in the output or the evidence before deciding, and give the count in the reason.',
+ '- Time and schedule rules: work out what the call actually does (for example the times a cron pattern fires) rather than trusting the description the agent wrote.',
+ '- Write the reason first, then make the verdict match it. A reason that says the rule was met with a "violated" verdict, or the other way round, is wrong.',
+ '',
+ 'A [Reference], when given, describes one acceptable way to handle the task. Use it only to understand what the rules mean; it is not a rule. Never mark a rule violated because the attempt differs from the reference.',
+ '',
+ 'Respond with a JSON object: {"rules": [{"index": <rule number>, "verdict": "satisfied" | "violated" | "unverifiable", "reason": "<one sentence>"}, ...], "summary": "<one sentence on the attempt>"}. Include every rule exactly once.',
+].join('\n');
+
+const VERDICTS = ['satisfied', 'violated', 'unverifiable'] as const;
+
+/**
+ * The judge answer for `count` rules: one verdict per rule, numbered 1 to
+ * `count`. The bounds also steer judges that do not enforce the schema.
+ */
+const checklistSchema = (count: number): Record<string, unknown> => ({
+ additionalProperties: false,
+ properties: {
+ rules: {
+ description: `Exactly ${count} verdict${count === 1 ? '' : 's'}, one per rule`,
+ items: {
+ additionalProperties: false,
+ properties: {
+ index: {
+ description: `The rule number, from 1 to ${count}`,
+ maximum: count,
+ minimum: 1,
+ type: 'integer',
+ },
+ reason: { description: 'One sentence grounding the verdict', type: 'string' },
+ verdict: { enum: VERDICTS, type: 'string' },
+ },
+ required: ['index', 'verdict', 'reason'],
+ type: 'object',
+ },
+ maxItems: count,
+ minItems: count,
+ type: 'array',
+ },
+ summary: { description: 'One sentence on the attempt as a whole', type: 'string' },
+ },
+ required: ['rules', 'summary'],
+ type: 'object',
+});
+
+export interface ChecklistRule {
+ kind: 'must' | 'must-not' | 'rule';
+ text: string;
+}
+
+const RULE_LINE = /^\s*(?:[-*β€’]\s*|\d+[.)]\s*)?(must\s+not|must)\s*[::](.*)$/i;
+
+/**
+ * Splits the criteria into rules: one per `Must:` / `Must not:` line, with
+ * following plain lines appended to the rule above them. Criteria without
+ * such lines are one rule.
+ */
+export const parseChecklistRules = (criteria: string): ChecklistRule[] => {
+ const rules: ChecklistRule[] = [];
+ for (const raw of criteria.split(/\r?\n/)) {
+ const line = raw.trim();
+ if (!line) continue;
+ const matched = RULE_LINE.exec(line);
+ if (matched) {
+ rules.push({
+ kind: /not$/i.test(matched[1].replaceAll(/\s+/g, '')) ? 'must-not' : 'must',
+ text: matched[2].trim(),
+ });
+ } else if (rules.length > 0) {
+ rules.at(-1)!.text += ` ${line}`;
+ }
+ }
+ return rules.length > 0 ? rules : [{ kind: 'rule', text: criteria.trim() }];
+};
+
+const ruleLabel = (rule: ChecklistRule) =>
+ rule.kind === 'must'
+ ? `Must: ${rule.text}`
+ : rule.kind === 'must-not'
+ ? `Must not: ${rule.text}`
+ : rule.text;
+
+const MARK: Record<EvalRuleVerdict['verdict'], string> = {
+ satisfied: 'βœ“',
+ unverifiable: '?',
+ violated: 'βœ—',
+};
+
+function buildUserPrompt(
+ rules: ChecklistRule[],
+ actual: string,
+ expected: string | undefined,
+ input: string | undefined,
+ evidence: string | undefined,
+): string {
+ const parts = [`[Rules]\n${rules.map((rule, i) => `${i + 1}. ${ruleLabel(rule)}`).join('\n')}`];
+ if (input) parts.push(`[Input]\n${input}`);
+ parts.push(`[Output]\n${actual}`);
+ if (evidence) {
+ parts.push(
+ `[Evidence]\nWhat the agent did while producing the output: its tool calls in order, with results, and the state it left behind. Rules about actions or resulting state are decided from here, not from what the output claims.\n${evidence}`,
+ );
+ }
+ // Graded only through the rules: shown as context, never as one more requirement.
+ if (expected) parts.push(`[Reference]\n${expected}`);
+ return parts.join('\n\n');
+}
+
+interface JudgeRuleRow {
+ index?: unknown;
+ reason?: unknown;
+ verdict?: unknown;
+}
+
+const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}`;
+
+/**
+ * Require exactly one explicit verdict for every one-based rule in the schema;
+ * otherwise say what is wrong, so a retry can be told.
+ */
+const readVerdicts = (
+ rules: ChecklistRule[],
+ rows: unknown[],
+): { problem: string } | { verdicts: EvalRuleVerdict[] } => {
+ if (rows.length !== rules.length)
+ return {
+ problem: `had ${plural(rows.length, 'verdict')} for ${plural(rules.length, 'rule')}`,
+ };
+ const byIndex = new Map<number, EvalRuleVerdict>();
+ for (const value of rows) {
+ const row = value as JudgeRuleRow | null | undefined;
+ const index = row?.index;
+ const verdict = VERDICTS.find((item) => item === row?.verdict);
+ if (typeof index !== 'number' || !Number.isInteger(index) || index < 1 || index > rules.length)
+ return { problem: `numbered a verdict ${String(index)}, outside 1 to ${rules.length}` };
+ if (byIndex.has(index)) return { problem: `gave rule ${index} more than one verdict` };
+ if (!verdict || typeof row?.reason !== 'string')
+ return { problem: `gave rule ${index} no valid verdict and reason` };
+ // A rule that is not met has to say why: the failure is read from this reason.
+ if (verdict !== 'satisfied' && !row.reason.trim())
+ return { problem: `gave rule ${index} a "${verdict}" verdict with an empty reason` };
+ byIndex.set(index, {
+ ...(row.reason && { reason: row.reason }),
+ rule: ruleLabel(rules[index - 1]),
+ verdict,
+ });
+ }
+ return { verdicts: rules.map((_, position) => byIndex.get(position + 1)!) };
+};
+
+/** Asks for exactly one verdict per rule; after an unusable answer, also says what was wrong. */
+const answerInstruction = (count: number, problem?: string) =>
+ [
+ ...(problem
+ ? [
+ `[Correction]\nYour previous answer ${problem}, so it could not be used. Answer again from the same materials.`,
+ ]
+ : []),
+ `[Answer]\nThere ${count === 1 ? 'is' : 'are'} ${plural(count, 'rule')}. Return exactly ${plural(count, 'verdict')}, numbered 1 to ${count}, one per rule as listed: never split a rule into several verdicts or merge rules. Return only valid JSON matching the schema.`,
+ ].join('\n\n');
+
+export interface MatchRuleChecklistParams {
+ actual: string;
+ context?: MatchContext;
+ expected?: string;
+ input?: string;
+ rubric: EvalBenchmarkRubric;
+}
+
+export const matchRuleChecklist = async ({
+ actual,
+ context,
+ expected,
+ input,
+ rubric,
+}: MatchRuleChecklistParams): Promise<MatchResult> => {
+ if (!context?.generateObject) {
+ return { ...judgeErrorResult('LLM judge not available'), gating: true };
+ }
+
+ const cfg = (rubric.config ?? {}) as RubricConfigLLM;
+ if (cfg.criteria !== undefined && typeof cfg.criteria !== 'string') {
+ return { ...judgeErrorResult('Invalid judge criteria'), gating: true };
+ }
+ const model = cfg.model || context.judgeModel;
+ if (typeof model !== 'string' || !model.trim()) {
+ return { ...judgeErrorResult('No judge model configured'), gating: true };
+ }
+
+ const rules = parseChecklistRules(cfg.criteria || 'The output completes the task correctly.');
+ if (rules.some((rule) => !rule.text)) {
+ return { ...judgeErrorResult('No checklist rules configured'), gating: true };
+ }
+ const userPrompt = buildUserPrompt(rules, actual, expected, input, context.judgeEvidence);
+ const schema = checklistSchema(rules.length);
+ const maxAttempts = Math.max(1, context.judgeMaxAttempts ?? 3);
+
+ let lastResult: MatchResult = {
+ ...judgeErrorResult('LLM judge did not return rule verdicts'),
+ gating: true,
+ };
+ // Why the previous answer was unusable: the retry says so instead of asking
+ // the same question again and getting the same mistake back.
+ let problem: string | undefined;
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ try {
+ const result = await context.generateObject({
+ messages: [
+ { content: cfg.systemRole || DEFAULT_SYSTEM_ROLE, role: 'system' as const },
+ {
+ content: `${userPrompt}\n\n${answerInstruction(rules.length, problem)}`,
+ role: 'user' as const,
+ },
+ ],
+ model,
+ provider: cfg.provider,
+ schema,
+ });
+ const read = Array.isArray(result?.rules)
+ ? readVerdicts(rules, result.rules)
+ : { problem: 'had no list of rule verdicts' };
+ if ('problem' in read || typeof result?.summary !== 'string') {
+ problem = 'problem' in read ? read.problem : 'had no summary';
+ lastResult = {
+ ...judgeErrorResult(`LLM judge did not return rule verdicts: its answer ${problem}`),
+ gating: true,
+ };
+ continue;
+ }
+ const { verdicts } = read;
+
+ const satisfied = verdicts.filter((item) => item.verdict === 'satisfied').length;
+ const summary = typeof result.summary === 'string' ? result.summary.trim() : '';
+ const lines = verdicts.map(
+ (item, i) =>
+ `${i + 1}. ${MARK[item.verdict]} ${item.rule}${
+ item.verdict === 'satisfied' || !item.reason ? '' : ` β€” ${item.reason}`
+ }`,
+ );
+
+ return {
+ gating: true,
+ passed: satisfied === verdicts.length,
+ reason: [summary, ...lines].filter(Boolean).join('\n'),
+ score: Math.round((satisfied / verdicts.length) * 1000) / 1000,
+ verdicts,
+ };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ problem = /invalid json/i.test(message) ? 'was not valid JSON' : 'could not be read';
+ lastResult = {
+ ...judgeErrorResult(`LLM judge failed: ${message}`),
+ gating: true,
+ };
+ }
+ }
+
+ return lastResult;
+};
diff --git a/packages/eval-rubric/src/matchers/types.ts b/packages/eval-rubric/src/matchers/types.ts
index 9567087ea7d..2b34d07efb6 100644
--- a/packages/eval-rubric/src/matchers/types.ts
+++ b/packages/eval-rubric/src/matchers/types.ts
@@ -1,3 +1,5 @@
+import type { EvalRuleVerdict } from '@lobechat/types';
+
export interface GenerateObjectPayload {
messages: { content: string; role: 'system' | 'user' }[];
model: string;
@@ -5,15 +7,38 @@ export interface GenerateObjectPayload {
schema: Record<string, unknown>;
}
+/** What a judge call returns: the fields the payload's schema asked for. */
+export interface JudgeObject {
+ [key: string]: unknown;
+ reason?: string;
+ score?: number;
+}
+
export interface MatchContext {
- generateObject?: (payload: GenerateObjectPayload) => Promise<{ reason: string; score: number }>;
+ generateObject?: (payload: GenerateObjectPayload) => Promise<JudgeObject>;
+ /**
+ * What the agent did while producing the output, for criteria about actions
+ * rather than the reply text: tool calls and their results, and the state
+ * they left behind. Only LLM-judged rubrics read it.
+ */
+ judgeEvidence?: string;
/** Max attempts for the LLM judge before giving up (transient flakes / missing score). Default 3. */
judgeMaxAttempts?: number;
judgeModel?: string;
}
export interface MatchResult {
+ /**
+ * The rubric decides pass/fail by itself: a case fails when a gating rubric
+ * fails, whatever the weighted score says. Set by rubrics with a binary
+ * verdict, such as the rule checklist.
+ */
+ gating?: boolean;
+ /** Grading failed; passed/score are diagnostic placeholders, not a quality verdict. */
+ judgeError?: string;
passed: boolean;
reason?: string;
score: number;
+ /** Per-rule verdicts of a rule checklist. */
+ verdicts?: EvalRuleVerdict[];
}
diff --git a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts
index 0066c38e8ad..dfbe4311b59 100644
--- a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts
+++ b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts
@@ -111,4 +111,39 @@ describe('buildMessagesEngineParams', () => {
expect(generators.hostname()).toBe('unknown');
expect(generators.defaultShell()).not.toContain('{{');
});
+
+ it('renders every date the model sees from the eval session clock', () => {
+ const params = buildMessagesEngineParams({
+ ...baseSnapshot(),
+ tools: {
+ manifests: [
+ {
+ identifier: 'lobe-web-browsing',
+ systemRole: 'Search.\nCurrent date: 2026-10-22',
+ } as any,
+ { identifier: 'other', systemRole: 'No date here' } as any,
+ ],
+ },
+ world: {
+ evalContext: { sessionDate: '2026-07-21', timezone: 'Asia/Shanghai' },
+ userTimezone: 'America/New_York',
+ },
+ });
+
+ expect(params.timezone).toBe('Asia/Shanghai');
+ expect(params.variableGenerators!.date()).toContain('July 21, 2026');
+ expect(params.variableGenerators!.timezone()).toBe('Asia/Shanghai');
+ expect(params.toolsConfig?.manifests?.[0].systemRole).toBe('Search.\nCurrent date: 2026-07-21');
+ expect(params.toolsConfig?.manifests?.[1].systemRole).toBe('No date here');
+ });
+
+ it('renders the eval clock in UTC when the case names no timezone', () => {
+ const params = buildMessagesEngineParams({
+ ...baseSnapshot(),
+ world: { evalContext: { sessionDate: '2026-07-21T23:30:00Z' }, userTimezone: 'Asia/Tokyo' },
+ });
+
+ expect(params.timezone).toBe('UTC');
+ expect(params.variableGenerators!.date()).toContain('July 21, 2026');
+ });
});
diff --git a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts
index 1d66368421b..ee939b14a22 100644
--- a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts
+++ b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts
@@ -1,5 +1,5 @@
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
-import type { MessagesEngineParams } from '@lobechat/context-engine';
+import type { LobeToolManifest, MessagesEngineParams } from '@lobechat/context-engine';
import type { ContextSnapshot } from './types';
import { createVariableGenerators } from './variableGenerators';
@@ -9,6 +9,31 @@ const definedOnly = <T extends Record<string, unknown>>(record: T): Partial<T> =
Object.entries(record).filter(([, value]) => value !== undefined),
) as Partial<T>;
+const CURRENT_DATE_LINE = /Current date: \d{4}-\d{2}-\d{2}/g;
+
+/**
+ * A tool prompt that states the current date (web browsing does, from the
+ * wall clock at load time) is rewritten to the attempt's clock, so the model
+ * sees one consistent "today".
+ */
+const pinManifestDates = (
+ manifests: LobeToolManifest[] | undefined,
+ clock: Date,
+ timezone: string,
+): LobeToolManifest[] | undefined => {
+ if (!manifests) return manifests;
+ const date = new Intl.DateTimeFormat('en-CA', {
+ day: '2-digit',
+ month: '2-digit',
+ timeZone: timezone,
+ year: 'numeric',
+ }).format(clock);
+ return manifests.map((manifest) => {
+ const systemRole = manifest.systemRole?.replaceAll(CURRENT_DATE_LINE, `Current date: ${date}`);
+ return systemRole === manifest.systemRole ? manifest : { ...manifest, systemRole };
+ });
+};
+
/**
* Turn a {@link ContextSnapshot} into the parameters the messages engine runs
* on. Pure: the same snapshot always yields the same parameters, so hosts
@@ -18,6 +43,18 @@ export const buildMessagesEngineParams = (snapshot: ContextSnapshot): MessagesEn
const { agent, fileContext, model, run, step, tools, variables, world } = snapshot;
const enabledToolIds = tools?.enabledToolIds;
+
+ // An eval attempt runs on its case clock: every "today" the model sees β€”
+ // `{{date}}`, the system date line, a tool prompt's current date β€” renders
+ // from the session date in the case timezone (UTC when none), never from the
+ // wall clock or the caller's timezone.
+ const evalClock = world?.evalContext?.sessionDate
+ ? new Date(world.evalContext.sessionDate)
+ : undefined;
+ const timezone = evalClock ? (world?.evalContext?.timezone ?? 'UTC') : world?.userTimezone;
+ const manifests = evalClock
+ ? pinManifestDates(tools?.manifests, evalClock, timezone!)
+ : tools?.manifests;
// The page agent's system role is only meaningful while a page is being
// edited; hide it unless the run enabled the tool explicitly.
const disabledToolIdentifiers =
@@ -60,7 +97,7 @@ export const buildMessagesEngineParams = (snapshot: ContextSnapshot): MessagesEn
toolDiscoveryConfig: tools?.toolDiscoveryConfig,
toolsConfig: {
disabledToolIdentifiers,
- manifests: tools?.manifests,
+ manifests,
tools: enabledToolIds,
},
...(tools?.enabledSkills?.length && { skillsConfig: { enabledSkills: tools.enabledSkills } }),
@@ -69,11 +106,12 @@ export const buildMessagesEngineParams = (snapshot: ContextSnapshot): MessagesEn
fileContext: fileContext ?? { enabled: true, includeFileUrl: true },
variableGenerators: createVariableGenerators({
model: model.model,
+ now: evalClock ? () => evalClock : undefined,
provider: model.provider,
- timezone: world?.userTimezone,
+ timezone,
variables,
}),
- timezone: world?.userTimezone,
+ timezone,
// --- world (frozen at creation) ---
...definedOnly({
diff --git a/packages/mecha/src/contextEngineering/variableGenerators.ts b/packages/mecha/src/contextEngineering/variableGenerators.ts
index 5a9bc65bbdb..b12c6c02205 100644
--- a/packages/mecha/src/contextEngineering/variableGenerators.ts
+++ b/packages/mecha/src/contextEngineering/variableGenerators.ts
@@ -6,6 +6,8 @@ import type { ContextVariables } from './types';
export interface CreateVariableGeneratorsParams {
model?: string;
+ /** The clock temporal placeholders render from; the wall clock when absent. */
+ now?: () => Date;
provider?: string;
/** IANA timezone the temporal placeholders render in. Defaults to UTC. */
timezone?: string;
@@ -26,11 +28,13 @@ export interface CreateVariableGeneratorsParams {
*/
export const createVariableGenerators = ({
model,
+ now,
provider,
timezone,
variables,
}: CreateVariableGeneratorsParams): VariableGenerators => {
const tz = timezone || 'UTC';
+ const clock = now ?? (() => new Date());
// h23 keeps midnight as "00" instead of "24".
const timeParts = (): Record<string, string> => {
const parts = new Intl.DateTimeFormat('en-US', {
@@ -42,25 +46,25 @@ export const createVariableGenerators = ({
second: '2-digit',
timeZone: tz,
year: 'numeric',
- }).formatToParts(new Date());
+ }).formatToParts(clock());
return Object.fromEntries(parts.map((part) => [part.type, part.value]));
};
const defaults: VariableGenerators = {
// --- time ---
- date: () => new Date().toLocaleDateString('en-US', { dateStyle: 'full', timeZone: tz }),
- datetime: () => new Date().toLocaleString('en-US', { timeZone: tz }),
+ date: () => clock().toLocaleDateString('en-US', { dateStyle: 'full', timeZone: tz }),
+ datetime: () => clock().toLocaleString('en-US', { timeZone: tz }),
day: () => timeParts().day,
hour: () => timeParts().hour,
- iso: () => new Date().toISOString(),
+ iso: () => clock().toISOString(),
locale: () => 'en-US',
minute: () => timeParts().minute,
month: () => timeParts().month,
second: () => timeParts().second,
- time: () => new Date().toLocaleTimeString('en-US', { timeStyle: 'medium', timeZone: tz }),
- timestamp: () => Date.now().toString(),
+ time: () => clock().toLocaleTimeString('en-US', { timeStyle: 'medium', timeZone: tz }),
+ timestamp: () => clock().getTime().toString(),
timezone: () => tz,
- weekday: () => new Date().toLocaleDateString('en-US', { timeZone: tz, weekday: 'long' }),
+ weekday: () => clock().toLocaleDateString('en-US', { timeZone: tz, weekday: 'long' }),
year: () => timeParts().year,
// The creds tool's session context renders the calendar date.
@@ -71,7 +75,7 @@ export const createVariableGenerators = ({
timeZone: tz,
weekday: 'long',
year: 'numeric',
- }).format(new Date()),
+ }).format(clock()),
// --- model ---
model: () => model ?? '',
diff --git a/packages/openapi/src/services/eval-context.service.ts b/packages/openapi/src/services/eval-context.service.ts
index 31fe7bbd04e..f67e7b56c97 100644
--- a/packages/openapi/src/services/eval-context.service.ts
+++ b/packages/openapi/src/services/eval-context.service.ts
@@ -1,4 +1,4 @@
-import { and, asc, count, eq, isNull } from 'drizzle-orm';
+import { and, asc, count, eq, isNull, sql } from 'drizzle-orm';
import { threads, topics, userInstalledPlugins } from '@/database/schemas';
@@ -49,7 +49,10 @@ export class EvalContextService extends BaseService {
return { threads: rows, total: totals[0].total };
}
async listPlugins(query: EvalPagination) {
- const where = this.buildWorkspaceWhere(userInstalledPlugins);
+ const where = and(
+ this.buildWorkspaceWhere(userInstalledPlugins),
+ sql`COALESCE(${userInstalledPlugins.source}, '') <> 'agent-eval'`,
+ );
const { limit, offset } = evalPagination(query);
const [rows, totals] = await Promise.all([
this.db
diff --git a/packages/openapi/src/services/eval-lifecycle.service.ts b/packages/openapi/src/services/eval-lifecycle.service.ts
index d1e52d3bba9..d37d0b42e88 100644
--- a/packages/openapi/src/services/eval-lifecycle.service.ts
+++ b/packages/openapi/src/services/eval-lifecycle.service.ts
@@ -4,6 +4,7 @@ import isEqual from 'fast-deep-equal';
import { AgentEvalRunModel, AgentEvalRunTopicModel } from '@/database/models/agentEval';
import { ThreadModel } from '@/database/models/thread';
+import { AgentEvalExecutionRepo } from '@/database/repositories/agentEvalExecution';
import { agentEvalRuns, agentEvalRunTopics, threads, topics } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import { evaluateAndFinalizeRun } from '@/server/services/agentEvalRun/aggregate';
@@ -195,7 +196,7 @@ export class EvalLifecycleService extends BaseService {
throw this.createConflictError('Cannot complete a run with outstanding or failed cases');
} else {
if (['failed', 'aborted'].includes(input.status))
- await ctx.runTopicModel.batchMarkAborted(id);
+ await new AgentEvalExecutionRepo(tx, this.userId, this.workspaceId).batchMarkAborted(id);
await ctx.runModel.update(id, { status: input.status });
}
return projectRun((await ctx.runModel.findById(id))!);
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index bd241867c02..9e22b688d97 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -4,6 +4,8 @@ import type { LobeAgentChatConfig } from '../agent/chatConfig';
import type { CreateThreadWithMessageParams } from '../aiChat';
import type { DeviceUnavailableErrorData } from '../device';
import { workingDirConfigSchema } from '../device';
+import type { EvalToolForwardingConfig } from '../eval/agentEval';
+import type { EvalMemoryReference } from '../eval/evalMemory';
import type { ComposerUserMessage, TaskDetail, UIChatMessage } from '../message';
import type { ChatTopic } from '../topic';
@@ -659,6 +661,25 @@ export interface ExecVirtualSubAgentParams {
* runs instead of re-routing through the agent-level `boundDeviceId`.
*/
deviceId?: string;
+ /**
+ * What the child inherits when the parent runs inside an eval attempt: the
+ * attempt's prompt context (session clock), its runtime (tool forwarding,
+ * Memory scope) and its step cap. Without these the child leaves the sandbox:
+ * it reaches real services, the caller's own Memory and the wall clock, and
+ * runs with no step limit.
+ */
+ eval?: {
+ context?: { envPrompt?: string; sessionDate?: string; timezone?: string };
+ maxSteps?: number;
+ runtime?: {
+ /** The parent's tool allowlist; the child may not reach past it either. */
+ allowedTools?: string[];
+ attemptId?: string;
+ caseId?: string;
+ memory?: EvalMemoryReference;
+ toolForwarding?: EvalToolForwardingConfig;
+ };
+ };
/** The Group ID inherited from the parent operation, when present */
groupId?: string;
/** Instruction/prompt for the virtual sub-agent */
diff --git a/packages/types/src/agentExecution/initRequest.ts b/packages/types/src/agentExecution/initRequest.ts
index 27a185d8ff0..cb2de2cb97e 100644
--- a/packages/types/src/agentExecution/initRequest.ts
+++ b/packages/types/src/agentExecution/initRequest.ts
@@ -1,3 +1,5 @@
+import type { EvalConnectorSnapshots } from '../eval/agentEval';
+import type { EvalMemoryReference } from '../eval/evalMemory';
import type { ChatAudioItem, ChatFileItem, ChatVideoItem, MessagePluginItem } from '../message';
import type { RuntimeMentionedAgent } from '../stepContext';
@@ -56,6 +58,12 @@ export interface AgentRunInitRequest {
disableTools?: boolean;
/** A user turn that is prompted but never persisted (self-iteration runs). */
ephemeralUserMessage?: string;
+ /** The exact tool surface exposed to an isolated evaluation attempt. */
+ evalAllowedTools?: string[];
+ /** Server-validated exact connector references; never credentials. */
+ evalConnectorSnapshots?: EvalConnectorSnapshots;
+ /** Server-created Memory scope for one evaluation attempt. */
+ evalMemory?: EvalMemoryReference;
/** When set, the run may use ONLY these tools. */
exclusivePluginIds?: string[];
/** The exact messages the caller supplied as history, instead of the topic's. */
diff --git a/packages/types/src/agentOperation.ts b/packages/types/src/agentOperation.ts
index 69fe631c857..dda0c940161 100644
--- a/packages/types/src/agentOperation.ts
+++ b/packages/types/src/agentOperation.ts
@@ -52,7 +52,10 @@ export type AgentOperationCompletionReason =
| 'interrupted'
| 'lease_expired'
| 'max_steps'
- /** The same tool call was requested over and over; a guard cut the run short. */
+ /**
+ * The same tool call was requested over and over, or one turn requested more
+ * tool calls than the burst limit; a guard cut the run short.
+ */
| 'tool_call_repeat_limit'
| 'waiting_for_async_tool'
| 'waiting_for_client'
diff --git a/packages/types/src/eval/agentEval.ts b/packages/types/src/eval/agentEval.ts
index 5fb57e19ab7..9d120fccbde 100644
--- a/packages/types/src/eval/agentEval.ts
+++ b/packages/types/src/eval/agentEval.ts
@@ -3,7 +3,10 @@
* Defines test cases, run configurations, and metadata for agent evaluation
*/
+import type { AgentMemoryChatConfig, LobeAgentChatConfig } from '../agent/chatConfig';
import type { ImportedMessage } from '../export';
+import type { EvalMemoryFixture, EvalMemorySnapshot } from './evalMemory';
+import type { EvalToolManifest, EvalToolManifests } from './toolManifest';
export type { RubricType as EvalMode } from './rubric';
@@ -17,16 +20,164 @@ export interface EvalToolForwardingConfig {
[identifier: string]: EvalToolForwardingTarget;
}
+/** A local connection selected for one logical mock service; never contains credentials. */
+export interface EvalConnectorBinding {
+ connectorId: string;
+ transport?: 'mcp' | 'lobe-bench';
+}
+
+export type EvalConnectorBindings = Record<string, EvalConnectorBinding>;
+
+/**
+ * A mock connection kept in its Environment instead of a user connector row.
+ * Bindings name it `env:<environmentId>:<service>` (see `environmentConnectionId`).
+ * `credentials` is the server-encrypted credential JSON and never leaves the
+ * server: copies sent to clients drop it and carry `hasCredentials` instead.
+ */
+export interface EvalEnvironmentConnection {
+ credentials?: string | null;
+ /** Set only on redacted copies sent to clients. */
+ hasCredentials?: boolean;
+ name?: string;
+ url: string;
+}
+
+/** Server-captured connection identity and tool contract used by a run. */
+export interface EvalConnectorSnapshot extends EvalConnectorBinding {
+ /** Frozen owning Dataset; absent only on legacy runs, which cannot resume. */
+ datasetId?: string;
+ fingerprint: string;
+ /** Frozen original contract; absent on legacy runs, which must not resume with a new surface. */
+ manifest?: EvalToolManifest;
+}
+
+export type EvalConnectorSnapshots = Record<string, EvalConnectorSnapshot>;
+
+/** Sampling parameters a model-only run applies to every case's hidden Agent. */
+export interface EvalRunModelParams {
+ frequency_penalty?: number;
+ presence_penalty?: number;
+ temperature?: number;
+ top_p?: number;
+}
+
+/**
+ * Model-specific settings (reasoning on/off and effort, thinking level and
+ * budget, verbosity …) a model-only run applies to every case's hidden Agent:
+ * the ones the chat model-params panel offers, per the model's
+ * `settings.extendParams`. Together with `EvalRunModelParams` they make one
+ * "contender": the same model with another setting is a different contender.
+ */
+export type EvalRunChatConfig = Pick<
+ LobeAgentChatConfig,
+ | 'codexMaxReasoningEffort'
+ | 'deepseekV4GAReasoningEffort'
+ | 'deepseekV4ReasoningEffort'
+ | 'disableContextCaching'
+ | 'effort'
+ | 'enableAdaptiveThinking'
+ | 'enableReasoning'
+ | 'glm5_2ReasoningEffort'
+ | 'glm5_3ReasoningEffort'
+ | 'gpt5_1ReasoningEffort'
+ | 'gpt5_2ProReasoningEffort'
+ | 'gpt5_2ReasoningEffort'
+ | 'gpt5_6ReasoningEffort'
+ | 'gpt5ReasoningEffort'
+ | 'gpt6ReasoningEffort'
+ | 'grok4_20ReasoningEffort'
+ | 'grok4_3ReasoningEffort'
+ | 'grok4_5ReasoningEffort'
+ | 'grok4_6ReasoningEffort'
+ | 'grok4_7ReasoningEffort'
+ | 'hy3ReasoningEffort'
+ | 'kimiK3ReasoningEffort'
+ | 'opus47Effort'
+ | 'preserveThinking'
+ | 'qwen38ReasoningEffort'
+ | 'reasoningBudgetToken'
+ | 'reasoningBudgetToken32k'
+ | 'reasoningBudgetToken80k'
+ | 'reasoningEffort'
+ | 'reasoningMode'
+ | 'ring2_6ReasoningEffort'
+ | 'step3_5ReasoningEffort'
+ | 'textVerbosity'
+ | 'thinking'
+ | 'thinkingBudget'
+ | 'thinkingLevel'
+ | 'thinkingLevel2'
+ | 'thinkingLevel3'
+ | 'thinkingLevel4'
+>;
+
+/** Logical mock services required by a case, independent of deployment and credentials. */
+export interface EvalCaseMockConfig {
+ /** Tool namespaces, each resolved through the environment's connector bindings. */
+ services: string[];
+}
+
export interface EvalToolForwardingTarget {
- endpoint: string;
+ /**
+ * Historical endpoint retained only for reading old data. New writes reject
+ * it, and execution resolves the selected connection's address instead.
+ */
+ endpoint?: string;
timeoutMs?: number;
}
+/**
+ * The Agent a test case brings with it. A case that carries one runs on its
+ * own hidden (`virtual`) Agent built from this setup, so a benchmark can give
+ * every case a different persona and tool set without touching the user's
+ * Agent list. Omitted fields fall back to the run's target Agent, or to the
+ * product defaults when the run only picks a model.
+ */
+export interface EvalCaseAgentConfig {
+ memory?: AgentMemoryChatConfig['memory'];
+ /** The name the model is told the user knows it by; no identity line when absent. */
+ name?: string;
+ /** Exact tool allowlist (plugin identifiers); an empty array disables tools. */
+ plugins?: string[];
+ systemRole?: string;
+ title?: string;
+}
+
/** Per-test-case runtime configuration used only by eval trajectories. */
export interface EvalCaseEnvironment {
+ agent?: EvalCaseAgentConfig;
+ /**
+ * Mock connections stored in this Environment row, by service. Only a shared
+ * Environment carries them; a case's own overrides never do.
+ */
+ connections?: Record<string, EvalEnvironmentConnection>;
+ /** Logical tool identifiers bound to scoped MCP connections in this installation. */
+ connectorBindings?: EvalConnectorBindings;
/** Case-specific system context appended after the dataset eval prompt. */
envPrompt?: string;
+ /**
+ * Memory each attempt starts from. Every attempt (and every pass@k thread)
+ * runs on its own isolated Memory owner seeded with this fixture; `{}` starts
+ * empty. The caller's own memories are never read or written by a trial.
+ */
+ memory?: EvalMemoryFixture;
+ /**
+ * Logical mock services required by this case. Each service must be bound
+ * to an available connection before execution.
+ */
+ mock?: EvalCaseMockConfig;
+ /**
+ * The attempt's clock, an ISO date or instant. Every "today" the model sees
+ * (the `{{date}}` placeholder, the system date line, a tool prompt's current
+ * date) renders from it instead of the wall clock, so the case reads the same
+ * on any day it is run. Nothing tells the model the date is pinned.
+ */
+ sessionDate?: string;
+ /** IANA timezone `sessionDate` renders in; UTC when absent. */
+ timezone?: string;
toolForwarding?: EvalToolForwardingConfig;
+ /** Original model-visible contracts, independent of mock connection discovery. */
+ toolManifests?: EvalToolManifests;
}
/**
@@ -96,6 +247,16 @@ export interface EvalRunConfig {
[key: string]: unknown;
agentSnapshot?: EvalRunAgentSnapshot;
caseSelection?: EvalCaseSelection;
+ /**
+ * The version of the dataset's cases the run ran on ({@link evalCaseVersionOf}),
+ * captured by the server when the run is created. Cases are edited in place,
+ * so a leaderboard counts only runs on the dataset's current version.
+ */
+ caseVersion?: string;
+ /** Model-specific settings of a model-only run; see {@link EvalRunChatConfig}. */
+ chatConfig?: EvalRunChatConfig;
+ /** Server-owned connection snapshots, keyed by case database ID. Credentials are excluded. */
+ connectorSnapshots?: Record<string, EvalConnectorSnapshots>;
/**
* Immutable snapshot of how the run executes: 'internal' (QStash workflow,
* topics pre-created) or 'external' (worker-driven, on-demand). Written at
@@ -109,8 +270,20 @@ export interface EvalRunConfig {
* @default 1
*/
k?: number;
+ /**
+ * How many cases of the run execute at once (each with its k attempts). Unset,
+ * every case starts together; set, the rest wait and start as cases finish.
+ */
maxConcurrency?: number;
maxSteps?: number;
+ /**
+ * Model every case runs on. Set it to compare models on a benchmark: the
+ * run then needs no target Agent, and each case runs on a hidden Agent
+ * built from its own setup plus this model.
+ */
+ model?: string;
+ /** Sampling parameters of a model-only run; see {@link EvalRunModelParams}. */
+ params?: EvalRunModelParams;
/**
* Score threshold for a test case to be considered "passed"
* @default 0.6
@@ -120,6 +293,8 @@ export interface EvalRunConfig {
system?: string;
user: string;
};
+ /** Provider of `model`; always set together with it. */
+ provider?: string;
timeout?: number;
}
@@ -129,7 +304,15 @@ export interface EvalRunConfig {
*/
export type EvalRunInputConfig = Pick<
EvalRunConfig,
- 'caseSelection' | 'k' | 'maxConcurrency' | 'maxSteps' | 'timeout'
+ | 'caseSelection'
+ | 'chatConfig'
+ | 'k'
+ | 'maxConcurrency'
+ | 'maxSteps'
+ | 'model'
+ | 'params'
+ | 'provider'
+ | 'timeout'
>;
/**
@@ -145,8 +328,23 @@ export interface EvalRunMetrics {
errorCases?: number;
externalCases?: number;
failedCases: number;
+ /**
+ * Attempts that ran but could not be graded (judge failure). Not in
+ * `failedCases`, not in `averageScore`: the run's grading is incomplete
+ * until they are re-judged.
+ */
+ judgeErrorCases?: number;
llmCalls?: number;
+ /**
+ * Share of cases expected to pass all j attempts (pass^j), for every j up to
+ * the run's attempts, keyed by j. Estimated without bias from each case's c
+ * passed of n attempts as C(c,j)/C(n,j), so a run of 5 attempts also says how
+ * it would fare on 3.
+ */
+ passAllAt?: Record<string, number>;
passAllK?: number;
+ /** Share of cases expected to pass at least one of j attempts (pass@j): 1 βˆ’ C(nβˆ’c,j)/C(n,j). */
+ passAnyAt?: Record<string, number>;
passAtK?: number;
passedCases: number;
passRate: number;
@@ -196,10 +394,20 @@ export interface EvalTopicMetadata {
/**
* Individual rubric score result
*/
+/** One rule of a `rule-checklist` rubric, as the judge decided it. */
+export interface EvalRuleVerdict {
+ reason?: string;
+ /** The rule as shown to the judge, e.g. "Must: Submit exactly one order". */
+ rule: string;
+ verdict: 'satisfied' | 'unverifiable' | 'violated';
+}
+
export interface EvalRubricScore {
reason?: string;
rubricId: string;
score: number;
+ /** Per-rule verdicts of a `rule-checklist` rubric. */
+ verdicts?: EvalRuleVerdict[];
}
/*eslint-disable perfectionist/sort-interfaces */
@@ -207,6 +415,12 @@ export interface EvalRubricScore {
* Evaluation result stored on RunTopic after scoring
*/
export interface EvalRunTopicResult {
+ /** When a run with a concurrency limit handed this waiting case a slot. */
+ dispatchedAt?: string;
+ /** Identity of the current execution, used to fence delayed callbacks. */
+ executionId?: string;
+ /** Actual requested model/provider pairs used for this grading attempt. */
+ judges?: Array<{ model: string; provider: string }>;
cost?: number;
tokens?: number;
duration?: number;
@@ -227,12 +441,18 @@ export interface EvalRunTopicResult {
error?: string;
errorDetail?: unknown;
+ /** Which stage failed when `status` is `judge_error`: the judge, never the candidate. */
+ errorPhase?: 'judge';
+ /** Why grading failed (judge model, config or parse error); cleared by a successful re-judge. */
+ judgeError?: string;
/** Opaque evidence reported by an external evaluator. */
externalResult?: Record<string, unknown>;
/** Per-thread external evidence for K > 1 runs. */
externalThreadResults?: Record<string, unknown>;
extractedAnswer?: string;
completionReason?: string;
+ /** Final state of the attempt's isolated Memory, kept after the owner is deleted. */
+ memorySnapshot?: EvalMemorySnapshot;
operationId?: string;
rubricScores?: EvalRubricScore[];
/** Set when evalMode is 'external' β€” agent finished, awaiting external scoring */
@@ -248,12 +468,29 @@ export interface EvalThreadResult {
cost?: number;
duration?: number;
error?: string;
+ /** Older stored attempts may carry this without a judge_error status. */
+ errorPhase?: 'judge';
+ executionId?: string;
+ /** Why grading this thread failed; the thread is re-judged, not re-run. */
+ judgeError?: string;
+ /** Actual requested model/provider pairs, preserved independently of defaults. */
+ judges?: Array<{ model: string; provider: string }>;
llmCalls?: number;
+ /** Final state of this thread's isolated Memory, kept after the owner is deleted. */
+ memorySnapshot?: EvalMemorySnapshot;
operationId?: string;
passed?: boolean;
rubricScores?: EvalRubricScore[];
score?: number;
- status?: 'error' | 'external' | 'failed' | 'passed' | 'running' | 'timeout' | 'completed';
+ status?:
+ | 'error'
+ | 'external'
+ | 'failed'
+ | 'passed'
+ | 'running'
+ | 'timeout'
+ | 'completed'
+ | 'judge_error';
steps?: number;
threadId: string;
tokens?: number;
@@ -273,3 +510,18 @@ export interface EvalThreadMetadata {
score?: number;
testCaseId: string;
}
+
+/**
+ * The version of a dataset's cases: the Release they were published in, with the
+ * presentation the bench engine serves tool results in (it changes what a model
+ * sees without a new Release). Undefined for a dataset that records no Release.
+ */
+export const evalCaseVersionOf = (
+ metadata?: Record<string, unknown> | null,
+): string | undefined => {
+ const release = typeof metadata?.release === 'string' ? metadata.release : undefined;
+ if (!release) return undefined;
+ const presentation =
+ typeof metadata?.presentation === 'string' ? metadata.presentation : undefined;
+ return presentation ? `${release}+${presentation}` : release;
+};
diff --git a/packages/types/src/eval/agentEvalEnvironment.ts b/packages/types/src/eval/agentEvalEnvironment.ts
new file mode 100644
index 00000000000..0fb3a31f2ae
--- /dev/null
+++ b/packages/types/src/eval/agentEvalEnvironment.ts
@@ -0,0 +1,30 @@
+import type { EvalCaseEnvironment } from './agentEval';
+
+// ============================================
+// Environment Entity Types
+// ============================================
+
+/**
+ * A reusable case environment: the Agent setup (persona, tools, memory
+ * switch), the Memory fixture, the clock and the mock connectors that many
+ * cases share. A case points at one through `environmentId`; one environment
+ * can back five, ten or a hundred cases, so none of this is copied per case.
+ */
+export interface AgentEvalEnvironment {
+ config: EvalCaseEnvironment;
+ createdAt: Date;
+ description?: string | null;
+ id: string;
+ /** Stable handle for scripts and imports (unique per owner when set). */
+ identifier?: string | null;
+ metadata?: Record<string, unknown> | null;
+ name: string;
+ updatedAt: Date;
+ userId?: string | null;
+ workspaceId?: string | null;
+}
+
+/** Environment list row: the entity plus how many cases point at it. */
+export interface AgentEvalEnvironmentListItem extends AgentEvalEnvironment {
+ testCaseCount?: number;
+}
diff --git a/packages/types/src/eval/agentEvalRun.ts b/packages/types/src/eval/agentEvalRun.ts
index 25d1a11a634..60f191139a9 100644
--- a/packages/types/src/eval/agentEvalRun.ts
+++ b/packages/types/src/eval/agentEvalRun.ts
@@ -24,6 +24,10 @@ export interface AgentEvalRun {
config?: EvalRunConfig | null;
createdAt: Date;
datasetId: string;
+ /** The Lobe Bench or Lab experiment this run belongs to, if any. */
+ experimentId?: string | null;
+ /** Derived from saved attempts, including legacy runs with incomplete metrics. */
+ hasUnverifiedAttempts?: boolean;
id: string;
metrics?: EvalRunMetrics | null;
name?: string | null;
@@ -49,6 +53,8 @@ export interface AgentEvalRunListItem {
experimentId?: string | null;
experimentName?: string;
failCount?: number;
+ /** True when saved attempt evidence is incomplete or contains execution/Judge errors. */
+ hasUnverifiedAttempts?: boolean;
id: string;
metrics?: EvalRunMetrics | null;
name?: string | null;
diff --git a/packages/types/src/eval/datasetPackage.ts b/packages/types/src/eval/datasetPackage.ts
new file mode 100644
index 00000000000..929ddced029
--- /dev/null
+++ b/packages/types/src/eval/datasetPackage.ts
@@ -0,0 +1,95 @@
+import type { EvalCaseEnvironment, EvalConnectorBindings, EvalTestCaseContent } from './agentEval';
+import type { RubricType } from './rubric';
+
+export type AgentEvalDatasetPackageEnvironment = Omit<EvalCaseEnvironment, 'connectorBindings'>;
+
+export interface AgentEvalDatasetPackageConnection {
+ credentials?:
+ { token: string; type: 'bearer' } | { headers: Record<string, string>; type: 'header' };
+ name: string;
+ url: string;
+}
+
+export type AgentEvalDatasetPackageConnectionBindings = Record<
+ string,
+ { connectionKey: string; transport?: 'mcp' | 'lobe-bench' }
+>;
+
+export interface AgentEvalDatasetPackageBindings {
+ caseBindings?: Record<string, EvalConnectorBindings>;
+ environmentBindings?: Record<string, EvalConnectorBindings>;
+}
+
+export interface AgentEvalDatasetPackageConnectionRequirement {
+ key: string;
+ name: string;
+ providedServices?: string[];
+ scope: 'environment' | 'case';
+ services: string[];
+}
+
+/** Editable installed targets. Keys are local environment/case IDs, not archive keys. */
+export interface AgentEvalDatasetConnectorRequirement {
+ bindings: EvalConnectorBindings;
+ key: string;
+ name: string;
+ scope: 'environment' | 'case';
+ services: string[];
+}
+
+/** Private packages may provision connections; installed IDs and ownership are never imported. */
+export interface AgentEvalDatasetPackage {
+ cases: Array<{
+ connectionBindings?: AgentEvalDatasetPackageConnectionBindings;
+ content: Omit<EvalTestCaseContent, 'environment'> & {
+ environment?: AgentEvalDatasetPackageEnvironment;
+ };
+ environmentKey?: string;
+ evalConfig?: Record<string, unknown>;
+ evalMode?: RubricType;
+ key: string;
+ metadata?: {
+ category?: string;
+ difficulty?: 'easy' | 'hard' | 'medium';
+ index?: number;
+ tags?: string[];
+ };
+ sortOrder?: number;
+ }>;
+ connections?: Record<string, AgentEvalDatasetPackageConnection>;
+ dataset: {
+ description?: string;
+ evalConfig?: Record<string, unknown>;
+ evalMode?: RubricType;
+ metadata?: {
+ mock?: {
+ connectors?: Record<string, { avatar?: string; description?: string; title?: string }>;
+ dataset: string;
+ };
+ presentation?: string;
+ release?: string;
+ };
+ name: string;
+ };
+ environments: Array<{
+ connectionBindings?: AgentEvalDatasetPackageConnectionBindings;
+ config: AgentEvalDatasetPackageEnvironment;
+ description?: string;
+ key: string;
+ name: string;
+ }>;
+ format: 'lobehub-eval-dataset';
+ version: 1;
+}
+
+export interface AgentEvalDatasetPackagePreview {
+ caseCount: number;
+ connectionRequirements: AgentEvalDatasetPackageConnectionRequirement[];
+ description?: string;
+ embeddedConnections?: Array<{ authConfigured: boolean; key: string; name: string }>;
+ environmentCount: number;
+ mockServices: string[];
+ name: string;
+ release?: string;
+ version: 1;
+}
diff --git a/packages/types/src/eval/environmentConnection.ts b/packages/types/src/eval/environmentConnection.ts
new file mode 100644
index 00000000000..b030e46381b
--- /dev/null
+++ b/packages/types/src/eval/environmentConnection.ts
@@ -0,0 +1,38 @@
+import type { EvalCaseEnvironment } from './agentEval';
+
+const PREFIX = 'env:';
+
+/** The connector id a binding uses for a connection stored in an Environment. */
+export const environmentConnectionId = (environmentId: string, service: string) =>
+ `${PREFIX}${environmentId}:${service}`;
+
+/** The Environment and service an `env:` connector id names, or undefined for a connector row. */
+export const parseEnvironmentConnectionId = (
+ connectorId: string,
+): { environmentId: string; service: string } | undefined => {
+ if (!connectorId.startsWith(PREFIX)) return;
+ const rest = connectorId.slice(PREFIX.length);
+ const separator = rest.indexOf(':');
+ if (separator <= 0 || separator === rest.length - 1) return;
+ return { environmentId: rest.slice(0, separator), service: rest.slice(separator + 1) };
+};
+
+/** An Environment config as it may leave the server: connection credentials removed. */
+export const redactEnvironmentConnections = <T extends EvalCaseEnvironment | null | undefined>(
+ config: T,
+): T => {
+ if (!config?.connections) return config;
+ return {
+ ...config,
+ connections: Object.fromEntries(
+ Object.entries(config.connections).map(([service, connection]) => [
+ service,
+ {
+ hasCredentials: !!connection.credentials,
+ ...(connection.name && { name: connection.name }),
+ url: connection.url,
+ },
+ ]),
+ ),
+ };
+};
diff --git a/packages/types/src/eval/evalMemory.ts b/packages/types/src/eval/evalMemory.ts
index ae573482f8f..27e81aee829 100644
--- a/packages/types/src/eval/evalMemory.ts
+++ b/packages/types/src/eval/evalMemory.ts
@@ -1,6 +1,97 @@
-/** Memory categories retained as evidence for an evaluation attempt. */
+/**
+ * Native Memory inputs for an eval attempt. Each collection is validated
+ * against its corresponding memory-user-memory input schema on the server.
+ * Owner ids and vectors are deliberately not part of this transport contract.
+ */
+export interface EvalMemoryFixture {
+ activities?: Record<string, unknown>[];
+ contexts?: Record<string, unknown>[];
+ experiences?: Record<string, unknown>[];
+ identities?: Record<string, unknown>[];
+ persona?: { narrative: string; tagline?: string };
+ preferences?: Record<string, unknown>[];
+ /**
+ * ISO 8601 instant the seeded rows were "remembered". Memory writes stamp
+ * the wall clock, but `timeIntent` filters by that clock, so a case that
+ * tells the Agent a fixed session date must pin its fixture rows to it.
+ */
+ seededAt?: string;
+}
+
+/**
+ * Which attempt's Memory the Memory tool and persona injection read and
+ * write: the attempt's own store, never the caller's memories. Server-authored
+ * when the attempt starts; never a tool argument.
+ */
+export interface EvalMemoryReference {
+ fixtureHash: string;
+ runId: string;
+ /** A pass@k attempt is one thread; a topic-level attempt owns its sub-agent threads. */
+ threadId?: string;
+ topicId: string;
+}
+
export type EvalMemoryLayer =
'activity' | 'context' | 'experience' | 'identity' | 'persona' | 'preference';
/** Whether an entry came from the initial fixture or the running Agent. */
export type EvalMemorySource = 'agent' | 'fixture';
+
+/** One Memory entry of an attempt: seeded from the case fixture, or written by the Agent. */
+export interface EvalMemoryEntry {
+ /** ISO 8601; the fixture's `seededAt` for seeded rows, the wall clock for the Agent's writes. */
+ capturedAt: string;
+ details?: string | null;
+ id: string;
+ layer: EvalMemoryLayer;
+ memoryCategory?: string | null;
+ memoryType?: string | null;
+ /** The layer-specific part of the entry (`withPreference`, `withContext`, …; the persona text). */
+ payload: Record<string, unknown>;
+ /** Set when the Agent removed the entry (identities only); kept as evidence. */
+ removedReason?: string | null;
+ source: 'agent' | 'fixture';
+ summary?: string | null;
+ tags?: string[] | null;
+ title?: string | null;
+}
+
+/** The attempt's Memory at the end of the attempt, retained as eval evidence. */
+export interface EvalMemorySnapshot {
+ attemptId: string;
+ entries: EvalMemoryEntry[];
+ /** Null for legacy attempts whose initial fixture provenance was not recorded. */
+ fixtureHash: string | null;
+ /**
+ * `simplified` when the account had no usable embedding model: entries were
+ * stored without vectors and searched without semantic ranking. Absent when
+ * the attempt used the account's embedding model.
+ */
+ retrieval?: 'simplified';
+}
+
+/** Stored attempt memory, including the ownership and vector fields omitted from UI snapshots. */
+export interface AgentEvalMemoryItem {
+ accessedAt: Date;
+ attemptId: string;
+ capturedAt: Date;
+ createdAt: Date;
+ details: string | null;
+ embedding: number[] | null;
+ fixtureHash: string | null;
+ id: string;
+ layer: EvalMemoryLayer;
+ memoryCategory: string | null;
+ memoryType: string | null;
+ payload: Record<string, unknown>;
+ removedReason: string | null;
+ runId: string;
+ source: 'agent' | 'fixture';
+ summary: string | null;
+ tags: string[] | null;
+ threadId: string | null;
+ title: string | null;
+ topicId: string | null;
+ updatedAt: Date;
+ userId: string;
+}
diff --git a/packages/types/src/eval/index.ts b/packages/types/src/eval/index.ts
index 3f58feef238..0de66c7f121 100644
--- a/packages/types/src/eval/index.ts
+++ b/packages/types/src/eval/index.ts
@@ -1,10 +1,15 @@
export * from './agentEval';
export * from './agentEvalDataset';
+export * from './agentEvalEnvironment';
export * from './agentEvalExperiment';
export * from './agentEvalRun';
export * from './benchmark';
export * from './dataset';
+export * from './datasetPackage';
+export * from './environmentConnection';
export * from './evalMemory';
export * from './evaluation';
export * from './ragas';
+export * from './rows';
export * from './rubric';
+export * from './toolManifest';
diff --git a/packages/types/src/eval/rows.ts b/packages/types/src/eval/rows.ts
new file mode 100644
index 00000000000..3fbc0638c26
--- /dev/null
+++ b/packages/types/src/eval/rows.ts
@@ -0,0 +1,39 @@
+import type {
+ EvalCaseEnvironment,
+ EvalConfig,
+ EvalMode,
+ EvalTestCaseContent,
+ EvalTestCaseMetadata,
+} from './agentEval';
+
+/** Persisted case input; omitted nullable fields use their database defaults. */
+export interface AgentEvalTestCaseInsert {
+ accessedAt?: Date;
+ content: EvalTestCaseContent;
+ createdAt?: Date;
+ datasetId: string;
+ environmentId?: string | null;
+ evalConfig?: EvalConfig | null;
+ evalMode?: EvalMode | null;
+ id?: string;
+ metadata?: EvalTestCaseMetadata | null;
+ sortOrder?: number | null;
+ updatedAt?: Date;
+ userId?: string | null;
+ workspaceId?: string | null;
+}
+
+/** Persisted reusable environment input, shared by models and import services. */
+export interface AgentEvalEnvironmentInsert {
+ accessedAt?: Date;
+ config: EvalCaseEnvironment;
+ createdAt?: Date;
+ description?: string | null;
+ id?: string;
+ identifier?: string | null;
+ metadata?: Record<string, unknown> | null;
+ name: string;
+ updatedAt?: Date;
+ userId?: string | null;
+ workspaceId?: string | null;
+}
diff --git a/packages/types/src/eval/rubric.ts b/packages/types/src/eval/rubric.ts
index 758d469ebd3..97c52ab95aa 100644
--- a/packages/types/src/eval/rubric.ts
+++ b/packages/types/src/eval/rubric.ts
@@ -17,6 +17,7 @@ export type RubricType =
| 'python'
// LLM scoring
| 'llm-rubric'
+ | 'rule-checklist'
| 'factuality'
| 'answer-relevance'
// Similarity
diff --git a/packages/types/src/eval/toolManifest.ts b/packages/types/src/eval/toolManifest.ts
new file mode 100644
index 00000000000..cda4546feb0
--- /dev/null
+++ b/packages/types/src/eval/toolManifest.ts
@@ -0,0 +1,45 @@
+import { z } from 'zod';
+
+import { LobeChatPluginApiSchema, MetaSchema } from '../tool/builtin';
+
+/** Model-facing contract only. Addresses, credentials and execution routing live in bindings. */
+export const evalToolManifestSchema = z
+ .object({
+ api: z
+ .array(
+ LobeChatPluginApiSchema.pick({ name: true, description: true, parameters: true })
+ .strict()
+ .refine(
+ (api) => !api.name.includes('____'),
+ 'Tool names cannot contain the routing separator',
+ ),
+ )
+ .min(1),
+ identifier: z
+ .string()
+ .min(1)
+ .max(255)
+ .refine(
+ (id) => !id.includes('____'),
+ 'Tool identifiers cannot contain the routing separator',
+ ),
+ meta: MetaSchema,
+ systemRole: z.string().optional(),
+ type: z.enum(['builtin', 'default', 'markdown', 'mcp', 'standalone']).optional(),
+ })
+ .strict()
+ .refine(
+ (manifest) => new Set(manifest.api.map((api) => api.name)).size === manifest.api.length,
+ 'Tool names must be unique within a contract',
+ );
+
+export const evalToolManifestsSchema = z
+ .record(z.string().min(1).max(255), evalToolManifestSchema)
+ .refine(
+ (manifests) =>
+ Object.entries(manifests).every(([key, manifest]) => key === manifest.identifier),
+ 'Tool contract keys must match their identifiers',
+ );
+
+export type EvalToolManifest = z.infer<typeof evalToolManifestSchema>;
+export type EvalToolManifests = Record<string, EvalToolManifest>;
diff --git a/packages/types/src/tool/plugin.ts b/packages/types/src/tool/plugin.ts
index 360155e5030..ba7e9cbd005 100644
--- a/packages/types/src/tool/plugin.ts
+++ b/packages/types/src/tool/plugin.ts
@@ -31,6 +31,13 @@ export interface CustomPluginParams {
};
description?: string;
enableSettings?: boolean;
+ /**
+ * Set on the mock connectors Lobe Bench installs for an account from a
+ * benchmark's mock service: the discovery URL the manifest was read from.
+ * A run refreshes the plugin when its cases point at another URL and never
+ * touches plugins without this marker.
+ */
+ lobeBench?: { url: string };
manifestMode?: 'local' | 'url';
manifestUrl?: string;
/**
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index e77bd62c470..07f7a14932b 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -180,6 +180,8 @@ export interface ChatTopicMetadata {
editingGroupId?: string;
/** Restored-history tail used as the source message for eval attempt threads. */
evalHistoryTailMessageId?: string;
+ /** Immutable initial Memory hashes keyed by run/topic/thread attempt ID, including empty fixtures. */
+ evalMemoryFixtures?: Record<string, string>;
/**
* Scoped pointer to the currently active assistant message for a running
* heterogeneous agent operation. Includes `operationId` so cold-start