π€― 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
import { randomUUID } from 'node:crypto';
import { TRACING_SCENARIOS } from '@lobechat/const';
import type { TracingOptions } from '@lobechat/llm-generation-tracing';
import { getModelPropertyWithFallback } from '@lobechat/model-runtime';
import {
BATCH_VERDICT_JSON_SCHEMA,
chainVerifyJudge,
type JudgeEvidence,
SINGLE_VERDICT_JSON_SCHEMA,
VERIFY_JUDGE_PROMPT_VERSION,
} from '@lobechat/prompts';
import type {
ToulminVerdict,
VerifyCheckItem,
VerifyCheckResultStatus,
VerifyVerdict,
} from '@lobechat/types';
import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';
import { AiModelModel } from '@/database/models/aiModel';
import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';
import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
import { AiGenerationService } from '@/server/services/aiGeneration';
import { FileService } from '@/server/services/file';
import { settledCarriedItemIds } from './carryForward';
import { resolveCheckInstruction } from './checkInstruction';
import { executionGapTypes, runEvidenceGaps, runEvidenceSpecs } from './evidenceCoverage';
import { planEvidenceVerification } from './evidencePlanner';
import { GIF_FRAME_SHEET_NOTE, isGifFrameSheet, resolveModelReadableFrameUrl } from './modelFrames';
import { planItemToPendingResult } from './resultSnapshot';
import { BatchVerdictSchema, type SingleVerdict, SingleVerdictSchema } from './schema';
import { VerifyStatusService } from './statusService';
import { describeThrownError } from './verifierError';
const log = debug('lobe-server:verify-executor');
/**
* Runs a verifier sub-agent (its own agent operation in an isolated thread) to
* actively investigate one criterion β reading files, running checks β and
* write its verdict back to the check result. Injected by the runtime layer
* because it needs full agent-execution context; when absent the agent item is
* marked skipped.
*/
export interface VerifierAgentRunner {
(args: {
checkItem: VerifyCheckItem;
/** Evidence the builder captured for this item β input to the verifier's judgment. */
evidence?: JudgeEvidence[];
goal: string;
operationId: string;
}): Promise<{ verifierOperationId: string } | null>;
}
export interface ExecuteVerifyParams {
/** Judge all LLM items in one batched generateObject (default true). */
batchLlm?: boolean;
/** The run's final output / artifacts, judged against the criteria. */
deliverable: string;
goal: string;
modelConfig: { model: string; provider: string };
operationId: string;
/** Runs agent checks and program checks without a native runner as verifier sub-agents. */
runVerifierAgent?: VerifierAgentRunner;
}
const verdictToStatus = (verdict: VerifyVerdict): VerifyCheckResultStatus =>
verdict === 'passed' ? 'passed' : 'failed';
const terminalResultStatuses = new Set<VerifyCheckResultStatus>([
'passed',
'failed',
'errored',
'skipped',
]);
/** Group a run's evidence rows by the plan item they back, for judge injection. */
type EvidenceByItem = Map<string, JudgeEvidence[]>;
const toToulmin = (v: SingleVerdict): ToulminVerdict => ({
counterEvidence: v.counterEvidence ?? undefined,
evidence: v.evidence ?? undefined,
limitation: v.limitation ?? undefined,
reasoning: v.reasoning ?? undefined,
});
export class VerifyExecutorService {
private readonly db: LobeChatDatabase;
private readonly userId: string;
private readonly workspaceId?: string;
private readonly runModel: VerifyRunModel;
private readonly resultModel: VerifyCheckResultModel;
private readonly statusService: VerifyStatusService;
private readonly documentModel: DocumentModel;
private readonly evidenceModel: VerifyEvidenceModel;
private readonly fileModel: FileModel;
private readonly fileService: FileService;
private readonly aiModelModel: AiModelModel;
constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
this.db = db;
this.userId = userId;
this.workspaceId = workspaceId;
this.runModel = new VerifyRunModel(db, userId, workspaceId);
this.resultModel = new VerifyCheckResultModel(db, userId, workspaceId);
this.statusService = new VerifyStatusService(db, userId, workspaceId);
this.documentModel = new DocumentModel(db, userId, workspaceId);
this.evidenceModel = new VerifyEvidenceModel(db, userId, workspaceId);
this.fileModel = new FileModel(db, userId, workspaceId);
this.fileService = new FileService(db, userId, workspaceId);
this.aiModelModel = new AiModelModel(db, userId, workspaceId);
}
/** The check item's detailed judging instruction; see {@link resolveCheckInstruction}. */
private resolveInstruction(item: VerifyCheckItem): Promise<string | undefined> {
return resolveCheckInstruction(this.documentModel, item);
}
/**
* Run the confirmed check plan for an operation. LLM items are judged inline;
* program items are placeholders (v1); agent items are spawned via the injected
* spawner (results land asynchronously). Recomputes the rollup at the end.
*/
async execute(params: ExecuteVerifyParams): Promise<void> {
// Resolve (or lazily create) the verification session bound to this Agent Run.
const run = await this.runModel.ensureForOperation(params.operationId);
if (!run.plan?.length) {
log('execute: no plan for op %s, skipping', params.operationId);
return;
}
if (!run.planConfirmedAt) {
log('execute: plan for op %s not confirmed, skipping', params.operationId);
return;
}
const verifyRunId = run.id;
const plan = run.plan as VerifyCheckItem[];
// Idempotently create the pending result rows (skip ones already present β
// an item may already have a row from evidence uploaded mid-run).
const existing = await this.resultModel.listByRun(verifyRunId);
const existingIds = new Set(existing.map((r) => r.checkItemId));
const toCreate = plan
.filter((i) => !existingIds.has(i.id))
.map((item) => planItemToPendingResult(verifyRunId, params.operationId, item));
if (toCreate.length > 0) await this.resultModel.createMany(toCreate);
await this.statusService.markVerifying(params.operationId);
// Load run-captured evidence once, grouped by plan item β feeds both the
// structural gate and the LLM judge.
const evidenceRows = await this.evidenceModel.listByRun(verifyRunId);
const evidenceByItem = await this.loadEvidence(evidenceRows);
// A repair round carries the checks it was not asked to fix (see
// carryPassedResultsForward). Those keep their copied verdict; one the
// builder evidenced again is judged again on old and new evidence together.
const { reopened, settled } = settledCarriedItemIds(existing, evidenceRows);
for (const checkItemId of reopened) {
const result = existing.find((row) => row.checkItemId === checkItemId);
const { carriedFrom, ...metadata } = (result?.metadata ?? {}) as Record<string, unknown>;
await this.resultModel.updateByCheckItem(verifyRunId, checkItemId, {
completedAt: null,
metadata: { ...metadata, reopenedFrom: carriedFrom },
status: 'pending',
verdict: null,
});
}
const items = plan.filter((item) => !settled.has(item.id));
// Structural gate (server, no LLM): an evidence-driven item missing any of
// its declared evidence types is marked uncertain up front and excluded from
// the judges β we never let a required artifact-backed claim pass unseen.
const gapIds = await this.runStructuralGate(verifyRunId, items, evidenceByItem);
const gated = items.filter((i) => !gapIds.has(i.id));
const declaredLlmItems = gated.filter((i) => i.verifierType === 'llm');
const supportsVision = await this.modelSupportsVision(
params.modelConfig.model,
params.modelConfig.provider,
);
const evidencePlans = new Map(
declaredLlmItems.map((item) => [
item.id,
planEvidenceVerification({
evidence: evidenceByItem.get(item.id) ?? [],
item,
modelSupportsVision: supportsVision,
}),
]),
);
const llmItems = declaredLlmItems.filter(
(item) => evidencePlans.get(item.id)?.route !== 'agent',
);
const multimodalItemIds = new Set(
llmItems
.filter((item) => evidencePlans.get(item.id)?.route === 'llm_multimodal')
.map((item) => item.id),
);
const agentItems = [
...gated.filter((i) => i.verifierType === 'agent'),
...declaredLlmItems.filter((item) => evidencePlans.get(item.id)?.route === 'agent'),
];
const programItems = gated.filter((i) => i.verifierType === 'program');
// The verifier kinds are independent β run them concurrently. Program checks
// currently use the verifier agent as an evidence-producing fallback until a
// sandboxed native program runner is available.
await Promise.all([
this.runProgramItems(params, verifyRunId, programItems, evidenceByItem),
this.runLlmItems(params, verifyRunId, llmItems, evidenceByItem, multimodalItemIds),
...agentItems.map((item) =>
this.runAgentItem(params, verifyRunId, item, evidenceByItem.get(item.id) ?? []),
),
]);
await this.statusService.recompute(params.operationId);
}
/** Group a run's evidence rows by the plan item id they back. */
private async loadEvidence(
rows: Awaited<ReturnType<VerifyEvidenceModel['listByRun']>>,
): Promise<EvidenceByItem> {
const documentIds = [
...new Set(rows.flatMap((row) => (row.documentId ? [row.documentId] : []))),
];
const documents = await this.documentModel.findByIds(documentIds);
const documentContent = new Map(documents.map((document) => [document.id, document.content]));
const byItem: EvidenceByItem = new Map();
for (const row of rows) {
const list = byItem.get(row.checkItemId) ?? [];
list.push({
content: row.documentId ? documentContent.get(row.documentId) : row.content,
description: row.description,
documentId: row.documentId,
fileId: row.fileId,
metadata: row.metadata,
type: row.type,
});
byItem.set(row.checkItemId, list);
}
return byItem;
}
private async hydrateInlineMedia(evidence: JudgeEvidence[]): Promise<JudgeEvidence[]> {
return Promise.all(
evidence.map(async (item) => {
if (!item.fileId || (item.type !== 'screenshot' && item.type !== 'gif')) return item;
const file = await this.fileModel.findById(item.fileId);
if (!file) return item;
const accessUrl = await resolveModelReadableFrameUrl(this.fileService, file);
return {
...item,
accessUrl,
description: isGifFrameSheet(item.type, accessUrl)
? [item.description, GIF_FRAME_SHEET_NOTE].filter(Boolean).join(' ')
: item.description,
};
}),
);
}
private async modelSupportsVision(model: string, provider: string): Promise<boolean> {
const custom = await this.aiModelModel.findByIdAndProvider(model, provider);
const customAbilities = custom?.abilities as { vision?: boolean } | undefined;
if (typeof customAbilities?.vision === 'boolean') return customAbilities.vision;
const abilities = await getModelPropertyWithFallback<{ vision?: boolean }>(
model,
'abilities',
provider,
);
return abilities?.vision === true;
}
/**
* Mark every evidence-driven item whose declared evidence is incomplete as
* `uncertain` (status `failed`, so it gates delivery and seeds repair), and
* return their ids so the judges skip them. Items with no `requiredEvidence`
* pass through untouched.
*/
private async runStructuralGate(
verifyRunId: string,
items: VerifyCheckItem[],
evidenceByItem: EvidenceByItem,
): Promise<Set<string>> {
const gapIds = new Set<string>();
for (const item of items) {
const gaps = runEvidenceGaps(item.verifierConfig, evidenceByItem.get(item.id) ?? []);
if (gaps.length === 0) continue;
gapIds.add(item.id);
const executionGaps = executionGapTypes(runEvidenceSpecs(item.verifierConfig), gaps);
const fileGaps = gaps.filter((type) => !executionGaps.includes(type));
const missing = [
...fileGaps,
...executionGaps.map((type) => `${type} from a real command execution`),
].join(', ');
// The repair that acts on this suggestion runs as a new operation with a
// round of its own, so the command targets the caller's operation, not
// this run: naming this (settled) run sent every repair's evidence one
// round behind the round its gate checks.
const suggestions = [
fileGaps.length > 0 &&
`Capture and upload the missing evidence (${fileGaps.join(', ')}) to your current run via \`lh acceptance run result submit --operation "$LOBEHUB_OPERATION_ID" --item ${item.id} --type ${fileGaps.length === 1 ? fileGaps[0] : `<${fileGaps.join('|')}>`} --file <path>${fileGaps.includes('video') ? ' --chapters <file>' : ''}\`.`,
// Format alone never covers an execution requirement: an authored
// example or a bare log carries no execution provenance.
executionGaps.length > 0 &&
'Run the command for real and publish it as terminal evidence (captured or imported, not authored).',
].filter(Boolean);
await this.resultModel.updateByCheckItem(verifyRunId, item.id, {
completedAt: new Date(),
confidence: 0,
status: 'failed',
suggestion: suggestions.join(' '),
toulmin: { limitation: `Required evidence not provided: ${missing}.` },
verdict: 'uncertain',
});
}
return gapIds;
}
/** Execute program checks through the verifier agent until a native runner exists. */
private async runProgramItems(
params: ExecuteVerifyParams,
verifyRunId: string,
items: VerifyCheckItem[],
evidenceByItem: EvidenceByItem,
): Promise<void> {
if (params.runVerifierAgent) {
await Promise.all(
items.map((item) =>
this.runAgentItem(params, verifyRunId, item, evidenceByItem.get(item.id) ?? []),
),
);
return;
}
for (const item of items) {
await this.resultModel.updateByCheckItem(verifyRunId, item.id, {
completedAt: new Date(),
status: item.required ? 'errored' : 'skipped',
toulmin: {
limitation: 'Program verifier requires a native runner or verifier-agent fallback.',
},
});
}
}
/** Judge all LLM items via the Toulmin judge (one batched call by default). */
private async runLlmItems(
params: ExecuteVerifyParams,
verifyRunId: string,
items: VerifyCheckItem[],
evidenceByItem: EvidenceByItem,
multimodalItemIds: Set<string>,
): Promise<void> {
if (items.length === 0) return;
try {
const textItems = items.filter((item) => !multimodalItemIds.has(item.id));
const multimodalItems = items.filter((item) => multimodalItemIds.has(item.id));
if ((params.batchLlm ?? true) && textItems.length > 1) {
await this.judgeBatch(params, verifyRunId, textItems, evidenceByItem);
} else {
for (const item of textItems)
await this.judgeSingle(params, verifyRunId, item, evidenceByItem);
}
for (const item of multimodalItems)
await this.judgeSingle(params, verifyRunId, item, evidenceByItem, true);
} catch (error) {
log('llm judge failed for op %s: %O', params.operationId, error);
await this.markUnfinishedErrored(
verifyRunId,
items,
`LLM judge failed: ${describeThrownError(error)}`,
);
}
}
/** Run one agent check as a verifier sub-agent (verdict lands async via its hook) or skip. */
private async runAgentItem(
params: ExecuteVerifyParams,
verifyRunId: string,
item: VerifyCheckItem,
evidence: JudgeEvidence[],
): Promise<void> {
if (!params.runVerifierAgent) {
await this.resultModel.updateByCheckItem(verifyRunId, item.id, {
completedAt: new Date(),
status: item.required ? 'errored' : 'skipped',
toulmin: { limitation: 'Agent verifier requires runtime context; not run here.' },
});
return;
}
try {
const spawned = await params.runVerifierAgent({
checkItem: item,
evidence,
goal: params.goal,
operationId: params.operationId,
});
if (!spawned?.verifierOperationId) {
// The runner resolved without an operation id β the spawn never
// persisted an operation. Log the returned shape at error level (this
// path lands in production runtime logs, unlike the debug-only `log`).
console.error(
'[verify] agent verifier returned no operation id for item %s: %O',
item.id,
spawned,
);
await this.resultModel.updateByCheckItem(verifyRunId, item.id, {
completedAt: new Date(),
// Infra failure, not a delivery verdict: the verifier never started, so
// there is nothing to judge. `errored` (no verdict) keeps this out of
// the delivery gate and the auto-repair set.
status: 'errored',
toulmin: { limitation: 'Agent verifier failed to start (no operation id returned).' },
});
return;
}
const current = (await this.resultModel.listByRun(verifyRunId)).find(
(result) => result.checkItemId === item.id,
);
if (current && terminalResultStatuses.has(current.status)) return;
await this.resultModel.updateByCheckItem(verifyRunId, item.id, {
startedAt: new Date(),
status: 'running',
verifierOperationId: spawned.verifierOperationId,
});
} catch (error) {
// Surface the real cause: the spawn throws during agent startup (before
// the verifier operation is persisted), and this catch previously only
// emitted a debug-level line + a generic limitation β so in production the
// actual error was invisible and the check just read "failed to start".
// Log at error level (reaches runtime logs) and thread the message into
// the verdict limitation so it is queryable from verify_check_results.
const detail = error instanceof Error ? error.message : String(error);
console.error('[verify] agent verifier spawn failed for item %s: %O', item.id, error);
await this.resultModel.updateByCheckItem(verifyRunId, item.id, {
completedAt: new Date(),
// Infra failure (spawn threw before the verifier op was persisted), not a
// delivery verdict β mark `errored` so it neither gates delivery nor seeds
// a repair round.
status: 'errored',
toulmin: { limitation: `Agent verifier failed to start: ${detail}` },
});
}
}
private async judgeBatch(
params: ExecuteVerifyParams,
verifyRunId: string,
items: VerifyCheckItem[],
evidenceByItem: EvidenceByItem,
): Promise<void> {
// Batch: N verdicts share ONE tracing row (N:1).
const tracingId = randomUUID();
const promptItems = await Promise.all(
items.map(async (i) => ({
evidence: evidenceByItem.get(i.id),
id: i.id,
instruction: await this.resolveInstruction(i),
title: i.title,
})),
);
const chain = chainVerifyJudge({
deliverable: params.deliverable,
goal: params.goal,
items: promptItems,
mode: 'batch',
});
const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);
const raw = await ai.generateObject(
{
...chain,
model: params.modelConfig.model,
provider: params.modelConfig.provider,
schema: BATCH_VERDICT_JSON_SCHEMA,
},
{
metadata: { trigger: RequestTrigger.Verify },
tracing: {
...({
promptVersion: VERIFY_JUDGE_PROMPT_VERSION,
scenario: TRACING_SCENARIOS.VerifyJudge,
schemaName: BATCH_VERDICT_JSON_SCHEMA.name,
tracingId,
} satisfies TracingOptions),
// Backfill the tracing FK only after the (async, best-effort) tracing
// row is persisted β verdicts are written with a null link below.
onPersisted: this.backfillTracing(
verifyRunId,
items.map((i) => i.id),
),
},
},
);
const parsed = BatchVerdictSchema.safeParse(raw);
if (!parsed.success) {
log('batch judge output invalid: %O', parsed.error.flatten());
for (const item of items) await this.judgeSingle(params, verifyRunId, item, evidenceByItem);
return;
}
const validIds = new Set(items.map((i) => i.id));
const returnedIds = new Set<string>();
for (const v of parsed.data.verdicts) {
if (!validIds.has(v.checkItemId)) continue;
returnedIds.add(v.checkItemId);
await this.writeVerdict({
checkItemId: v.checkItemId,
verdict: v,
verifyRunId,
});
}
for (const item of items) {
if (!returnedIds.has(item.id)) {
await this.judgeSingle(params, verifyRunId, item, evidenceByItem);
}
}
}
private async judgeSingle(
params: ExecuteVerifyParams,
verifyRunId: string,
item: VerifyCheckItem,
evidenceByItem: EvidenceByItem,
multimodal = false,
): Promise<void> {
// Per-criterion: each result gets its own tracing row (1:1).
const tracingId = randomUUID();
const hydratedEvidence = multimodal
? await this.hydrateInlineMedia(evidenceByItem.get(item.id) ?? [])
: evidenceByItem.get(item.id);
const chain = chainVerifyJudge({
deliverable: params.deliverable,
goal: params.goal,
items: [
{
evidence: hydratedEvidence,
id: item.id,
instruction: await this.resolveInstruction(item),
title: item.title,
},
],
mode: 'single',
});
const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);
const raw = await ai.generateObject(
{
...chain,
model: params.modelConfig.model,
provider: params.modelConfig.provider,
schema: SINGLE_VERDICT_JSON_SCHEMA,
},
{
metadata: { trigger: RequestTrigger.Verify },
tracing: {
...({
promptVersion: VERIFY_JUDGE_PROMPT_VERSION,
scenario: TRACING_SCENARIOS.VerifyJudge,
schemaName: SINGLE_VERDICT_JSON_SCHEMA.name,
tracingId,
} satisfies TracingOptions),
onPersisted: this.backfillTracing(verifyRunId, [item.id]),
},
},
);
const parsed = SingleVerdictSchema.safeParse(raw);
if (!parsed.success) {
log('single judge output invalid: %O', parsed.error.flatten());
await this.resultModel.updateByCheckItem(verifyRunId, item.id, {
completedAt: new Date(),
status: 'errored',
toulmin: { limitation: 'LLM judge returned an invalid structured verdict.' },
});
return;
}
await this.writeVerdict({
checkItemId: item.id,
verdict: parsed.data,
verifyRunId,
});
}
private async markUnfinishedErrored(
verifyRunId: string,
items: VerifyCheckItem[],
limitation: string,
): Promise<void> {
const results = await this.resultModel.listByRun(verifyRunId);
const terminalIds = new Set(
results
.filter((result) => terminalResultStatuses.has(result.status))
.map((result) => result.checkItemId),
);
await Promise.all(
items
.filter((item) => !terminalIds.has(item.id))
.map((item) =>
this.resultModel.updateByCheckItem(verifyRunId, item.id, {
completedAt: new Date(),
status: 'errored',
toulmin: { limitation },
}),
),
);
}
private async writeVerdict(params: {
checkItemId: string;
verdict: SingleVerdict;
verifyRunId: string;
}): Promise<void> {
const { verifyRunId, checkItemId, verdict } = params;
// `verifier_tracing_id` is intentionally left null here β the tracing row is
// written asynchronously (best-effort, after the response), so linking it now
// would violate the FK. It is backfilled by `backfillTracing` once the row exists.
await this.resultModel.updateByCheckItem(verifyRunId, checkItemId, {
completedAt: new Date(),
confidence: verdict.confidence,
status: verdictToStatus(verdict.verdict),
suggestion: verdict.suggestion ?? null,
toulmin: toToulmin(verdict),
verdict: verdict.verdict,
});
}
/**
* Build the `onPersisted` callback handed to the tracing layer. It fires in the
* tracing hook's deferred (post-response) continuation once the
* `llm_generation_tracing` row is committed β only then is it safe to set the
* FK link. Receives the persisted tracing id (or null if tracing was disabled
* or the record failed), so a missing tracing row simply leaves the link null.
*/
private backfillTracing(verifyRunId: string, checkItemIds: string[]) {
return async (tracingId: string | null): Promise<void> => {
if (!tracingId) return;
try {
await this.resultModel.backfillTracingId(verifyRunId, checkItemIds, tracingId);
} catch (error) {
log('tracing-id backfill failed for run %s (non-fatal): %O', verifyRunId, error);
}
};
}
}