π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ refactor(verify): make the verify agent selectable per task (#16121)
Arvin Xuaff3760ec493
diff --git a/apps/server/src/services/verify/__tests__/agentVerifier.test.ts b/apps/server/src/services/verify/__tests__/agentVerifier.test.tsnew file mode 100644index 00000000000..c889b70e89c--- /dev/null+++ b/apps/server/src/services/verify/__tests__/agentVerifier.test.ts@@ -0,0 +1,120 @@+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { VerifyToolIdentifier } from '@lobechat/builtin-tool-verify';+import type { VerifyCheckItem } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createVerifierAgentRunner } from '../agentVerifier';++// AgentModel/ThreadModel expose their methods as arrow-function class fields+// (instance props, not on the prototype), so they can't be spied via the+// prototype β mock the modules instead. Hoisted so the factories can close over them.+const { existsByIdMock, getBuiltinAgentMock, threadCreateMock, execAgentMock } = vi.hoisted(() => ({+ execAgentMock: vi.fn(async (_params: any) => ({ operationId: 'verifier-op-1' })),+ existsByIdMock: vi.fn(),+ getBuiltinAgentMock: vi.fn(),+ threadCreateMock: vi.fn(async () => ({ id: 'thread-1' })),+}));++/** The single execAgent param object, asserted to exist. */+const execParams = (): any => {+ const call = execAgentMock.mock.calls[0];+ expect(call).toBeDefined();+ return call![0];+};++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(() => ({+ existsById: existsByIdMock,+ getBuiltinAgent: getBuiltinAgentMock,+ })),+}));+vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(() => ({ create: threadCreateMock })),+}));+// The runner dynamically imports AiAgentService to break a static cycle.+vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: vi.fn().mockImplementation(() => ({ execAgent: execAgentMock })),+}));++const checkItem: VerifyCheckItem = {+ id: 'check-1',+ index: 0,+ onFail: 'manual',+ required: true,+ title: 'Toolbar renders',+ verifierConfig: {},+ verifierType: 'agent',+};++const runnerArgs = { checkItem, goal: 'ship the toolbar', operationId: 'parent-op-1' };+const db = {} as any;++const baseParams = {+ db,+ deliverable: 'the toolbar',+ model: 'gpt-parent',+ provider: 'openai',+ topicId: 'topic-1',+ userId: 'u',+};++describe('createVerifierAgentRunner', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ threadCreateMock.mockResolvedValue({ id: 'thread-1' });+ execAgentMock.mockResolvedValue({ operationId: 'verifier-op-1' });+ });++ it('returns undefined without a topicId (no thread to host the verifier)', () => {+ const runner = createVerifierAgentRunner({ db, deliverable: 'x', topicId: null, userId: 'u' });+ expect(runner).toBeUndefined();+ });++ it('runs a pinned agent by agentId, keeping its own model/provider', async () => {+ existsByIdMock.mockResolvedValue(true);++ const runner = createVerifierAgentRunner({ ...baseParams, verifierAgentId: 'agent-codex' })!;+ const result = await runner(runnerArgs);++ expect(result).toEqual({ verifierOperationId: 'verifier-op-1' });+ expect(existsByIdMock).toHaveBeenCalledWith('agent-codex');+ expect(getBuiltinAgentMock).not.toHaveBeenCalled();++ const params = execParams();+ expect(params.agentId).toBe('agent-codex');+ // A pinned agent keeps its own agency β never overridden by the parent run.+ expect(params.slug).toBeUndefined();+ expect(params.model).toBeUndefined();+ expect(params.provider).toBeUndefined();+ // A pinned agent lacks the writeback tool, so it must be injected.+ expect(params.additionalPluginIds).toEqual([VerifyToolIdentifier]);+ });++ it('falls back to the builtin verify agent (by slug) inheriting parent model/provider', async () => {+ existsByIdMock.mockResolvedValue(false); // pinned id no longer exists+ getBuiltinAgentMock.mockResolvedValue({ id: 'builtin-verify' });++ const runner = createVerifierAgentRunner({ ...baseParams, verifierAgentId: 'agent-deleted' })!;+ await runner(runnerArgs);++ expect(getBuiltinAgentMock).toHaveBeenCalledWith(BUILTIN_AGENT_SLUGS.verifyAgent);+ const params = execParams();+ expect(params.slug).toBe(BUILTIN_AGENT_SLUGS.verifyAgent);+ expect(params.agentId).toBeUndefined();+ expect(params.model).toBe('gpt-parent');+ expect(params.provider).toBe('openai');+ // The builtin verify agent already declares the tool β not re-injected.+ expect(params.additionalPluginIds).toBeUndefined();+ });++ it('uses the builtin agent when no verifierAgentId is pinned', async () => {+ getBuiltinAgentMock.mockResolvedValue({ id: 'builtin-verify' });++ const runner = createVerifierAgentRunner({ ...baseParams })!;+ await runner(runnerArgs);++ // No pinned id β never probes existsById, goes straight to the builtin.+ expect(existsByIdMock).not.toHaveBeenCalled();+ expect(execParams().slug).toBe(BUILTIN_AGENT_SLUGS.verifyAgent);+ });+});diff --git a/apps/server/src/services/verify/agentVerifier.ts b/apps/server/src/services/verify/agentVerifier.tsindex 8ad106799f0..f48383e5d90 100644--- a/apps/server/src/services/verify/agentVerifier.ts+++ b/apps/server/src/services/verify/agentVerifier.ts@@ -1,4 +1,5 @@import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { VerifyToolIdentifier } from '@lobechat/builtin-tool-verify';import type { VerifyCheckItem } from '@lobechat/types';import { ThreadType } from '@lobechat/types';import debug from 'debug';@@ -37,24 +38,35 @@ export const buildVerifierPrompt = (params: {};/**- * Build a {@link VerifierAgentRunner} that runs each `agent`-type check as the- * dedicated builtin **verify agent**: it materializes the verify agent, opens an- * isolated thread, and `execAgent`s (headless) with the check context (incl.- * `checkItemId`) injected into the prompt. The verify agent investigates and- * writes its verdict back via the `submitVerifyResult` tool during its run β no- * document creation, no output parsing, no external completion hook.+ * Build a {@link VerifierAgentRunner} that runs each `agent`-type check as a+ * **verify agent**: it opens an isolated thread and `execAgent`s (headless) with+ * the check context (incl. `checkItemId`) injected into the prompt. The verify+ * agent investigates and writes its verdict back via the `submitVerifyResult`+ * tool during its run β no document creation, no output parsing, no external+ * completion hook.+ *+ * Which agent runs is selectable: when the task pins a `verifierAgentId`+ * (`TaskVerifyConfig.verifierAgentId`) that agent runs under its OWN agency+ * config (executionTarget / device / provider) β so picking a heterogeneous+ * agent (e.g. Codex) naturally gives the verifier device + browser access. When+ * unset (or the pinned agent no longer exists) it falls back to the builtin+ * verify agent, which inherits the parent run's model/provider (its own default+ * may not point at a configured provider).*/export const createVerifierAgentRunner = (params: {db: LobeChatDatabase;deliverable: string;- /** Inherit the parent run's model so the verifier uses a configured provider. */+ /** Inherit the parent run's model so the builtin fallback uses a configured provider. */model?: string | null;provider?: string | null;topicId?: string | null;userId: string;+ /** Task-pinned verify agent. Falls back to the builtin verify agent when unset/missing. */+ verifierAgentId?: string | null;workspaceId?: string;}): VerifierAgentRunner | undefined => {- const { db, deliverable, model, provider, topicId, userId, workspaceId } = params;+ const { db, deliverable, model, provider, topicId, userId, verifierAgentId, workspaceId } =+ params;if (!topicId) return undefined;return async ({ checkItem, goal, operationId }) => {@@ -64,17 +76,42 @@ export const createVerifierAgentRunner = (params: {?.content ?? undefined): undefined;- // Materialize the builtin verify agent (idempotent) to get an id for the thread.- const verifyAgent = await new AgentModel(db, userId, workspaceId).getBuiltinAgent(- BUILTIN_AGENT_SLUGS.verifyAgent,- );- if (!verifyAgent) {- log('verify agent unavailable, cannot run agent verifier for check %s', checkItem.id);- return null;+ const agentModel = new AgentModel(db, userId, workspaceId);++ // Resolve which agent verifies. A pinned agent runs as itself (`agentId`) so+ // its own agency config drives execution target/provider β we don't override+ // its model/provider. The builtin fallback runs by `slug` and inherits the+ // parent run's model/provider.+ let threadAgentId: string;+ let agentRef: { agentId: string } | { slug: string };+ let inheritModel = false;+ // A pinned agent (selected for its runtime/device) carries only its own+ // configured plugins, so it lacks the verify writeback tool β inject it, else+ // the verdict never lands and the check result is stuck `running`. The builtin+ // verify agent already declares this tool in its plugins, so it isn't re-added.+ let extraPluginIds: string[] = [];++ if (verifierAgentId && (await agentModel.existsById(verifierAgentId))) {+ threadAgentId = verifierAgentId;+ agentRef = { agentId: verifierAgentId };+ extraPluginIds = [VerifyToolIdentifier];+ } else {+ if (verifierAgentId) {+ log('pinned verify agent %s not found, falling back to builtin', verifierAgentId);+ }+ // Materialize the builtin verify agent (idempotent) to get an id for the thread.+ const builtin = await agentModel.getBuiltinAgent(BUILTIN_AGENT_SLUGS.verifyAgent);+ if (!builtin) {+ log('verify agent unavailable, cannot run agent verifier for check %s', checkItem.id);+ return null;+ }+ threadAgentId = builtin.id;+ agentRef = { slug: BUILTIN_AGENT_SLUGS.verifyAgent };+ inheritModel = true;}const thread = await new ThreadModel(db, userId, workspaceId).create({- agentId: verifyAgent.id,+ agentId: threadAgentId,title: `Verify: ${checkItem.title}`,topicId,type: ThreadType.Isolation,@@ -88,15 +125,17 @@ export const createVerifierAgentRunner = (params: {// β verify lifecycle β this runner β aiAgent.const { AiAgentService } = await import('@/server/services/aiAgent');const result = await new AiAgentService(db, userId, { workspaceId }).execAgent({+ // Inject the verify writeback tool for pinned agents (no-op list otherwise).+ ...(extraPluginIds.length ? { additionalPluginIds: extraPluginIds } : {}),appContext: { threadId: thread.id, topicId },autoStart: true,- // Inherit the parent run's model/provider so the verifier uses a provider- // that's actually configured (the builtin agent's default may not be).- ...(model ? { model } : {}),+ // Only the builtin fallback inherits the parent run's model/provider; a+ // pinned agent keeps its own (critical for heterogeneous runtimes).+ ...(inheritModel && model ? { model } : {}),parentOperationId: operationId,prompt: buildVerifierPrompt({ checkItem, deliverable, goal, instruction }),- ...(provider ? { provider } : {}),- slug: BUILTIN_AGENT_SLUGS.verifyAgent,+ ...(inheritModel && provider ? { provider } : {}),+ ...agentRef,userInterventionConfig: { approvalMode: 'headless' },});diff --git a/apps/server/src/services/verify/lifecycle.ts b/apps/server/src/services/verify/lifecycle.tsindex 8763948be09..818633c7725 100644--- a/apps/server/src/services/verify/lifecycle.ts+++ b/apps/server/src/services/verify/lifecycle.ts@@ -1,6 +1,7 @@import debug from 'debug';import { AgentOperationModel } from '@/database/models/agentOperation';+import { TaskModel } from '@/database/models/task';import type { LobeChatDatabase } from '@/database/type';import { createVerifierAgentRunner } from './agentVerifier';@@ -49,14 +50,24 @@ export const runVerifyOnCompletion = async (return;}+ // Task-bound runs may pin which agent verifies (TaskVerifyConfig.verifierAgentId,+ // with subtask inheritance). Non-task runs leave it undefined β builtin fallback.+ let verifierAgentId: string | undefined;+ if (op.taskId) {+ const verifyConfig = await new TaskModel(db, userId, workspaceId).resolveVerifyConfig(+ op.taskId,+ );+ verifierAgentId = verifyConfig?.verifierAgentId ?? undefined;+ }+const executor = new VerifyExecutorService(db, userId, workspaceId);await executor.execute({deliverable: params.deliverable,goal: params.goal,modelConfig: { model: op.model, provider: op.provider },operationId: params.operationId,- // `agent`-type checks run as the dedicated builtin verify agent, which- // writes its verdict back via the submitVerifyResult tool during its run.+ // `agent`-type checks run as the task-pinned verify agent (or the builtin+ // one), which writes its verdict back via the submitVerifyResult tool.runVerifierAgent: createVerifierAgentRunner({db,deliverable: params.deliverable,@@ -64,6 +75,7 @@ export const runVerifyOnCompletion = async (provider: op.provider,topicId: op.topicId,userId,+ verifierAgentId,workspaceId,}),});