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.

🐛 fix: goal verify errored redispatch (#21442)

Arvin Xu2950135c3c7d
diff --git a/apps/server/src/router-hono/workflows/verify/handlers/onVerifierComplete.ts b/apps/server/src/router-hono/workflows/verify/handlers/onVerifierComplete.ts
index 551e2e2dc74..297a00b0acb 100644
--- a/apps/server/src/router-hono/workflows/verify/handlers/onVerifierComplete.ts
+++ b/apps/server/src/router-hono/workflows/verify/handlers/onVerifierComplete.ts
@@ -9,6 +9,7 @@ const log = debug('lobe-server:workflows:verify:on-verifier-complete');
export interface OnVerifierCompletePayload {
checkItemId: string;
errorMessage?: string;
+ errorType?: string;
hookId?: string;
hookType?: string;
operationId: string;
@@ -24,6 +25,7 @@ export async function onVerifierComplete(c: Context) {
const {
checkItemId,
errorMessage,
+ errorType,
operationId,
parentOperationId,
reason,
@@ -50,6 +52,7 @@ export async function onVerifierComplete(c: Context) {
{
checkItemId,
errorMessage,
+ errorType,
parentOperationId,
reason,
verifierOperationId: operationId,
diff --git a/apps/server/src/services/goal/decideNextMove.test.ts b/apps/server/src/services/goal/decideNextMove.test.ts
index 8df9a2d7983..95d62b6de0d 100644
--- a/apps/server/src/services/goal/decideNextMove.test.ts
+++ b/apps/server/src/services/goal/decideNextMove.test.ts
@@ -1,5 +1,6 @@
import {
ACCEPTANCE_REVIEW_ERRORED_ERROR,
+ VERIFICATION_OUT_OF_CREDITS_ERROR,
VERIFICATION_UNJUDGEABLE_ERROR,
} from '@lobechat/const/goal';
import type { GoalGraphNode, GoalGraphSnapshot, TaskItem } from '@lobechat/types';
@@ -225,6 +226,14 @@ describe('decideNextMove', () => {
frontierTask: task({ error: ACCEPTANCE_REVIEW_ERRORED_ERROR, status: 'paused' }),
}),
).toMatchObject({ branch: 'failure_decision', outcome: 'waiting_human' });
+
+ // A verifier refused for want of credits refuses every re-delivery too.
+ // Retrying it like any verifier error spent a builder attempt per round.
+ expect(
+ decide(snapshot, {
+ frontierTask: task({ error: VERIFICATION_OUT_OF_CREDITS_ERROR, status: 'paused' }),
+ }),
+ ).toMatchObject({ branch: 'failure_decision', outcome: 'waiting_human' });
});
it('treats a plain pause as waiting on a person and a run as waiting on the world', () => {
diff --git a/apps/server/src/services/goal/failureClass.test.ts b/apps/server/src/services/goal/failureClass.test.ts
index 0fe925e271e..257ceacea40 100644
--- a/apps/server/src/services/goal/failureClass.test.ts
+++ b/apps/server/src/services/goal/failureClass.test.ts
@@ -1,3 +1,4 @@
+import { VERIFICATION_OUT_OF_CREDITS_ERROR } from '@lobechat/const/goal';
import { describe, expect, it } from 'vitest';
import { classifyGoalFailure, parseQuotaResetAt } from './failureClass';
@@ -53,6 +54,8 @@ describe('classifyGoalFailure', () => {
],
['GATEWAY_NOT_CONFIGURED', 'gateway'],
['InvalidProviderAPIKey', 'credentials'],
+ // The verifier's credit refusal has no retry branch; the setup gate owns it.
+ [VERIFICATION_OUT_OF_CREDITS_ERROR, 'credentials'],
])('reads %s as a setup problem (%s)', (error, kind) => {
expect(classifyGoalFailure(error)).toMatchObject({ class: 'environment', problem: { kind } });
});
diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts
index 6e4d5ea4b2f..1cef032340a 100644
--- a/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts
+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts
@@ -15,7 +15,10 @@ import {
goalEvents,
goalNodes,
goals,
+ messagePlugins,
+ messages,
tasks,
+ topics,
users,
verifyCheckResults,
verifyRuns,
@@ -94,6 +97,80 @@ describe('buildTaskPrompt Goal loop context', () => {
});
});
+describe('buildTaskPrompt questions earlier rounds asked', () => {
+ /**
+ * Regression: each Goal round is a fresh conversation, so a question an
+ * earlier round put to the owner — and the answer — never reached the next.
+ * Rounds asked the same thing again, timed out, delivered "awaiting your
+ * confirmation", failed Acceptance and spawned another round.
+ */
+ it('hands the next round what earlier rounds asked and what came back', async () => {
+ const taskModel = new TaskModel(db, userId);
+ const task = await taskModel.create({ instruction: 'Compare the two designs.' });
+ await taskModel.update(task.id, { totalTopics: 2 });
+ const goal = await new GoalModel(db, userId).create({
+ subjectType: 'standalone',
+ title: 'Asked before',
+ });
+ const graphModel = new GoalGraphModel(db, userId);
+ const taskNode = await graphModel.createNode(goal.id, { kind: 'task', title: 'Compare' });
+ await graphModel.bindTask(goal.id, taskNode!.id, task.id);
+
+ const taskTopicModel = new TaskTopicModel(db, userId);
+ const asks = [
+ {
+ content: 'User answers:\n- Confirm the four decisions as recommended?: Yes',
+ question: 'Confirm the four decisions as recommended?',
+ topicId: 'asked-round-1',
+ },
+ {
+ content:
+ 'No answer received within the wait window; the user did not respond. Continue without their input or ask in plain text.',
+ question: 'Can a virtual display be created on this machine?',
+ topicId: 'asked-round-2',
+ },
+ ];
+ for (const [i, ask] of asks.entries()) {
+ await db.insert(topics).values({ id: ask.topicId, userId });
+ await taskTopicModel.add(task.id, ask.topicId, { seq: i + 1, trigger: 'goal' });
+ const messageId = `asked-message-${i}`;
+ await db.insert(messages).values({
+ content: ask.content,
+ createdAt: new Date(Date.UTC(2026, 9, 1, 10 + i)),
+ id: messageId,
+ role: 'tool',
+ topicId: ask.topicId,
+ userId,
+ });
+ await db.insert(messagePlugins).values({
+ apiName: 'askUserQuestion',
+ arguments: JSON.stringify({ questions: [{ options: [], question: ask.question }] }),
+ id: messageId,
+ identifier: 'claude-code',
+ toolCallId: `tc-${i}`,
+ userId,
+ });
+ }
+
+ const result = await buildTaskPrompt((await taskModel.findById(task.id))!, {
+ briefModel: new BriefModel(db, userId),
+ db,
+ taskModel,
+ taskTopicModel,
+ userId,
+ });
+
+ expect(result.prompt).toContain('Questions earlier rounds already asked the owner');
+ expect(result.prompt).toContain(
+ '1. Confirm the four decisions as recommended?\n → User answers: - Confirm the four decisions as recommended?: Yes',
+ );
+ expect(result.prompt).toContain(
+ '2. Can a virtual display be created on this machine?\n → No answer received within the wait window',
+ );
+ expect(result.prompt).toContain('Do not ask the owner again');
+ });
+});
+
describe('buildTaskPrompt unresolved checks', () => {
const planItem = (id: string) => ({
id,
diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.ts
index ea380c8f5f2..b9297255467 100644
--- a/apps/server/src/services/taskRunner/buildTaskPrompt.ts
+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.ts
@@ -1,9 +1,11 @@
+import { UserInteractionApiName } from '@lobechat/builtin-tool-user-interaction';
import { buildTaskRunPrompt, type TaskRunPromptGoalLoop } from '@lobechat/prompts';
import type { TaskItem, TaskTopicHandoff, WorkspaceData } from '@lobechat/types';
import { AcceptanceModel } from '@/database/models/acceptance';
import type { BriefModel } from '@/database/models/brief';
import { GoalModel } from '@/database/models/goal';
+import { MessageModel } from '@/database/models/message';
import type { TaskModel } from '@/database/models/task';
import type { TaskTopicModel } from '@/database/models/taskTopic';
import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
@@ -23,6 +25,56 @@ import { resolveTaskAcceptance } from '@/server/services/verify/taskAcceptanceRe
/** Cap on unresolved checks carried into the next round's prompt. */
const MAX_GOAL_FAILED_CHECKS = 8;
+/** Cap on earlier questions to the owner carried into the next round's prompt. */
+const MAX_GOAL_ASKED_QUESTIONS = 8;
+const MAX_ASKED_ANSWER_CHARS = 500;
+
+/**
+ * What earlier rounds of a Task asked the owner, and what came back. Every
+ * builder shape records the question under the same `askUserQuestion` API, with
+ * the answer — or the notice that none arrived — as the tool message's text.
+ */
+const readAskedQuestions = async (
+ deps: BuildTaskPromptDeps,
+ topicIds: string[],
+): Promise<NonNullable<TaskRunPromptGoalLoop['askedQuestions']>> => {
+ const calls = await new MessageModel(
+ deps.db,
+ deps.userId,
+ deps.workspaceId,
+ ).listToolCallsInTopics({
+ apiName: UserInteractionApiName.askUserQuestion,
+ limit: MAX_GOAL_ASKED_QUESTIONS,
+ topicIds,
+ });
+ return calls.flatMap((call) => {
+ let questions: string[] = [];
+ try {
+ const args = JSON.parse(call.arguments ?? '{}') as {
+ question?: unknown;
+ questions?: Array<{ question?: unknown }>;
+ };
+ questions = [
+ ...(Array.isArray(args.questions) ? args.questions.map((q) => q?.question) : []),
+ args.question,
+ ].filter((q): q is string => typeof q === 'string' && !!q.trim());
+ } catch {
+ // Unreadable arguments: nothing to tell the next round about.
+ }
+ if (questions.length === 0) return [];
+ const answer = call.content?.trim();
+ return [
+ {
+ answer:
+ answer && answer.length > MAX_ASKED_ANSWER_CHARS
+ ? `${answer.slice(0, MAX_ASKED_ANSWER_CHARS)}…`
+ : answer || undefined,
+ questions,
+ },
+ ];
+ });
+};
+
/**
* Whether the verifier actually judged this result. `pending` / `running` rows
* are planned checks, and `errored` means the verifier never ran — neither says
@@ -51,14 +103,22 @@ const resolveGoalLoopContext = async (
// Runs lost to a machine problem (offline device, usage limit, transport fault)
// are not rounds the budget counts, so the agent is not told it is on a later
// round than the coordinator thinks.
- const unchargedRuns = countUnchargedRuns(
- await deps.taskTopicModel.findByTaskId(task.id).catch(() => []),
- );
+ const taskRuns = await deps.taskTopicModel.findByTaskId(task.id).catch(() => []);
+ const unchargedRuns = countUnchargedRuns(taskRuns);
const context: TaskRunPromptGoalLoop = {
maxRounds: Number.isFinite(budget) ? budget : null,
round: countChargedTaskAttempts(task, unchargedRuns) + 1,
};
+ // Each round is a fresh conversation, so a question an earlier round asked —
+ // and its answer — never reached the next one. Rounds kept re-asking the
+ // owner the same thing, timing out, and delivering "awaiting confirmation".
+ const askedQuestions = await readAskedQuestions(
+ deps,
+ taskRuns.flatMap((run) => (run.topicId ? [run.topicId] : [])),
+ ).catch(() => []);
+ if (askedQuestions.length > 0) context.askedQuestions = askedQuestions;
+
try {
const acceptance = await new AcceptanceModel(db, userId, workspaceId).findBySubject(
'task',
diff --git a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
index cd6c6e22a79..34aacced7db 100644
--- a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
+++ b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
@@ -2,6 +2,7 @@
import {
ACCEPTANCE_REVIEW_ERRORED_ERROR,
VERIFICATION_ERRORED_ERROR,
+ VERIFICATION_OUT_OF_CREDITS_ERROR,
VERIFICATION_UNJUDGEABLE_ERROR,
} from '@lobechat/const/goal';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -660,6 +661,80 @@ describe('driveTaskFromVerify', () => {
expect(deliverArg.errorMessage.toLowerCase()).toContain('internal error');
});
+ /**
+ * Regression: a verifier refused with "Budget exceeded" paused the Goal Task
+ * with the generic errored string, which the coordinator recovers with a new
+ * builder attempt. Every attempt re-uploaded the same evidence into the same
+ * refused verifier, spending credits round after round with nothing judged.
+ */
+ it('errored on a credit refusal → pauses with the out-of-credits reason, not the retryable one', async () => {
+ runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'errored' });
+ goalFindByTask.mockResolvedValue({ id: 'goal-1' });
+ checkResultsListByRun.mockResolvedValueOnce([
+ {
+ checkItemTitle: 'Report is published',
+ required: true,
+ status: 'errored',
+ toulmin: {
+ limitation:
+ 'Verifier failed before submitting a verdict: Budget exceeded (InsufficientBudgetForModel)',
+ },
+ },
+ ]);
+
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+
+ expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', {
+ error: VERIFICATION_OUT_OF_CREDITS_ERROR,
+ });
+ expect(taskUpdateStatus).not.toHaveBeenCalledWith('task-1', 'paused', {
+ error: VERIFICATION_ERRORED_ERROR,
+ });
+ expect(deliverMock.mock.calls[0][0].errorMessage).toContain('out of credits');
+ });
+
+ it('errored: an optional check refused for credits does not hide a retryable required error', async () => {
+ runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'errored' });
+ checkResultsListByRun.mockResolvedValueOnce([
+ {
+ required: true,
+ status: 'errored',
+ toulmin: { limitation: 'Verifier failed before submitting a verdict: socket hang up' },
+ },
+ {
+ required: false,
+ status: 'errored',
+ toulmin: {
+ limitation:
+ 'Verifier failed before submitting a verdict: Free plan limit (FreePlanLimit)',
+ },
+ },
+ ]);
+
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+
+ expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', {
+ error: VERIFICATION_ERRORED_ERROR,
+ });
+ });
+
+ it('errored for another reason → keeps the retryable errored reason', async () => {
+ runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'errored' });
+ checkResultsListByRun.mockResolvedValueOnce([
+ {
+ required: true,
+ status: 'errored',
+ toulmin: { limitation: 'Verifier failed before submitting a verdict: socket hang up' },
+ },
+ ]);
+
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+
+ expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', {
+ error: VERIFICATION_ERRORED_ERROR,
+ });
+ });
+
it('skips when the run has not terminally settled (verifying/repairing)', async () => {
runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'verifying' });
await driveTaskFromVerify(db, 'u1', 'op-1');
diff --git a/apps/server/src/services/verify/__tests__/verifierError.test.ts b/apps/server/src/services/verify/__tests__/verifierError.test.ts
new file mode 100644
index 00000000000..dbfb51372f9
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/verifierError.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+
+import { describeThrownError, isOutOfCreditsFailure, withErrorType } from '../verifierError';
+
+describe('verifierError', () => {
+ it.each([
+ 'Verifier failed before submitting a verdict: Budget exceeded (InsufficientBudgetForModel)',
+ 'LLM judge failed: Budget exceeded',
+ 'Verifier failed before submitting a verdict: FreePlanLimit',
+ ])('reads %s as a credit refusal', (text) => {
+ expect(isOutOfCreditsFailure(text)).toBe(true);
+ });
+
+ it.each([
+ 'Verifier failed before submitting a verdict: socket hang up',
+ 'Verifier completed without submitting a verdict.',
+ undefined,
+ ])('does not read %s as a credit refusal', (text) => {
+ expect(isOutOfCreditsFailure(text)).toBe(false);
+ });
+
+ it('appends the code once', () => {
+ expect(withErrorType('Budget exceeded', 'InsufficientBudgetForModel')).toBe(
+ 'Budget exceeded (InsufficientBudgetForModel)',
+ );
+ expect(withErrorType('InvalidProviderAPIKey', 'InvalidProviderAPIKey')).toBe(
+ 'InvalidProviderAPIKey',
+ );
+ expect(withErrorType(undefined, 'InsufficientBudgetForModel')).toBe(
+ 'InsufficientBudgetForModel',
+ );
+ expect(withErrorType('socket hang up')).toBe('socket hang up');
+ });
+
+ /** Regression: a thrown runtime payload was recorded as "[object Object]". */
+ it('describes a thrown model-runtime payload with its code', () => {
+ expect(
+ describeThrownError({
+ error: { message: 'Budget exceeded' },
+ errorType: 'InsufficientBudgetForModel',
+ }),
+ ).toBe('Budget exceeded (InsufficientBudgetForModel)');
+ expect(describeThrownError(new Error('boom'))).toBe('boom');
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/verifierTerminal.test.ts b/apps/server/src/services/verify/__tests__/verifierTerminal.test.ts
index 49357f4ea98..e473514ed8b 100644
--- a/apps/server/src/services/verify/__tests__/verifierTerminal.test.ts
+++ b/apps/server/src/services/verify/__tests__/verifierTerminal.test.ts
@@ -84,6 +84,22 @@ describe('settleVerifierCheckFromTerminal', () => {
expect(finalizeVerifyRunMock).toHaveBeenCalledWith(db, 'u', 'parent-op', {}, 'ws');
});
+ it('keeps the runtime error code beside the message so a credit refusal stays recognisable', async () => {
+ await settleVerifierCheckFromTerminal(db, 'u', {
+ checkItemId: 'check-1',
+ errorMessage: 'Budget exceeded',
+ errorType: 'InsufficientBudgetForModel',
+ parentOperationId: 'parent-op',
+ reason: 'error',
+ verifierOperationId: 'verifier-op',
+ });
+
+ expect(updateByCheckItemMock.mock.calls[0][2].toulmin).toEqual({
+ limitation:
+ 'Verifier failed before submitting a verdict: Budget exceeded (InsufficientBudgetForModel)',
+ });
+ });
+
it('does not overwrite a result already written by submitVerifyResult', async () => {
listResultsByRunMock.mockResolvedValue([{ checkItemId: 'check-1', status: 'passed' }]);
diff --git a/apps/server/src/services/verify/agentVerifier.ts b/apps/server/src/services/verify/agentVerifier.ts
index af2b52a5aa3..d5c76512339 100644
--- a/apps/server/src/services/verify/agentVerifier.ts
+++ b/apps/server/src/services/verify/agentVerifier.ts
@@ -133,6 +133,7 @@ export const createVerifierAgentRunner = (params: {
{
checkItemId: checkItem.id,
errorMessage: event.errorMessage,
+ errorType: event.errorType,
parentOperationId: operationId,
reason: event.reason,
verifierOperationId: event.operationId,
diff --git a/apps/server/src/services/verify/executor.ts b/apps/server/src/services/verify/executor.ts
index 514ade59b25..695f9548e18 100644
--- a/apps/server/src/services/verify/executor.ts
+++ b/apps/server/src/services/verify/executor.ts
@@ -36,6 +36,7 @@ import { GIF_FRAME_SHEET_NOTE, isGifFrameSheet, resolveModelReadableFrameUrl } f
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');
@@ -365,7 +366,7 @@ export class VerifyExecutorService {
await this.markUnfinishedErrored(
verifyRunId,
items,
- `LLM judge failed: ${error instanceof Error ? error.message : String(error)}`,
+ `LLM judge failed: ${describeThrownError(error)}`,
);
}
}
diff --git a/apps/server/src/services/verify/settle.ts b/apps/server/src/services/verify/settle.ts
index 9b76e399b7f..e3d65ecc0af 100644
--- a/apps/server/src/services/verify/settle.ts
+++ b/apps/server/src/services/verify/settle.ts
@@ -2,6 +2,7 @@ import {
ACCEPTANCE_REVIEW_ERRORED_ERROR,
VERIFICATION_ERRORED_ERROR,
VERIFICATION_FAILED_ERROR,
+ VERIFICATION_OUT_OF_CREDITS_ERROR,
VERIFICATION_UNJUDGEABLE_ERROR,
} from '@lobechat/const/goal';
import debug from 'debug';
@@ -23,6 +24,7 @@ import { maybeAutoRepair } from './repairService';
import { VerifyReporterService } from './reporter';
import { VerifyStatusService } from './statusService';
import { attachTaskRunToAcceptance, resolveTaskAcceptance } from './taskAcceptance';
+import { isOutOfCreditsFailure } from './verifierError';
const log = debug('lobe-server:verify-settle');
@@ -207,6 +209,25 @@ export const driveTaskFromVerify = async (
? 'unjudgeable'
: run.status;
+ // A verifier refused for want of credits stays refused however often the
+ // builder re-delivers. Name that cause, so the Goal coordinator asks for
+ // credits instead of starting builder attempt after builder attempt into
+ // the same refusal. An unreadable cause keeps the ordinary errored path.
+ const outOfCredits =
+ outcome === 'errored' &&
+ (await new VerifyCheckResultModel(db, userId, workspaceId)
+ .listByRun(run.id)
+ .then((results) =>
+ results.some(
+ (r) =>
+ r.required && r.status === 'errored' && isOutOfCreditsFailure(r.toulmin?.limitation),
+ ),
+ )
+ .catch((error) => {
+ log('verify-settle errored causes unavailable for %s: %O', run.id, error);
+ return false;
+ }));
+
if (outcome === 'passed') {
// Verify and, for Goal tasks, Acceptance review must pass before completing
// the task and cascading (checkpoint / sibling
@@ -231,7 +252,10 @@ export const driveTaskFromVerify = async (
// rejected delivery:
// - failed: the verifier ran and judged the delivery short of the criteria.
// - errored: the verifier could not run (infra) — the delivery was NOT
- // evaluated, so we must not claim it "did not pass".
+ // evaluated, so we must not claim it "did not pass". When
+ // the cause is a credit refusal it gets its own summary:
+ // another builder attempt cannot fix that, so it routes
+ // to a person.
// - review_errored: the verifiers passed, but the Acceptance review on top of
// them still could not run after its retry. The builder
// cannot fix a broken reviewer, so this routes to a person.
@@ -250,9 +274,11 @@ export const driveTaskFromVerify = async (
? VERIFICATION_UNJUDGEABLE_ERROR
: outcome === 'review_errored'
? ACCEPTANCE_REVIEW_ERRORED_ERROR
- : isErrored
- ? VERIFICATION_ERRORED_ERROR
- : VERIFICATION_FAILED_ERROR;
+ : outOfCredits
+ ? VERIFICATION_OUT_OF_CREDITS_ERROR
+ : isErrored
+ ? VERIFICATION_ERRORED_ERROR
+ : VERIFICATION_FAILED_ERROR;
if (task.automationMode) {
// Mirror of the pass branch: verify judges THIS tick, not the lifetime
// schedule. Pausing here would permanently disarm the cron (the
@@ -308,11 +334,13 @@ export const driveTaskFromVerify = async (
}),
goalReview?.status === 'rejected' ? goalReview.feedback : undefined,
)
- : outcome === 'errored' || outcome === 'review_errored'
- ? 'Verification could not be completed due to an internal error; the delivery was not evaluated. Please retry or review it manually.'
- : outcome === 'unjudgeable'
- ? 'Acceptance review could not judge this delivery from the captured evidence. Review it manually, or restate the check so evidence can settle it.'
- : undefined;
+ : outOfCredits
+ ? 'Verification could not run because the account is out of credits for the verifier model; the delivery was not evaluated. Top up credits, then retry.'
+ : outcome === 'errored' || outcome === 'review_errored'
+ ? 'Verification could not be completed due to an internal error; the delivery was not evaluated. Please retry or review it manually.'
+ : outcome === 'unjudgeable'
+ ? 'Acceptance review could not judge this delivery from the captured evidence. Review it manually, or restate the check so evidence can settle it.'
+ : undefined;
await new TaskResultBridgeService(db, userId, workspaceId).deliver({
operationId,
reason: outcome === 'passed' ? 'done' : 'error',
diff --git a/apps/server/src/services/verify/verifierError.ts b/apps/server/src/services/verify/verifierError.ts
new file mode 100644
index 00000000000..b1f0003431e
--- /dev/null
+++ b/apps/server/src/services/verify/verifierError.ts
@@ -0,0 +1,47 @@
+/**
+ * Codes (and the bare message the credit gate throws) for a verifier model call
+ * refused because the account has no spendable credits. A retry fails the same
+ * way until someone tops up, so this outcome must not start another attempt.
+ */
+const OUT_OF_CREDITS_PATTERN =
+ /\b(?:InsufficientBudgetForModel|FreePlanLimit|SubscriptionPlanLimit|InsufficientQuota)\b|\bbudget exceeded\b/i;
+
+/** Whether an errored check's recorded cause is a credit refusal. */
+export const isOutOfCreditsFailure = (text?: string | null): boolean =>
+ !!text && OUT_OF_CREDITS_PATTERN.test(text);
+
+/**
+ * Error text with its stable code appended, so the recorded limitation can be
+ * classified later without guessing from free-form prose ("Budget exceeded").
+ */
+export const withErrorType = (message: string | undefined, errorType?: string): string => {
+ const text = message?.trim() ?? '';
+ if (!errorType || text.includes(errorType)) return text || errorType || '';
+ return text ? `${text} (${errorType})` : errorType;
+};
+
+/**
+ * Describe a thrown model-runtime error. Those are plain payloads —
+ * `{ errorType, error: { message } }` — so `String(error)` read "[object Object]"
+ * and dropped the code.
+ */
+export const describeThrownError = (error: unknown): string => {
+ if (error instanceof Error) return error.message;
+ if (error && typeof error === 'object') {
+ const payload = error as {
+ error?: { message?: unknown };
+ errorType?: unknown;
+ message?: unknown;
+ };
+ const message =
+ typeof payload.error?.message === 'string'
+ ? payload.error.message
+ : typeof payload.message === 'string'
+ ? payload.message
+ : undefined;
+ const errorType = typeof payload.errorType === 'string' ? payload.errorType : undefined;
+ const described = withErrorType(message, errorType);
+ if (described) return described;
+ }
+ return String(error);
+};
diff --git a/apps/server/src/services/verify/verifierTerminal.ts b/apps/server/src/services/verify/verifierTerminal.ts
index 02cda8e9283..0d4f2b41e6e 100644
--- a/apps/server/src/services/verify/verifierTerminal.ts
+++ b/apps/server/src/services/verify/verifierTerminal.ts
@@ -6,6 +6,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { finalizeVerifyRun } from './settle';
import { VerifyStatusService } from './statusService';
+import { withErrorType } from './verifierError';
const log = debug('lobe-server:verify-verifier-terminal');
@@ -14,6 +15,8 @@ const TERMINAL_RESULT_STATUSES = new Set(['passed', 'failed', 'errored', 'skippe
export interface SettleVerifierCheckFromTerminalParams {
checkItemId: string;
errorMessage?: string;
+ /** Stable runtime code (e.g. `InsufficientBudgetForModel`) the terminal event carried. */
+ errorType?: string;
parentOperationId: string;
reason?: string;
verifierOperationId: string;
@@ -30,7 +33,8 @@ export const settleVerifierCheckFromTerminal = async (
params: SettleVerifierCheckFromTerminalParams,
workspaceId?: string,
): Promise<void> => {
- const { checkItemId, errorMessage, parentOperationId, reason, verifierOperationId } = params;
+ const { checkItemId, errorMessage, errorType, parentOperationId, reason, verifierOperationId } =
+ params;
try {
const run = await new VerifyRunModel(db, userId, workspaceId).findByOperation(
@@ -45,10 +49,13 @@ export const settleVerifierCheckFromTerminal = async (
if (!result || TERMINAL_RESULT_STATUSES.has(result.status)) return;
+ // Keep the code beside the message: settle reads it to tell a credit
+ // refusal (no retry can help) from an error another attempt might clear.
+ const cause = withErrorType(errorMessage, errorType);
const limitation =
reason === 'done'
? 'Verifier completed without submitting a verdict.'
- : `Verifier failed before submitting a verdict${errorMessage ? `: ${errorMessage}` : '.'}`;
+ : `Verifier failed before submitting a verdict${cause ? `: ${cause}` : '.'}`;
await resultModel.updateByCheckItem(run.id, checkItemId, {
completedAt: new Date(),
diff --git a/packages/const/src/goal.ts b/packages/const/src/goal.ts
index ce12dfa5d9f..0cb12e8ddf6 100644
--- a/packages/const/src/goal.ts
+++ b/packages/const/src/goal.ts
@@ -132,6 +132,19 @@ export const VERIFICATION_FAILED_ERROR = 'Delivery did not pass verification.';
/** The verifier itself could not run, so the delivery was never evaluated. */
export const VERIFICATION_ERRORED_ERROR =
'Verification could not run (internal error); the delivery was not evaluated.';
+/**
+ * The verifier could not run because the account has no credits left for its
+ * model. The delivery was never evaluated, and nothing a builder does changes
+ * that.
+ *
+ * Deliberately has NO recovery branch. Recovering it like any other verifier
+ * error started a fresh builder attempt, which re-delivered the same evidence
+ * into the same refused verifier and spent attempt after attempt until the
+ * budget ran out. The `InsufficientBudgetForModel` code in the text classifies
+ * it as a setup problem, so the gate asks for credits instead of a judgment.
+ */
+export const VERIFICATION_OUT_OF_CREDITS_ERROR =
+ 'Verification could not run: the verifier model was refused for lack of credits (InsufficientBudgetForModel); the delivery was not evaluated.';
/**
* The review read the evidence and found the criterion undecidable from it — it
* asks for an action the review layer cannot perform (re-running the delivered
diff --git a/packages/database/src/models/__tests__/messages/message.toolCallsInTopics.test.ts b/packages/database/src/models/__tests__/messages/message.toolCallsInTopics.test.ts
new file mode 100644
index 00000000000..f1326780520
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/message.toolCallsInTopics.test.ts
@@ -0,0 +1,131 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { messagePlugins, messages, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'tool-calls-in-topics-user';
+const otherUserId = 'tool-calls-in-topics-other';
+const messageModel = new MessageModel(serverDB, userId);
+
+const seedToolCall = async (opts: {
+ apiName?: string;
+ content: string;
+ createdAt: Date;
+ id: string;
+ ownerId?: string;
+ topicId: string;
+}) => {
+ const owner = opts.ownerId ?? userId;
+ await serverDB.insert(messages).values({
+ content: opts.content,
+ createdAt: opts.createdAt,
+ id: opts.id,
+ role: 'tool',
+ topicId: opts.topicId,
+ userId: owner,
+ });
+ await serverDB.insert(messagePlugins).values({
+ apiName: opts.apiName ?? 'askUserQuestion',
+ arguments: JSON.stringify({ questions: [{ question: opts.id }] }),
+ id: opts.id,
+ identifier: 'claude-code',
+ toolCallId: `tc-${opts.id}`,
+ userId: owner,
+ });
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(topics).values([
+ { id: 'tcit-round1', userId },
+ { id: 'tcit-round2', userId },
+ { id: 'tcit-unrelated', userId },
+ { id: 'tcit-other', userId: otherUserId },
+ ]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+});
+
+describe('MessageModel.listToolCallsInTopics', () => {
+ it('returns the calls to one API across the given topics, oldest first', async () => {
+ await seedToolCall({
+ content: 'User answers:\n- q: yes',
+ createdAt: new Date('2026-10-01T10:00:00Z'),
+ id: 'tcit-a',
+ topicId: 'tcit-round1',
+ });
+ await seedToolCall({
+ content: 'No answer received within the wait window',
+ createdAt: new Date('2026-10-01T11:00:00Z'),
+ id: 'tcit-b',
+ topicId: 'tcit-round2',
+ });
+ await seedToolCall({
+ apiName: 'Bash',
+ content: 'ls',
+ createdAt: new Date('2026-10-01T11:30:00Z'),
+ id: 'tcit-bash',
+ topicId: 'tcit-round2',
+ });
+ await seedToolCall({
+ content: 'not this task',
+ createdAt: new Date('2026-10-01T12:00:00Z'),
+ id: 'tcit-unrelated-call',
+ topicId: 'tcit-unrelated',
+ });
+ await seedToolCall({
+ content: 'someone else',
+ createdAt: new Date('2026-10-01T12:00:00Z'),
+ id: 'tcit-foreign',
+ ownerId: otherUserId,
+ topicId: 'tcit-other',
+ });
+
+ const rows = await messageModel.listToolCallsInTopics({
+ apiName: 'askUserQuestion',
+ topicIds: ['tcit-round1', 'tcit-round2', 'tcit-other'],
+ });
+
+ expect(rows.map((row) => [row.topicId, row.content])).toEqual([
+ ['tcit-round1', 'User answers:\n- q: yes'],
+ ['tcit-round2', 'No answer received within the wait window'],
+ ]);
+ expect(JSON.parse(rows[0].arguments!)).toEqual({ questions: [{ question: 'tcit-a' }] });
+ });
+
+ it('keeps the newest calls when capped', async () => {
+ for (const [i, id] of ['tcit-1', 'tcit-2', 'tcit-3'].entries()) {
+ await seedToolCall({
+ content: id,
+ createdAt: new Date(Date.UTC(2026, 9, 1, 10 + i)),
+ id,
+ topicId: 'tcit-round1',
+ });
+ }
+
+ const rows = await messageModel.listToolCallsInTopics({
+ apiName: 'askUserQuestion',
+ limit: 2,
+ topicIds: ['tcit-round1'],
+ });
+
+ expect(rows.map((row) => row.content)).toEqual(['tcit-2', 'tcit-3']);
+ });
+
+ it('returns nothing for no topics', async () => {
+ expect(
+ await messageModel.listToolCallsInTopics({ apiName: 'askUserQuestion', topicIds: [] }),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/message/index.ts b/packages/database/src/models/message/index.ts
index b954ff23f23..633dd02e095 100644
--- a/packages/database/src/models/message/index.ts
+++ b/packages/database/src/models/message/index.ts
@@ -80,6 +80,7 @@ export class MessageModel {
findMessagePlugin: MessagePluginStore['findMessagePlugin'];
listMessagePluginsByTopic: MessagePluginStore['listMessagePluginsByTopic'];
findLatestPluginStateInTopic: MessagePluginStore['findLatestPluginStateInTopic'];
+ listToolCallsInTopics: MessagePluginStore['listToolCallsInTopics'];
listMessagePluginsForOperation: MessagePluginStore['listMessagePluginsForOperation'];
listMessagePluginsByIds: MessagePluginStore['listMessagePluginsByIds'];
findToolMessageIdByToolCallId: MessagePluginStore['findToolMessageIdByToolCallId'];
@@ -187,6 +188,7 @@ export class MessageModel {
this.findMessagePlugin = plugins.findMessagePlugin;
this.listMessagePluginsByTopic = plugins.listMessagePluginsByTopic;
this.findLatestPluginStateInTopic = plugins.findLatestPluginStateInTopic;
+ this.listToolCallsInTopics = plugins.listToolCallsInTopics;
this.listMessagePluginsForOperation = plugins.listMessagePluginsForOperation;
this.listMessagePluginsByIds = plugins.listMessagePluginsByIds;
this.findToolMessageIdByToolCallId = plugins.findToolMessageIdByToolCallId;
diff --git a/packages/database/src/models/message/plugin.ts b/packages/database/src/models/message/plugin.ts
index d5a214360c5..63df2d446d6 100644
--- a/packages/database/src/models/message/plugin.ts
+++ b/packages/database/src/models/message/plugin.ts
@@ -164,6 +164,50 @@ export class MessagePluginStore extends MessageScope {
}));
};
+ /**
+ * The newest calls to one tool API across several topics, oldest first, with
+ * the tool message's text — where a CLI adapter records the call's result.
+ * Lets a later run read what earlier runs of the same Task asked and got
+ * back, e.g. the owner's answers to `askUserQuestion`.
+ */
+ listToolCallsInTopics = async (params: {
+ apiName: string;
+ limit?: number;
+ topicIds: string[];
+ }): Promise<
+ Array<{ arguments?: string; content?: string; createdAt: Date; topicId: string | null }>
+ > => {
+ if (params.topicIds.length === 0) return [];
+
+ const rows = await this.db
+ .select({
+ arguments: messagePlugins.arguments,
+ content: messages.content,
+ createdAt: messages.createdAt,
+ id: messages.id,
+ topicId: messages.topicId,
+ })
+ .from(messagePlugins)
+ .innerJoin(messages, eq(messagePlugins.id, messages.id))
+ .where(
+ and(
+ inArray(messages.topicId, params.topicIds),
+ eq(messagePlugins.apiName, params.apiName),
+ this.ownership(),
+ this.pluginsOwnership(),
+ ),
+ )
+ .orderBy(desc(messages.createdAt), desc(messages.id))
+ .limit(params.limit ?? 20);
+
+ return rows.reverse().map((row) => ({
+ arguments: row.arguments ?? undefined,
+ content: row.content ?? undefined,
+ createdAt: row.createdAt,
+ topicId: row.topicId,
+ }));
+ };
+
/**
* The `state` of the most recent call to one tool API in a topic that
* produced any — a failed or aborted call leaves no state. Lets a tool read
diff --git a/packages/prompts/src/prompts/task/index.test.ts b/packages/prompts/src/prompts/task/index.test.ts
index f0b7d26e7e6..87f0853793e 100644
--- a/packages/prompts/src/prompts/task/index.test.ts
+++ b/packages/prompts/src/prompts/task/index.test.ts
@@ -736,6 +736,51 @@ describe('buildTaskRunPrompt', () => {
},
);
+ /**
+ * Regression: each round asked the owner the same questions, timed out,
+ * delivered "awaiting your confirmation", failed Acceptance and spawned the
+ * next round, which asked again. The round now sees what was already asked.
+ */
+ it('hands the next round the questions already asked and tells it not to re-ask', () => {
+ const result = buildTaskRunPrompt(
+ {
+ goalLoop: {
+ askedQuestions: [
+ {
+ answer: 'User answers:\n- 四项决策是否按推荐确认?: 是',
+ questions: ['四项决策是否按推荐确认?'],
+ },
+ {
+ answer: 'No answer received within the wait window; the user did not respond.',
+ questions: ['能不能在本机建虚拟屏?', '能不能装驱动?'],
+ },
+ { questions: ['ssh 被 1Password 挡住怎么办?'] },
+ ],
+ round: 3,
+ },
+ task: { ...baseTask, identifier: 'TASK-1', instruction: '对比设计', name: '对比设计' },
+ },
+ NOW,
+ );
+
+ expect(result).toContain('Questions earlier rounds already asked the owner');
+ expect(result).toContain('1. 四项决策是否按推荐确认?');
+ expect(result).toContain('- 四项决策是否按推荐确认?: 是');
+ expect(result).toContain('2. 能不能在本机建虚拟屏? / 能不能装驱动?');
+ expect(result).toContain('3. ssh 被 1Password 挡住怎么办?\n → (nothing came back)');
+ expect(result).toContain('Do not ask the owner again');
+ });
+
+ it('tells every later round not to re-ask, even with no recorded questions', () => {
+ const result = buildTaskRunPrompt(
+ { goalLoop: { round: 2 }, task: { ...baseTask, identifier: 'TASK-1', instruction: 'x' } },
+ NOW,
+ );
+
+ expect(result).not.toContain('Questions earlier rounds already asked');
+ expect(result).toContain('Do not ask the owner again');
+ });
+
it('omits the round budget suffix for uncapped goals', () => {
const result = buildTaskRunPrompt(
{
diff --git a/packages/prompts/src/prompts/task/index.ts b/packages/prompts/src/prompts/task/index.ts
index 2b0772f9209..285e329cb46 100644
--- a/packages/prompts/src/prompts/task/index.ts
+++ b/packages/prompts/src/prompts/task/index.ts
@@ -537,6 +537,12 @@ export interface TaskRunPromptWorkspaceNode {
* up without re-discovering everything.
*/
export interface TaskRunPromptGoalLoop {
+ /**
+ * Questions earlier rounds put to the owner, with what came back — their
+ * answer, or the notice that none arrived. Each round starts in a fresh
+ * conversation, so without this a round re-asked what the last one asked.
+ */
+ askedQuestions?: Array<{ answer?: string; questions: string[] }>;
/** Feedback from the automatic Acceptance review of the previous delivery. */
automaticReviewFeedback?: string;
/** Checks that did not pass in the previous round, with the verifier's why/suggestion. */
@@ -835,6 +841,20 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strin
taskLines.push(` ${i + 1}. ${check.title}${check.why ? ` — ${check.why}` : ''}`);
}
}
+ if (goalLoop.askedQuestions && goalLoop.askedQuestions.length > 0) {
+ taskLines.push(' Questions earlier rounds already asked the owner, and what came back:');
+ for (const [i, asked] of goalLoop.askedQuestions.entries()) {
+ taskLines.push(` ${i + 1}. ${asked.questions.join(' / ')}`);
+ const answer = asked.answer?.replaceAll(/\s+/g, ' ').trim();
+ taskLines.push(` → ${answer || '(nothing came back)'}`);
+ }
+ }
+ // Each round is a fresh conversation, and a run waits on nobody: a round
+ // that asked, timed out and delivered "awaiting your confirmation" failed
+ // Acceptance, and the next round asked the same thing again.
+ taskLines.push(
+ " Do not ask the owner again about anything an earlier round already asked or that the owner's feedback answers: treat those answers as final. If an earlier question got no answer, do not ask it again or wait for one — go with the option you would recommend, state it in your delivery as an assumption the owner can overturn, and finish the work.",
+ );
taskLines.push(
' To read a previous round in full, run: `lh task topic view ' +
task.identifier +