🤯 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(agent-runtime): explain credit exhaustion in failed sub-agent results (#20067)
Arvin Xu7054df10aefc
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex ab35cb4ebe6..2e53facdaae 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -3761,6 +3761,85 @@ describe('AgentRuntimeService', () => {expect(call.pluginError).toEqual({ message: 'Operation abandoned: inactivity_watchdog' });});+ // "Budget exceeded" alone reads like a per-sub-agent allowance, so parents+ // retried or fanned out more sub-agents against the same exhausted limit.+ describe('billing-limit failures', () => {+ const budgetError = (type: string, budgetTypeAtError?: string) => ({+ body: {+ budget: {+ availableCredits: 24_659,+ budgetTypeAtError,+ requiredCredits: 50_638,+ },+ message: 'Budget exceeded',+ },+ message: 'Budget exceeded',+ type,+ });+ const bridgeContent = async (error: unknown) => {+ await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: { ...childState, error } as any,+ reason: 'error',+ });+ return updateToolMessage.mock.calls.at(-1)?.[1];+ };++ it('explains a personal credit shortfall without quoting the balance', async () => {+ const error = budgetError('InsufficientBudgetForModel', 'subscription');+ const call = await bridgeContent(error);++ expect(call.content).toBe(+ 'Sub-agent did not complete (error): stopped by a LobeHub billing limit (InsufficientBudgetForModel): ' ++ "the account's LobeHub credits are too low for this model; the account owner has to top up or upgrade. " ++ 'This limit is shared by every sub-agent and by this conversation, so retrying or dispatching more sub-agents on the same model will not get past it; ' ++ 'a sub-agent that runs on a less expensive model may still fit. ' ++ 'Otherwise finish with what you already have and tell the user about the limit.',+ );+ expect(call.content).not.toMatch(/24659|24,659|50638/);+ expect(call.pluginError).toEqual(error);+ });++ it.each([+ [+ 'workspace',+ "the workspace's shared LobeHub credits can't cover this model's estimated cost",+ ],+ [+ 'workspace_member',+ "this member's workspace credit allowance can't cover this model's estimated cost",+ ],+ ])('names the %s allowance as the one to raise', async (scope, expected) => {+ const call = await bridgeContent(budgetError('InsufficientBudgetForModel', scope));++ expect(call.content).toContain(expected);+ expect(call.content).not.toContain('top up');+ });++ it('points plan-limit failures at the plan, not at credits', async () => {+ const call = await bridgeContent(budgetError('SubscriptionPlanLimit', 'subscription'));++ expect(call.content).toContain(+ 'plan limit was reached or the plan does not cover this model',+ );+ });++ // InsufficientBudgetForModel still leaves credits in the allowance, so a+ // cheaper model can fit; only an exhausted plan makes every dispatch futile.+ it('keeps the cheaper-model path open for a model-cost shortfall only', async () => {+ const shortfall = await bridgeContent(+ budgetError('InsufficientBudgetForModel', 'workspace_member'),+ );+ expect(shortfall.content).toContain('on the same model will not get past it');+ expect(shortfall.content).toContain('less expensive model may still fit');++ const exhausted = await bridgeContent(budgetError('FreePlanLimit', 'workspace'));+ expect(exhausted.content).toContain("the workspace's shared LobeHub credits are used up");+ expect(exhausted.content).toContain('more sub-agents will not get past it');+ expect(exhausted.content).not.toContain('less expensive model');+ });+ });+it('truncates an oversized child error so it cannot bloat the parent context', async () => {const huge = 'x'.repeat(500);await service.completeSubAgentBridge({diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex c2363c56f21..94caa98e765 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -43,7 +43,7 @@ import {type ExecVirtualSubAgentParams,type UIChatMessage,} from '@lobechat/types';-import { RequestTrigger } from '@lobechat/types';+import { ChatErrorType, RequestTrigger } from '@lobechat/types';import { isRecord } from '@lobechat/utils/object';import debug from 'debug';import urlJoin from 'url-join';@@ -303,6 +303,60 @@ const formatErrorForMetadata = (error: unknown): Record<string, any> | undefinedreturn { message: String(error) };};+const SUB_AGENT_CREDIT_ERROR_TYPES = new Set<string>([+ ChatErrorType.FreePlanLimit,+ ChatErrorType.InsufficientBudgetForModel,+ ChatErrorType.SubscriptionPlanLimit,+]);++/**+ * A child stopped by the cost-admission gate fails with the bare message+ * "Budget exceeded", which reads like a per-sub-agent allowance. The parent+ * then retries or fans out more sub-agents against the same limit. Say which+ * limit it is and who can lift it.+ *+ * Mirrors the bot reply copy (`bot/replyTemplate.ts`): the payer is not+ * addressed as "you" and figures are never quoted, because a bot run is billed+ * to its owner while the parent's reply may reach a shared channel.+ */+const formatSubAgentCreditErrorReason = (error: unknown): string | undefined => {+ if (!error || typeof error !== 'object') return;+ const { body, errorType, type } = error as {+ body?: { budget?: { budgetTypeAtError?: unknown } };+ errorType?: unknown;+ type?: unknown;+ };+ const creditType = [type, errorType].find(+ (value): value is string =>+ typeof value === 'string' && SUB_AGENT_CREDIT_ERROR_TYPES.has(value),+ );+ if (!creditType) return;++ const budgetType = body?.budget?.budgetTypeAtError;+ // InsufficientBudgetForModel means the allowance still has credits, just not+ // enough for this model's estimated cost — a cheaper model may still fit, so+ // the no-retry claim only holds for the same model (bot/replyTemplate gives+ // the same "switch to a less expensive model" advice).+ const modelCostShortfall = creditType === ChatErrorType.InsufficientBudgetForModel;+ const shortfall = modelCostShortfall ? "can't cover this model's estimated cost" : 'are used up';+ const limit =+ budgetType === 'workspace'+ ? `the workspace's shared LobeHub credits ${shortfall}; a workspace admin has to add credits`+ : budgetType === 'workspace_member'+ ? `this member's workspace credit allowance ${modelCostShortfall ? shortfall : 'is used up'}; a workspace admin has to raise it`+ : modelCostShortfall+ ? "the account's LobeHub credits are too low for this model; the account owner has to top up or upgrade"+ : "the account's LobeHub plan limit was reached or the plan does not cover this model; the account owner has to upgrade the plan";++ const advice = modelCostShortfall+ ? 'This limit is shared by every sub-agent and by this conversation, so retrying or dispatching more sub-agents on the same model will not get past it; a sub-agent that runs on a less expensive model may still fit. ' ++ 'Otherwise finish with what you already have and tell the user about the limit.'+ : 'This limit is shared by every sub-agent and by this conversation, so retrying or dispatching more sub-agents will not get past it. ' ++ 'Finish with what you already have and tell the user about the limit.';++ return `stopped by a LobeHub billing limit (${creditType}): ${limit}. ${advice}`;+};+/*** Extract a short, human-readable reason string from a failed operation's* `state.error`, for inlining into the tool-result `content` a parent agent@@ -313,6 +367,9 @@ const formatErrorForMetadata = (error: unknown): Record<string, any> | undefined* error still rides on `pluginError`; this is just the readable summary.*/const formatSubAgentErrorReason = (error: unknown): string | undefined => {+ const creditReason = formatSubAgentCreditErrorReason(error);+ if (creditReason) return creditReason;+const message = formatErrorForMetadata(error)?.message;if (typeof message !== 'string') return undefined;const trimmed = message.trim();