π€― 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): recover malformed tool_call names instead of finishing silently (#14577)
Arvin Xu0d39dff2d58d
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 651a0ccb27e..144e399119d 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -469,7 +469,7 @@ export class GeneralChatAgent implements Agent {case 'llm_result': {// LLM response received, check if it contains tool calls- const { hasToolsCalling, toolsCalling, parentMessageId } =+ const { hasToolsCalling, toolsCalling, parentMessageId, result } =context.payload as GeneralAgentCallLLMResultPayload;if (hasToolsCalling && toolsCalling && toolsCalling.length > 0) {@@ -516,12 +516,26 @@ export class GeneralChatAgent implements Agent {return instructions;}+ // Silent-drop diagnostic: LLM emitted raw tool_calls but every one+ // failed to resolve to a known tool (e.g. malformed names without the+ // `____` separator). Surface this in reasonDetail so dashboards can+ // distinguish it from a genuine no-tool completion. See LOBE-8696.+ const rawToolCallCount = result?.tool_calls?.length ?? 0;+ const hasUnresolvedToolCalls = rawToolCallCount > 0;+// No tool calls, conversation is completereturn {reason: state.forceFinish ? 'max_steps_completed' : 'completed',- reasonDetail: state.forceFinish- ? 'Force finish: LLM produced final text response after max steps'- : 'LLM response completed without tool calls',+ reasonDetail: hasUnresolvedToolCalls+ ? `LLM returned ${rawToolCallCount} unresolvable tool_calls: ${(+ result?.tool_calls ?? []+ )+ .map((tc) => tc.function?.name)+ .filter(Boolean)+ .join(', ')}`+ : state.forceFinish+ ? 'Force finish: LLM produced final text response after max steps'+ : 'LLM response completed without tool calls',type: 'finish',};}diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex 518e4c1e060..08a2fdb5921 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -176,6 +176,41 @@ describe('GeneralChatAgent', () => {});});+ // Regression for LOBE-8696: when the LLM emits tool_calls whose names+ // can't be resolved (e.g. `activateTools` instead of+ // `lobe-activator____activateTools`), the agent used to silently finish+ // with "completed without tool calls". Surface the unresolved names so+ // dashboards can spot the regression.+ it('should report unresolvable tool_calls in reasonDetail', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });++ const state = createMockState();+ const context = createMockContext('llm_result', {+ hasToolsCalling: true,+ toolsCalling: [],+ parentMessageId: 'msg-1',+ result: {+ content: '',+ tool_calls: [+ { id: 't1', type: 'function', function: { name: 'activateTools', arguments: '{}' } },+ { id: 't2', type: 'function', function: { name: 'activateSkill', arguments: '{}' } },+ ],+ },+ });++ const result = await agent.runner(context, state);++ expect(result).toEqual({+ type: 'finish',+ reason: 'completed',+ reasonDetail: 'LLM returned 2 unresolvable tool_calls: activateTools, activateSkill',+ });+ });+it('should return call_tool for single tool that does not need intervention', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },diff --git a/packages/context-engine/src/engine/tools/ToolNameResolver.ts b/packages/context-engine/src/engine/tools/ToolNameResolver.tsindex c64f63bbc34..173c3c1e58c 100644--- a/packages/context-engine/src/engine/tools/ToolNameResolver.ts+++ b/packages/context-engine/src/engine/tools/ToolNameResolver.ts@@ -79,19 +79,57 @@ export class ToolNameResolver {* Resolve tool calls from AI response back to original tool information* @param toolCalls - Tool calls from AI model response* @param manifests - Available tool manifests mapped by identifier+ * @param offeredToolNames - Tool names actually sent to the LLM in this turn+ * (e.g. `lobe-activator____activateTools`). When provided, the+ * missing-prefix fallback only considers tools in this list, so a model+ * can't trigger tools that weren't enabled for the current call and+ * disabled duplicates can't shadow enabled ones.* @returns Resolved tool payloads*/resolve(toolCalls: MessageToolCall[],manifests: Record<string, LobeToolManifest>,+ offeredToolNames?: string[],): ChatToolPayload[] {+ const offeredSet = offeredToolNames ? new Set(offeredToolNames) : null;+return toolCalls.map((toolCall): ChatToolPayload | null => {- const [initialIdentifier, apiName, type] =+ const [initialIdentifier, initialApiName, type] =toolCall.function.name.split(PLUGIN_SCHEMA_SEPARATOR);let identifier = initialIdentifier;-- if (!apiName) return null;+ let apiName = initialApiName;++ // Fallback for malformed tool names without the `____` separator+ // (e.g. model returns "activateTools" instead of+ // "lobe-activator____activateTools"). When the bare name uniquely+ // matches an API across the manifests we're allowed to consider,+ // recover the identifier so we don't silently drop the tool call.+ // The manifest's `type` is picked up by the existing `type ??+ // manifests[identifier]?.type` fallback when building the payload.+ if (!apiName) {+ const bareName = initialIdentifier;+ const matches: string[] = [];+ for (const [id, manifest] of Object.entries(manifests)) {+ const matchedApi = manifest?.api?.find(+ (api: LobeChatPluginApi) => api.name === bareName,+ );+ if (!matchedApi) continue;+ // Restrict to tools actually offered to the LLM this turn so a+ // model can't reach tools that weren't enabled, and so disabled+ // duplicates don't make an enabled call look ambiguous.+ if (offeredSet && !offeredSet.has(this.generate(id, matchedApi.name, manifest.type))) {+ continue;+ }+ matches.push(id);+ }+ if (matches.length === 1) {+ identifier = matches[0];+ apiName = bareName;+ } else {+ return null;+ }+ }// Step 1: Resolve hashed identifier if neededif (identifier.startsWith(PLUGIN_SCHEMA_API_MD5_PREFIX)) {diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.tsindex d0be34a5340..18b54c35795 100644--- a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts+++ b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts@@ -714,6 +714,255 @@ describe('ToolNameResolver', () => {expect(result).toEqual([]);});+ // Regression for LOBE-8696: some models (e.g. deepseek-v4-pro) drop the+ // `<identifier>____` prefix and emit only the bare API name. When that+ // bare name uniquely matches an API in the available manifests, we should+ // recover the identifier from the manifest instead of silently dropping+ // the call (which previously caused empty assistant bubbles).+ describe('resolve - missing-prefix fallback', () => {+ it('should recover identifier when bare API name uniquely matches a manifest', () => {+ const toolCalls = [+ {+ function: { arguments: '{"toolIds": ["foo"]}', name: 'activateTools' },+ id: 'call_1',+ type: 'function',+ },+ ];++ const manifests = {+ 'lobe-activator': {+ api: [{ description: 'Activate tools', name: 'activateTools', parameters: {} }],+ identifier: 'lobe-activator',+ meta: {},+ type: 'builtin' as const,+ },+ 'lobe-skills': {+ api: [{ description: 'Activate skill', name: 'activateSkill', parameters: {} }],+ identifier: 'lobe-skills',+ meta: {},+ type: 'builtin' as const,+ },+ };++ const result = resolver.resolve(toolCalls, manifests);++ expect(result).toHaveLength(1);+ expect(result[0]).toEqual({+ apiName: 'activateTools',+ arguments: '{"toolIds": ["foo"]}',+ id: 'call_1',+ identifier: 'lobe-activator',+ type: 'builtin',+ });+ });++ it('should drop bare API names when no manifest exposes them', () => {+ const toolCalls = [+ {+ function: { arguments: '{}', name: 'unknownAction' },+ id: 'call_1',+ type: 'function',+ },+ ];++ const manifests = {+ 'lobe-activator': {+ api: [{ description: '', name: 'activateTools', parameters: {} }],+ identifier: 'lobe-activator',+ meta: {},+ type: 'builtin' as const,+ },+ };++ const result = resolver.resolve(toolCalls, manifests);++ expect(result).toEqual([]);+ });++ it('should drop bare API names when multiple manifests expose the same name (ambiguous)', () => {+ const toolCalls = [+ {+ function: { arguments: '{}', name: 'createDocument' },+ id: 'call_1',+ type: 'function',+ },+ ];++ const manifests = {+ 'lobe-agent-documents': {+ api: [{ description: '', name: 'createDocument', parameters: {} }],+ identifier: 'lobe-agent-documents',+ meta: {},+ type: 'builtin' as const,+ },+ 'lobe-notebook': {+ api: [{ description: '', name: 'createDocument', parameters: {} }],+ identifier: 'lobe-notebook',+ meta: {},+ type: 'builtin' as const,+ },+ };++ const result = resolver.resolve(toolCalls, manifests);++ expect(result).toEqual([]);+ });++ it('should preserve manifest type when recovering identifier', () => {+ const toolCalls = [+ {+ function: { arguments: '{}', name: 'open_page' },+ id: 'call_1',+ type: 'function',+ },+ ];++ const manifests = {+ 'mcp-browser': {+ api: [{ description: '', name: 'open_page', parameters: {} }],+ identifier: 'mcp-browser',+ meta: {},+ type: 'mcp' as const,+ },+ };++ const result = resolver.resolve(toolCalls, manifests);++ expect(result).toHaveLength(1);+ expect(result[0].identifier).toBe('mcp-browser');+ expect(result[0].apiName).toBe('open_page');+ expect(result[0].type).toBe('mcp');+ });++ // The fallback's manifests map can be broader than the tools actually+ // sent to the LLM (e.g. the client builds it from every installed+ // plugin and every builtin). Without a turn-scope restriction, a+ // malformed bare name could resolve to a tool that wasn't enabled, or+ // a disabled duplicate could shadow an enabled call. The optional+ // `offeredToolNames` parameter restricts the fallback to tools that+ // were actually offered this turn.+ it('should restrict fallback to tools actually offered this turn', () => {+ const toolCalls = [+ {+ function: { arguments: '{}', name: 'activateTools' },+ id: 'call_1',+ type: 'function',+ },+ ];++ const manifests = {+ 'lobe-activator': {+ api: [{ description: '', name: 'activateTools', parameters: {} }],+ identifier: 'lobe-activator',+ meta: {},+ type: 'builtin' as const,+ },+ // Disabled this turn β must not be reachable via fallback+ 'lobe-activator-deprecated': {+ api: [{ description: '', name: 'activateTools', parameters: {} }],+ identifier: 'lobe-activator-deprecated',+ meta: {},+ type: 'builtin' as const,+ },+ };++ const result = resolver.resolve(toolCalls, manifests, ['lobe-activator____activateTools']);++ expect(result).toHaveLength(1);+ expect(result[0].identifier).toBe('lobe-activator');+ expect(result[0].apiName).toBe('activateTools');+ });++ it('should drop bare API names whose tool was not offered this turn', () => {+ const toolCalls = [+ {+ function: { arguments: '{}', name: 'activateTools' },+ id: 'call_1',+ type: 'function',+ },+ ];++ const manifests = {+ 'lobe-activator': {+ api: [{ description: '', name: 'activateTools', parameters: {} }],+ identifier: 'lobe-activator',+ meta: {},+ type: 'builtin' as const,+ },+ };++ // Manifest exists but the tool was not sent to the LLM this turn.+ const result = resolver.resolve(toolCalls, manifests, ['lobe-skills____activateSkill']);++ expect(result).toEqual([]);+ });++ it('should treat an enabled call as unique when a disabled duplicate would have made it ambiguous', () => {+ const toolCalls = [+ {+ function: { arguments: '{}', name: 'createDocument' },+ id: 'call_1',+ type: 'function',+ },+ ];++ const manifests = {+ // Only this manifest's createDocument is offered this turn.+ 'lobe-agent-documents': {+ api: [{ description: '', name: 'createDocument', parameters: {} }],+ identifier: 'lobe-agent-documents',+ meta: {},+ type: 'builtin' as const,+ },+ // Installed but not offered β without the offered-list restriction+ // this would make the fallback ambiguous and drop the valid call.+ 'lobe-notebook': {+ api: [{ description: '', name: 'createDocument', parameters: {} }],+ identifier: 'lobe-notebook',+ meta: {},+ type: 'builtin' as const,+ },+ };++ const result = resolver.resolve(toolCalls, manifests, [+ 'lobe-agent-documents____createDocument',+ ]);++ expect(result).toHaveLength(1);+ expect(result[0].identifier).toBe('lobe-agent-documents');+ });++ it('should respect hashed offered names when matching', () => {+ const identifier = 'mcp-server';+ const apiName = 'get.current/weather';+ // generate produces a hashed tool name for invalid characters+ const offeredName = resolver.generate(identifier, apiName, 'mcp');++ const toolCalls = [+ {+ function: { arguments: '{}', name: apiName },+ id: 'call_1',+ type: 'function',+ },+ ];++ const manifests = {+ [identifier]: {+ api: [{ description: '', name: apiName, parameters: {} }],+ identifier,+ meta: {},+ type: 'mcp' as const,+ },+ };++ const result = resolver.resolve(toolCalls, manifests, [offeredName]);++ expect(result).toHaveLength(1);+ expect(result[0].identifier).toBe(identifier);+ expect(result[0].apiName).toBe(apiName);+ });+ });+it('should handle tool calls with different types', () => {const toolCalls = [{diff --git a/src/store/chat/agents/StreamingHandler.ts b/src/store/chat/agents/StreamingHandler.tsindex 679d4cf2e87..5f9dab34fda 100644--- a/src/store/chat/agents/StreamingHandler.ts+++ b/src/store/chat/agents/StreamingHandler.ts@@ -464,7 +464,26 @@ export class StreamingHandler {},}));- this.tools = this.callbacks.transformToolCalls(processedToolCalls);+ const resolved = this.callbacks.transformToolCalls(processedToolCalls);++ // Silent-drop guard: the model emitted tool_calls but every name failed to+ // resolve (e.g. missing `____` prefix the resolver couldn't recover from).+ // Without this log the operation would finish as "completed without tool+ // calls" even though the user's intent was lost. See LOBE-8696.+ if (resolved.length < processedToolCalls.length) {+ const resolvedKeys = new Set(resolved.map((t) => t.id));+ const unresolved = processedToolCalls+ .filter((t) => !resolvedKeys.has(t.id))+ .map((t) => t.function.name);+ log(+ '[processFinalToolCalls] unresolved tool_call names messageId=%s, operationId=%s, names=%o',+ this.context.messageId,+ this.context.operationId,+ unresolved,+ );+ }++ this.tools = resolved;this.isFunctionCall = true;}diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.tsindex 71f16704d15..156e46a5dce 100644--- a/src/store/chat/agents/createAgentExecutors.ts+++ b/src/store/chat/agents/createAgentExecutors.ts@@ -317,6 +317,58 @@ export const createAgentExecutors = (context: {let finalUsage: ModelUsage | undefined;let finalToolCalls: MessageToolCall[] | undefined;+ // Expand dynamically activated tools (from lobe-activator activateTools API)+ // and merge them into the agent config for this LLM call.+ // Built before the StreamingHandler so we can bind the offered tool+ // names into the transformToolCalls callback (LOBE-8696).+ const activatedToolIds = runtimeContext?.stepContext?.activatedToolIds;+ let resolvedAgentConfig = context.agentConfig;++ if (activatedToolIds?.length && context.toolsEngine) {+ const additional = context.toolsEngine.generateToolsDetailed({+ context: { isExplicitActivation: true },+ model: agentConfigData.model,+ provider: agentConfigData.provider!,+ skipDefaultTools: true,+ toolIds: activatedToolIds,+ });++ if (additional.tools?.length) {+ const mergedEnabledManifests = dedupeBy(+ [...(context.agentConfig.enabledManifests || []), ...additional.enabledManifests],+ (manifest) => manifest.identifier,+ );+ const mergedEnabledToolIds = [+ ...new Set([+ ...(context.agentConfig.enabledToolIds || []),+ ...additional.enabledToolIds,+ ]),+ ];+ const mergedTools = dedupeBy(+ [...(context.agentConfig.tools || []), ...additional.tools],+ (tool) => tool.function.name,+ );++ resolvedAgentConfig = {+ ...context.agentConfig,+ enabledManifests: mergedEnabledManifests,+ enabledToolIds: mergedEnabledToolIds,+ tools: mergedTools,+ };++ log(+ `${stagePrefix} Injected %d activated tools: %o`,+ activatedToolIds.length,+ activatedToolIds,+ );+ }+ }++ // Names of tools actually sent to the LLM this turn. Passed to the+ // resolver's missing-prefix fallback so a model can't reach tools that+ // weren't enabled, and disabled duplicates can't shadow enabled calls.+ const offeredToolNames = (resolvedAgentConfig.tools ?? []).map((tool) => tool.function.name);+// Create streaming handler with callbacksconst handler = new StreamingHandler({@@ -404,58 +456,14 @@ export const createAgentExecutors = (context: {url: file?.url,alt: file?.filename || file?.id,})),- transformToolCalls: context.get().internal_transformToolCalls,+ transformToolCalls: (calls) =>+ context.get().internal_transformToolCalls(calls, offeredToolNames),toggleToolCallingStreaming: internal_toggleToolCallingStreaming,},);const messages = llmPayload.messages.filter((message) => message.id !== assistantMessageId);- // Expand dynamically activated tools (from lobe-activator activateTools API)- // and merge them into the agent config for this LLM call- const activatedToolIds = runtimeContext?.stepContext?.activatedToolIds;- let resolvedAgentConfig = context.agentConfig;-- if (activatedToolIds?.length && context.toolsEngine) {- const additional = context.toolsEngine.generateToolsDetailed({- context: { isExplicitActivation: true },- model: agentConfigData.model,- provider: agentConfigData.provider!,- skipDefaultTools: true,- toolIds: activatedToolIds,- });-- if (additional.tools?.length) {- const mergedEnabledManifests = dedupeBy(- [...(context.agentConfig.enabledManifests || []), ...additional.enabledManifests],- (manifest) => manifest.identifier,- );- const mergedEnabledToolIds = [- ...new Set([- ...(context.agentConfig.enabledToolIds || []),- ...additional.enabledToolIds,- ]),- ];- const mergedTools = dedupeBy(- [...(context.agentConfig.tools || []), ...additional.tools],- (tool) => tool.function.name,- );-- resolvedAgentConfig = {- ...context.agentConfig,- enabledManifests: mergedEnabledManifests,- enabledToolIds: mergedEnabledToolIds,- tools: mergedTools,- };-- log(- `${stagePrefix} Injected %d activated tools: %o`,- activatedToolIds.length,- activatedToolIds,- );- }- }-await chatService.createAssistantMessageStream({abortController,params: {diff --git a/src/store/chat/slices/plugin/actions/internals.ts b/src/store/chat/slices/plugin/actions/internals.tsindex 6a55e24e970..bb1d59325e7 100644--- a/src/store/chat/slices/plugin/actions/internals.ts+++ b/src/store/chat/slices/plugin/actions/internals.ts@@ -27,7 +27,10 @@ export class PluginInternalsActionImpl {void get;}- internal_transformToolCalls = (toolCalls: MessageToolCall[]): ChatToolPayload[] => {+ internal_transformToolCalls = (+ toolCalls: MessageToolCall[],+ offeredToolNames?: string[],+ ): ChatToolPayload[] => {const toolNameResolver = new ToolNameResolver();// Build manifests map from tool store@@ -73,7 +76,7 @@ export class PluginInternalsActionImpl {}// Resolve tool calls and add source field- const resolved = toolNameResolver.resolve(toolCalls, manifests);+ const resolved = toolNameResolver.resolve(toolCalls, manifests, offeredToolNames);return resolved.map((payload) => {// Parse and repair arguments if needed