π€― 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
π fix: allow verifier to read task documents (#17593)
Arvin Xu6313e543b7f5
diff --git a/apps/server/src/services/verify/__tests__/agentVerifier.test.ts b/apps/server/src/services/verify/__tests__/agentVerifier.test.tsindex fa3755d2b9e..682e7a80188 100644--- a/apps/server/src/services/verify/__tests__/agentVerifier.test.ts+++ b/apps/server/src/services/verify/__tests__/agentVerifier.test.ts@@ -1,4 +1,5 @@import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';import { VerifyToolIdentifier } from '@lobechat/builtin-tool-verify';import type { VerifyCheckItem } from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -11,13 +12,17 @@ import { createVerifierAgentRunner } from '../agentVerifier';const {existsByIdMock,getBuiltinAgentMock,+ getPinnedDocumentsMock,+ associateDocumentMock,threadCreateMock,execAgentMock,settleVerifierCheckFromTerminalMock,} = vi.hoisted(() => ({execAgentMock: vi.fn(async (_params: any) => ({ operationId: 'verifier-op-1' })),+ associateDocumentMock: vi.fn(),existsByIdMock: vi.fn(),getBuiltinAgentMock: vi.fn(),+ getPinnedDocumentsMock: vi.fn(),settleVerifierCheckFromTerminalMock: vi.fn(),threadCreateMock: vi.fn(async () => ({ id: 'thread-1' })),}));@@ -38,6 +43,14 @@ vi.mock('@/database/models/agent', () => ({vi.mock('@/database/models/thread', () => ({ThreadModel: vi.fn().mockImplementation(() => ({ create: threadCreateMock })),}));+vi.mock('@/database/models/task', () => ({+ TaskModel: vi.fn().mockImplementation(() => ({ getPinnedDocuments: getPinnedDocumentsMock })),+}));+vi.mock('@/server/services/agentDocuments', () => ({+ AgentDocumentsService: vi+ .fn()+ .mockImplementation(() => ({ associateDocument: associateDocumentMock })),+}));// The runner dynamically imports AiAgentService to break a static cycle.vi.mock('@/server/services/aiAgent', () => ({AiAgentService: vi.fn().mockImplementation(() => ({ execAgent: execAgentMock })),@@ -64,6 +77,7 @@ const baseParams = {deliverable: 'the toolbar',model: 'gpt-parent',provider: 'openai',+ taskId: 'task-1',topicId: 'topic-1',userId: 'u',};@@ -73,6 +87,7 @@ describe('createVerifierAgentRunner', () => {vi.clearAllMocks();threadCreateMock.mockResolvedValue({ id: 'thread-1' });execAgentMock.mockResolvedValue({ operationId: 'verifier-op-1' });+ getPinnedDocumentsMock.mockResolvedValue([]);});it('returns undefined without a topicId (no thread to host the verifier)', () => {@@ -174,6 +189,37 @@ describe('createVerifierAgentRunner', () => {expect(execParams().slug).toBe(BUILTIN_AGENT_SLUGS.verifyAgent);});+ it('keeps the parent task scope so the verifier can read its pinned documents', async () => {+ getBuiltinAgentMock.mockResolvedValue({ id: 'builtin-verify' });++ const runner = createVerifierAgentRunner({ ...baseParams })!;+ await runner(runnerArgs);++ expect(execParams().appContext).toEqual({+ taskId: 'task-1',+ threadId: 'thread-1',+ topicId: 'topic-1',+ });+ });++ it('associates pinned task documents with the verifier and supplies readable ids', async () => {+ getBuiltinAgentMock.mockResolvedValue({ id: 'builtin-verify' });+ getPinnedDocumentsMock.mockResolvedValue([+ { documentId: 'docs-manuscript' },+ { documentId: 'docs-notes' },+ ]);+ associateDocumentMock+ .mockResolvedValueOnce({ id: 'agent-doc-manuscript' })+ .mockResolvedValueOnce({ id: 'agent-doc-notes' });++ const runner = createVerifierAgentRunner({ ...baseParams })!;+ await runner(runnerArgs);++ expect(associateDocumentMock).toHaveBeenNthCalledWith(1, 'builtin-verify', 'docs-manuscript');+ expect(associateDocumentMock).toHaveBeenNthCalledWith(2, 'builtin-verify', 'docs-notes');+ expect(execParams().additionalPluginIds).toEqual([AgentDocumentsIdentifier]);+ });+it('injects the builder-captured evidence into the verifier prompt', async () => {getBuiltinAgentMock.mockResolvedValue({ id: 'builtin-verify' });diff --git a/apps/server/src/services/verify/agentVerifier.ts b/apps/server/src/services/verify/agentVerifier.tsindex 5c114597086..a817cd1b68a 100644--- a/apps/server/src/services/verify/agentVerifier.ts+++ b/apps/server/src/services/verify/agentVerifier.ts@@ -1,18 +1,21 @@import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';import { VerifyToolIdentifier } from '@lobechat/builtin-tool-verify';-import type { VerifyCheckItem } from '@lobechat/types';+import type { VerifierTaskDocument } from '@lobechat/prompts';+import { buildVerifierPrompt } from '@lobechat/prompts';import { ThreadType } from '@lobechat/types';import debug from 'debug';import { AgentModel } from '@/database/models/agent';import { DocumentModel } from '@/database/models/document';+import { TaskModel } from '@/database/models/task';import { ThreadModel } from '@/database/models/thread';import type { LobeChatDatabase } from '@/database/type';+import { AgentDocumentsService } from '@/server/services/agentDocuments';import type { AgentHook, AgentHookEvent } from '@/server/services/agentRuntime/hooks/types';import { AiAgentService } from '@/server/services/aiAgent';import type { VerifierAgentRunner } from './executor';-import { describeEvidence, type JudgeEvidence } from './prompts';import { settleVerifierCheckFromTerminal } from './verifierTerminal';const log = debug('lobe-server:verify-agent-verifier');@@ -26,30 +29,6 @@ const log = debug('lobe-server:verify-agent-verifier');* verifier judges against the run goal AND this evidence β it's the verifier's* primary Data, not a competing verdict.*/-export const buildVerifierPrompt = (params: {- checkItem: VerifyCheckItem;- deliverable: string;- evidence?: JudgeEvidence[];- goal: string;- instruction?: string;-}): string => {- const { checkItem, deliverable, evidence, goal, instruction } = params;- const capturedEvidence = describeEvidence(evidence);- return [- `## Check to verify\ncheckItemId: ${checkItem.id}\nTitle: ${checkItem.title}`,- checkItem.description ? `Summary: ${checkItem.description}` : '',- instruction ? `\n## Judging instruction\n${instruction}` : '',- `\n## Run goal\n${goal}`,- deliverable ? `\n## Deliverable / final output\n${deliverable}` : '',- capturedEvidence- ? `\n## Captured evidence (builder self-evidence β primary Data, weight above prose)${capturedEvidence}`- : '',- `\n## Your task\nInvestigate whether the deliverable satisfies this check, judging against the run goal and the judging instruction. Weight the captured evidence above as primary Data; gather more yourself only where it's missing or insufficient. When done, call \`submitVerifyResult\` exactly once with checkItemId="${checkItem.id}" and your verdict (passed / failed / uncertain) plus evidence and reasoning.`,- ]- .filter(Boolean)- .join('\n');-};-/*** Build a {@link VerifierAgentRunner} that runs each `agent`-type check as a* **verify agent**: it opens an isolated thread and `execAgent`s (headless) with@@ -73,14 +52,25 @@ export const createVerifierAgentRunner = (params: {/** Verify-safe model selected by the completion lifecycle. */model?: string | null;provider?: string | null;+ /** Parent task scope so the verifier can inspect the task and its pinned documents. */+ taskId?: 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, verifierAgentId, workspaceId } =- params;+ const {+ db,+ deliverable,+ model,+ provider,+ taskId,+ topicId,+ userId,+ verifierAgentId,+ workspaceId,+ } = params;if (!topicId) return undefined;return async ({ checkItem, evidence, goal, operationId }) => {@@ -124,6 +114,23 @@ export const createVerifierAgentRunner = (params: {useProvidedModelConfig = true;}+ let taskDocuments: VerifierTaskDocument[] | undefined;+ if (taskId) {+ const pinnedDocuments = await new TaskModel(db, userId, workspaceId).getPinnedDocuments(+ taskId,+ );+ const agentDocumentsService = new AgentDocumentsService(db, userId, workspaceId);+ taskDocuments = await Promise.all(+ pinnedDocuments.map(async ({ documentId }) => ({+ agentDocumentId: (+ await agentDocumentsService.associateDocument(threadAgentId, documentId)+ ).id,+ documentId,+ })),+ );+ }+ if (taskDocuments?.length) extraPluginIds.push(AgentDocumentsIdentifier);+const thread = await new ThreadModel(db, userId, workspaceId).create({agentId: threadAgentId,title: `Verify: ${checkItem.title}`,@@ -180,7 +187,7 @@ export const createVerifierAgentRunner = (params: {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 },+ appContext: { taskId, threadId: thread.id, topicId },autoStart: true,...(evidenceFileIds.length ? { fileIds: evidenceFileIds } : {}),hooks,@@ -188,7 +195,14 @@ export const createVerifierAgentRunner = (params: {// a pinned agent keeps its own runtime config....(useProvidedModelConfig && model ? { model } : {}),parentOperationId: operationId,- prompt: buildVerifierPrompt({ checkItem, deliverable, evidence, goal, instruction }),+ prompt: buildVerifierPrompt({+ checkItem,+ deliverable,+ evidence,+ goal,+ instruction,+ taskDocuments,+ }),...(useProvidedModelConfig && provider ? { provider } : {}),...agentRef,userInterventionConfig: { approvalMode: 'headless' },diff --git a/apps/server/src/services/verify/lifecycle.ts b/apps/server/src/services/verify/lifecycle.tsindex 4c15cfcfc1b..7e60ca1f7a5 100644--- a/apps/server/src/services/verify/lifecycle.ts+++ b/apps/server/src/services/verify/lifecycle.ts@@ -87,6 +87,7 @@ export const runVerifyOnCompletion = async (deliverable: params.deliverable,model: modelConfig.model,provider: modelConfig.provider,+ taskId: op.taskId,topicId: op.topicId,userId,verifierAgentId,diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.tsindex 37c65fba23a..23c4784923d 100644--- a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts@@ -86,7 +86,7 @@ describe('AgentDocumentModel', () => {expect(row?.policyLoad).toBe(PolicyLoad.PROGRESSIVE);});- it('should be idempotent (onConflictDoNothing)', async () => {+ it('should return the existing binding id after an association conflict', async () => {const [doc] = await serverDB.insert(documents).values({@@ -106,8 +106,33 @@ describe('AgentDocumentModel', () => {const second = await agentDocumentModel.associate({ agentId, documentId: doc!.id });expect(first.id).toBeDefined();- // Second call should not throw, id may be undefined due to onConflictDoNothing- expect(second).toBeDefined();+ expect(second.id).toBe(first.id);+ });++ it('should return one stable binding id to concurrent association callers', async () => {+ const [doc] = await serverDB+ .insert(documents)+ .values({+ content: 'content',+ fileType: 'article',+ filename: 'concurrent.html',+ source: 'https://example.com/concurrent',+ sourceType: 'web',+ title: 'Concurrent Page',+ totalCharCount: 7,+ totalLineCount: 1,+ userId,+ })+ .returning();++ const results = await Promise.all(+ Array.from({ length: 3 }, () =>+ agentDocumentModel.associate({ agentId, documentId: doc!.id }),+ ),+ );++ expect(new Set(results.map(({ id }) => id))).toEqual(new Set([results[0].id]));+ expect(results[0].id).not.toBe('');});it('should not create documents row β only the link', async () => {diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.tsindex c170f981631..10579a3a21f 100644--- a/packages/database/src/models/agentDocuments/agentDocument.ts+++ b/packages/database/src/models/agentDocuments/agentDocument.ts@@ -256,7 +256,8 @@ export class AgentDocumentModel {* - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.** Returns:- * - The inserted agent document binding id, or an empty id when the source document is missing.+ * - The inserted or existing agent document binding id.+ * - An empty id only when the source document is missing.**/async associate(params: {@@ -298,7 +299,24 @@ export class AgentDocumentModel {.onConflictDoNothing().returning({ id: agentDocuments.id });- return { id: result?.id };+ if (result) return result;++ // A concurrent caller (or an earlier run) may already own this unique+ // agent/document binding. The conflict loser must resolve that row instead+ // of leaking `undefined` to callers that need the binding id.+ const [existing] = await trx+ .select({ id: agentDocuments.id })+ .from(agentDocuments)+ .where(+ and(+ this.agentDocOwnership(),+ eq(agentDocuments.agentId, agentId),+ eq(agentDocuments.documentId, documentId),+ ),+ )+ .limit(1);++ return { id: existing?.id ?? '' };});}diff --git a/packages/file-loaders/src/loadFile.test.ts b/packages/file-loaders/src/loadFile.test.tsindex cea88c799ae..47651307a9b 100644--- a/packages/file-loaders/src/loadFile.test.ts+++ b/packages/file-loaders/src/loadFile.test.ts@@ -31,7 +31,7 @@ describe('loadFile', () => {expect(doc.source).toBe(file);expect(doc.content).toContain('123');expect(doc.pages && doc.pages.length).toBeGreaterThan(0);- });+ }, 15_000);it('returns error page when fs.stat fails', async () => {const doc = await loadFile('/not/exists.xyz');diff --git a/packages/file-loaders/test/loaders.test.ts b/packages/file-loaders/test/loaders.test.tsindex ecc30b4b51c..c8b0283ca55 100644--- a/packages/file-loaders/test/loaders.test.ts+++ b/packages/file-loaders/test/loaders.test.ts@@ -55,6 +55,6 @@ describe('loadFile Integration Tests', () => {// @ts-expect-errordelete docs.modifiedTime;expect(docs).toMatchSnapshot();- });+ }, 15_000);});});diff --git a/packages/prompts/src/prompts/index.ts b/packages/prompts/src/prompts/index.tsindex c011e78e7a4..63fe43b3319 100644--- a/packages/prompts/src/prompts/index.ts+++ b/packages/prompts/src/prompts/index.ts@@ -22,3 +22,4 @@ export * from './systemRole';export * from './task';export * from './toolDiscovery';export * from './userMemory';+export * from './verify';diff --git a/packages/prompts/src/prompts/verify/index.test.ts b/packages/prompts/src/prompts/verify/index.test.tsnew file mode 100644index 00000000000..2d88cbe79a2--- /dev/null+++ b/packages/prompts/src/prompts/verify/index.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest';++import { buildVerifierPrompt } from './index';++const checkItem = {+ id: 'check-1',+ index: 0,+ onFail: 'manual' as const,+ required: true,+ title: 'Read the manuscript',+ verifierConfig: {},+ verifierType: 'agent' as const,+};++describe('buildVerifierPrompt', () => {+ it('distinguishes readable agent document ids from backing document ids', () => {+ const prompt = buildVerifierPrompt({+ checkItem,+ deliverable: 'Draft complete',+ goal: 'Write a novel',+ taskDocuments: [+ {+ agentDocumentId: 'agent-doc-manuscript',+ documentId: 'docs-manuscript',+ },+ ],+ });++ expect(prompt).toContain('## Task documents');+ expect(prompt).toContain(+ 'agentDocumentId: agent-doc-manuscript (backing documentId: docs-manuscript)',+ );+ expect(prompt).toContain('Use `lobe-agent-documents.readDocument` with the `agentDocumentId`');+ });++ it('omits the task document section when no documents are available', () => {+ const prompt = buildVerifierPrompt({+ checkItem,+ deliverable: 'Done',+ goal: 'Ship it',+ });++ expect(prompt).not.toContain('## Task documents');+ });+});diff --git a/packages/prompts/src/prompts/verify/index.ts b/packages/prompts/src/prompts/verify/index.tsnew file mode 100644index 00000000000..c2d2bec4d44--- /dev/null+++ b/packages/prompts/src/prompts/verify/index.ts@@ -0,0 +1,86 @@+import type { VerifyCheckItem, VerifyEvidenceType } from '@lobechat/types';++export interface VerifierPromptEvidence {+ content?: string | null;+ description?: string | null;+ type: VerifyEvidenceType;+}++export interface VerifierTaskDocument {+ /** Agent-scoped row id accepted by lobe-agent-documents.readDocument. */+ agentDocumentId: string;+ /** Backing documents-table id, included only to disambiguate the two identities. */+ documentId: string;+}++export interface VerifierPromptInput {+ checkItem: VerifyCheckItem;+ deliverable: string;+ evidence?: VerifierPromptEvidence[];+ goal: string;+ instruction?: string;+ taskDocuments?: VerifierTaskDocument[];+}++const describeEvidence = (evidence: VerifierPromptEvidence[] | undefined): string => {+ if (!evidence?.length) return '';++ let items = '';+ for (const item of evidence) {+ const caption = item.description ? ` β ${item.description}` : '';+ const payload = item.content ? `: ${item.content}` : ' [artifact captured]';+ items += `\n - (${item.type})${caption}${payload}`;+ }++ return `\nEvidence captured during the run:${items}`;+};++const describeTaskDocuments = (documents: VerifierTaskDocument[] | undefined): string => {+ if (!documents?.length) return '';++ let items = '';+ for (const { agentDocumentId, documentId } of documents) {+ items += `\n- agentDocumentId: ${agentDocumentId} (backing documentId: ${documentId})`;+ }++ return `+## Task documents+Use \`lobe-agent-documents.readDocument\` with the \`agentDocumentId\` below. Do not pass the backing \`documentId\` as \`id\`.${items}`;+};++export const buildVerifierPrompt = ({+ checkItem,+ deliverable,+ evidence,+ goal,+ instruction,+ taskDocuments,+}: VerifierPromptInput): string => `## Check to verify+checkItemId: ${checkItem.id}+Title: ${checkItem.title}${checkItem.description ? `\nSummary: ${checkItem.description}` : ''}${+ instruction+ ? `++## Judging instruction+${instruction}`+ : ''+}++## Run goal+${goal}${+ deliverable+ ? `++## Deliverable / final output+${deliverable}`+ : ''+}${describeTaskDocuments(taskDocuments)}${+ evidence?.length+ ? `++## Captured evidence (builder self-evidence β primary Data, weight above prose)${describeEvidence(evidence)}`+ : ''+}++## Your task+Investigate whether the deliverable satisfies this check, judging against the run goal and the judging instruction. Weight the captured evidence above as primary Data; gather more yourself only where it's missing or insufficient. When done, call \`submitVerifyResult\` exactly once with checkItemId="${checkItem.id}" and your verdict (passed / failed / uncertain) plus evidence and reasoning.`;