π€― 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 garbled tool names instead of ending the turn (#19362)
Arvin Xu18131e9f754a
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 5a186f2b1b5..8143d5f7f58 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -30,6 +30,22 @@ import { shouldCompress } from '../utils/tokenCounter';const TOOL_NOT_ALLOWED_CONTENT ='Tool execution blocked because the tool is not allowed in the current execution scope.';const TOOL_NOT_ALLOWED_REASON = 'tool_not_allowed';+/**+ * Names the offending calls so the model sees what it actually emitted. The+ * name it reads back from its own turn is regenerated from the persisted+ * identifier/apiName pair, which for an unparseable name is not what it typed.+ */+const unresolvedToolContent = (names: string) =>+ `Tool call rejected: no available tool is named ${names}. Copy a name exactly as declared in the tools schema and call it again.`;+const UNRESOLVED_TOOL_REASON = 'tool_name_unresolved';+/**+ * How many times one operation may answer unresolvable tool calls with a+ * rejected tool result before giving up. The feedback exists so the model can+ * fix a garbled name; a model that keeps emitting names nothing can match is+ * broken, and failing loudly beats burning the step budget on it.+ */+const UNRESOLVED_TOOL_FEEDBACK_LIMIT = 2;+const PLUGIN_SCHEMA_SEPARATOR = '____';// Leave 35% of the model window for server-side context engineering (system// role, knowledge, memories, skills, etc.) and the model's completion. The// initial 50% threshold still supplies the lower side of the hysteresis band.@@ -757,26 +773,75 @@ 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 .- const rawToolCallCount = result?.tool_calls?.length ?? 0;- const hasUnresolvedToolCalls = rawToolCallCount > 0;+ // The model asked for tools but not one name resolved β it garbled the+ // `____` separator beyond repair, or named a tool that was never+ // offered. Finishing here would write an empty assistant message and+ // mark the operation `done` while the requested work never ran, which+ // reads as a conversation that just stopped mid-task. Hand the model a+ // rejected tool result instead so it can retry with a real name.+ const rawToolCalls = result?.tool_calls ?? [];+ if (rawToolCalls.length > 0) {+ const namedToolCalls = rawToolCalls.filter((toolCall) => !!toolCall.function?.name);+ const unresolvedNames = namedToolCalls+ .map((toolCall) => toolCall.function.name)+ .join(', ');+ const overFeedbackLimit =+ (state.unresolvedToolFeedbackRounds ?? 0) >= UNRESOLVED_TOOL_FEEDBACK_LIMIT;++ // Past max steps the LLM payload carries no tools at all, so a tool+ // call here is the model ignoring that. The run is already over+ // budget β end it rather than spending more steps on a retry, and+ // keep the names for the dashboards.+ if (state.forceFinish) {+ return {+ reason: 'max_steps_completed',+ reasonDetail: `LLM returned ${rawToolCalls.length} unresolvable tool_calls after max steps: ${unresolvedNames || 'unnamed'}`,+ type: 'finish',+ };+ }++ // Nothing addressable to reject (nameless calls), or the model has+ // already been told twice: fail the operation so it surfaces as an+ // error instead of a silent `done`.+ if (namedToolCalls.length === 0 || overFeedbackLimit) {+ throw new Error(+ `LLM returned ${rawToolCalls.length} unresolvable tool_calls: ${unresolvedNames || 'unnamed'}`,+ );+ }++ return {+ payload: {+ blockedContent: unresolvedToolContent(unresolvedNames),+ blockedReason: UNRESOLVED_TOOL_REASON,+ parentMessageId,+ unresolvedToolNames: true,+ toolsCalling: namedToolCalls.map((toolCall): ChatToolPayload => {+ const [identifier, apiName] = toolCall.function.name.split(PLUGIN_SCHEMA_SEPARATOR);++ return {+ apiName: apiName ?? identifier,+ arguments: toolCall.function.arguments,+ id: toolCall.id,+ identifier,+ // A garbled name does not mean a garbled signature: Gemini+ // 3.x still requires `thoughtSignature` to come back on the+ // next turn or it 400s, which would kill the retry this+ // rejection exists to enable.+ thoughtSignature: toolCall.thoughtSignature,+ type: 'builtin',+ };+ }),+ },+ type: 'resolve_blocked_tools',+ } satisfies AgentInstruction;+ }// No tool calls, conversation is completereturn {reason: state.forceFinish ? 'max_steps_completed' : 'completed',- 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',+ reasonDetail: 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 b3cb672a2e3..b63864c37e8 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -300,12 +300,12 @@ describe('GeneralChatAgent', () => {});});- // Regression for 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 () => {+ // Regression: when the LLM emits tool_calls whose names can't be resolved+ // (e.g. `activateTools` instead of `lobe-activator____activateTools`), the+ // agent used to finish with "completed without tool calls", writing an+ // empty assistant message while the requested work never ran. Reject the+ // calls instead so the model can retry with a real name.+ it('should reject unresolvable tool_calls so the model can retry', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },operationId: 'test-session',@@ -321,18 +321,192 @@ describe('GeneralChatAgent', () => {content: '',tool_calls: [{ id: 't1', type: 'function', function: { name: 'activateTools', arguments: '{}' } },- { id: 't2', type: 'function', function: { name: 'activateSkill', arguments: '{}' } },+ {+ id: 't2',+ type: 'function',+ function: { name: 'lobe-skills____activateSkill', arguments: '{"a":1}' },+ },],},});const result = await agent.runner(context, state);+ expect(result).toEqual({+ type: 'resolve_blocked_tools',+ payload: {+ blockedContent:+ 'Tool call rejected: no available tool is named activateTools, lobe-skills____activateSkill. Copy a name exactly as declared in the tools schema and call it again.',+ blockedReason: 'tool_name_unresolved',+ parentMessageId: 'msg-1',+ unresolvedToolNames: true,+ toolsCalling: [+ {+ apiName: 'activateTools',+ arguments: '{}',+ id: 't1',+ identifier: 'activateTools',+ type: 'builtin',+ },+ {+ apiName: 'activateSkill',+ arguments: '{"a":1}',+ id: 't2',+ identifier: 'lobe-skills',+ type: 'builtin',+ },+ ],+ },+ });+ });++ it('should fail the operation once the unresolvable-tool feedback budget is spent', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });++ const state = createMockState({ unresolvedToolFeedbackRounds: 2 });+ const context = createMockContext('llm_result', {+ hasToolsCalling: true,+ toolsCalling: [],+ parentMessageId: 'msg-1',+ result: {+ content: '',+ tool_calls: [+ { id: 't2', type: 'function', function: { name: 'activateTools', arguments: '{}' } },+ ],+ },+ });++ await expect(agent.runner(context, state)).rejects.toThrow(+ 'LLM returned 1 unresolvable tool_calls: activateTools',+ );+ });++ // Gemini 3.x 400s on the next tool-call turn unless `thoughtSignature` is+ // round-tripped, which would kill the retry the rejection exists to enable.+ it('should keep the thought signature of an unresolvable tool call', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });++ const context = createMockContext('llm_result', {+ hasToolsCalling: true,+ toolsCalling: [],+ parentMessageId: 'msg-1',+ result: {+ content: '',+ tool_calls: [+ {+ id: 't1',+ type: 'function',+ function: { name: 'activateTools', arguments: '{}' },+ thoughtSignature: 'EoMYCoAYA_gemini3_thought_signature_fixture',+ },+ ],+ },+ });++ const result = await agent.runner(context, createMockState());++ expect((result as any).payload.toolsCalling[0]).toEqual(+ expect.objectContaining({+ id: 't1',+ thoughtSignature: 'EoMYCoAYA_gemini3_thought_signature_fixture',+ }),+ );+ });++ it('should finish instead of retrying unresolvable tool_calls past max steps', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });++ const context = createMockContext('llm_result', {+ hasToolsCalling: true,+ toolsCalling: [],+ parentMessageId: 'msg-1',+ result: {+ content: '',+ tool_calls: [+ { id: 't1', type: 'function', function: { name: 'activateTools', arguments: '{}' } },+ ],+ },+ });++ const result = await agent.runner(context, createMockState({ forceFinish: true }));+expect(result).toEqual({type: 'finish',- reason: 'completed',- reasonDetail: 'LLM returned 2 unresolvable tool_calls: activateTools, activateSkill',+ reason: 'max_steps_completed',+ reasonDetail: 'LLM returned 1 unresolvable tool_calls after max steps: activateTools',+ });+ });++ // The message history is rehydrated from the DB every step and carries+ // rejections written by earlier operations, so the budget has to be+ // operation-scoped state rather than a count of matching tool rows.+ it('should not spend the budget on rejections from earlier operations', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });++ const rejection = {+ content:+ 'Tool call rejected: no available tool is named activateTools. Copy a name exactly as declared in the tools schema and call it again.',+ role: 'tool' as const,+ };+ const state = createMockState({+ messages: [+ { ...rejection, id: 'tool-1', tool_call_id: 'old-1' },+ { ...rejection, id: 'tool-2', tool_call_id: 'old-2' },+ ] as AgentState['messages'],});+ const context = createMockContext('llm_result', {+ hasToolsCalling: true,+ toolsCalling: [],+ parentMessageId: 'msg-1',+ result: {+ content: '',+ tool_calls: [+ { id: 't1', type: 'function', function: { name: 'activateTools', arguments: '{}' } },+ ],+ },+ });++ const result = await agent.runner(context, state);++ expect((result as any).type).toBe('resolve_blocked_tools');+ });++ it('should fail when unresolvable tool_calls carry no name to reject', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });++ const context = createMockContext('llm_result', {+ hasToolsCalling: true,+ toolsCalling: [],+ parentMessageId: 'msg-1',+ result: {+ content: '',+ tool_calls: [{ id: 't1', type: 'function', function: { name: '', arguments: '{}' } }],+ },+ });++ await expect(agent.runner(context, createMockState())).rejects.toThrow(+ 'LLM returned 1 unresolvable tool_calls: unnamed',+ );});it('should return call_tool for single tool that does not need intervention', async () => {diff --git a/packages/agent-runtime/src/executors/resolveTools.test.ts b/packages/agent-runtime/src/executors/resolveTools.test.tsindex 1b9747877a7..cdfa09d4327 100644--- a/packages/agent-runtime/src/executors/resolveTools.test.ts+++ b/packages/agent-runtime/src/executors/resolveTools.test.ts@@ -145,6 +145,79 @@ describe('resolveTools executors', () => {);});+ // Without this write the rejection is lost: state messages are rebuilt from+ // the DB every step, and conversation-flow only collects a tool row whose+ // parent assistant lists the matching call.+ it('advertises unresolvable calls on the parent assistant and counts the round', async () => {+ const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {+ payload: {+ blockedContent: 'Tool call rejected: no available tool is named searchh.',+ blockedReason: 'tool_name_unresolved',+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [createToolCall()],+ unresolvedToolNames: true,+ },+ type: 'resolve_blocked_tools',+ };++ const result = await resolveBlockedTools(host)(instruction, createState());++ expect(host.transports.messages.update).toHaveBeenCalledWith('assistant-msg-1', {+ tools: [createToolCall()],+ });+ expect(result.newState.unresolvedToolFeedbackRounds).toBe(1);+ });++ it('accumulates unresolvable rounds across steps of one operation', async () => {+ const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [createToolCall()],+ unresolvedToolNames: true,+ },+ type: 'resolve_blocked_tools',+ };++ const result = await resolveBlockedTools(host)(+ instruction,+ createState({ unresolvedToolFeedbackRounds: 1 }),+ );++ expect(result.newState.unresolvedToolFeedbackRounds).toBe(2);+ });++ it('leaves the parent untouched for ordinary blocked tools', async () => {+ const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [createToolCall()],+ },+ type: 'resolve_blocked_tools',+ };++ const result = await resolveBlockedTools(host)(instruction, createState());++ expect(host.transports.messages.update).not.toHaveBeenCalled();+ expect(result.newState.unresolvedToolFeedbackRounds).toBeUndefined();+ });++ it('fails loudly when the parent assistant cannot be updated', async () => {+ const failure = new Error('db down');+ host.transports.messages.update = vi.fn().mockRejectedValue(failure);++ const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [createToolCall()],+ unresolvedToolNames: true,+ },+ type: 'resolve_blocked_tools',+ };++ await expect(resolveBlockedTools(host)(instruction, createState())).rejects.toThrow('db down');+ expect(createToolMessage).not.toHaveBeenCalled();+ });+it('persists a caller-provided blocked reason and content', async () => {const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {payload: {diff --git a/packages/agent-runtime/src/executors/resolveTools.ts b/packages/agent-runtime/src/executors/resolveTools.tsindex 1ad0efdcaf9..9ef119436ad 100644--- a/packages/agent-runtime/src/executors/resolveTools.ts+++ b/packages/agent-runtime/src/executors/resolveTools.ts@@ -50,6 +50,25 @@ export const resolveBlockedTools =);}+ // Unresolvable names never made it into the parent assistant's `tools`,+ // because resolution produced nothing to persist. Put them there before the+ // rows exist: every step rebuilds `state.messages` from the DB, and+ // conversation-flow only collects a tool row whose parent lists the call, so+ // an unadvertised rejection is dropped on the way back in and the model+ // never learns its tool name was wrong.+ if (payload.unresolvedToolNames) {+ try {+ await transports.messages.update(payload.parentMessageId, {+ tools: payload.toolsCalling,+ });+ } catch (error) {+ await publishPersistError(host, error);+ throw error;+ }++ newState.unresolvedToolFeedbackRounds = (state.unresolvedToolFeedbackRounds ?? 0) + 1;+ }+for (const toolPayload of payload.toolsCalling) {const result: ToolRunResult = {content: blockedContent,diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.tsindex 701a85af0d4..e9eb29889db 100644--- a/packages/agent-runtime/src/types/instruction.ts+++ b/packages/agent-runtime/src/types/instruction.ts@@ -305,6 +305,20 @@ export interface AgentInstructionResolveBlockedTools extends AgentInstructionBasparentMessageId: string;/** Tool calls that were blocked and need tool results */toolsCalling: ChatToolPayload[];+ /**+ * These calls named tools that resolved to nothing, so the parent assistant+ * was persisted without any `tools` of its own. Two consequences the+ * executor has to handle:+ *+ * - The tool rows must be advertised on the parent, or the next step loses+ * them: state messages are rebuilt from the DB every step, and+ * conversation-flow only collects a tool row when its parent assistant+ * lists the matching call. An unadvertised rejection never reaches the+ * model, which is the feedback this whole path exists to deliver.+ * - The instruction counts as one round against+ * {@link AgentState.unresolvedToolFeedbackRounds}.+ */+ unresolvedToolNames?: boolean;};type: 'resolve_blocked_tools';}diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.tsindex fa93e7db4f2..caeba490422 100644--- a/packages/agent-runtime/src/types/state.ts+++ b/packages/agent-runtime/src/types/state.ts@@ -189,6 +189,15 @@ export interface AgentState {/** Tool source map for routing tool execution to correct handler */toolSourceMap?: Record<string, ToolSource>;++ /**+ * How many times this operation has answered unresolvable tool calls with a+ * rejected tool result. Operation-scoped on purpose: the same rejection rows+ * are also readable from the message history, but that history is rehydrated+ * from the DB on every step and carries earlier operations' rejections, so+ * counting rows there would spend a new operation's budget before it starts.+ */+ unresolvedToolFeedbackRounds?: number;// --- Usage and Cost Tracking ---/*** Accumulated usage statistics for this session.diff --git a/packages/context-engine/src/engine/tools/ToolNameResolver.ts b/packages/context-engine/src/engine/tools/ToolNameResolver.tsindex 422431d5931..8baa69c9a07 100644--- a/packages/context-engine/src/engine/tools/ToolNameResolver.ts+++ b/packages/context-engine/src/engine/tools/ToolNameResolver.ts@@ -140,93 +140,160 @@ export class ToolNameResolver {offeredToolNames?: string[],): ChatToolPayload[] {const offeredSet = offeredToolNames ? new Set(offeredToolNames) : null;+ /** Built lazily: only a call that fails to resolve needs the candidate list. */+ let repairCandidates: string[] | undefined;+ const getRepairCandidates = (): string[] => {+ repairCandidates ??= offeredToolNames ?? this.listManifestToolNames(manifests);+ return repairCandidates;+ };return toolCalls.map((toolCall): ChatToolPayload | null => {- const [initialIdentifier, initialApiName, type] =- toolCall.function.name.split(PLUGIN_SCHEMA_SEPARATOR);- let identifier = initialIdentifier;- 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;- }- }+ const resolved = this.resolveOne(toolCall, manifests, offeredSet);+ if (resolved) return resolved;- // Step 1: Resolve hashed identifier if needed- if (identifier.startsWith(PLUGIN_SCHEMA_API_MD5_PREFIX)) {- const identifierMd5 = identifier.replace(PLUGIN_SCHEMA_API_MD5_PREFIX, '');- // Find the manifest by hashed identifier- const foundIdentifier = Object.keys(manifests).find(- (id) => this.genHash(id) === identifierMd5,- );- if (foundIdentifier) {- identifier = foundIdentifier;- }- }+ // Last resort: the model garbled the separator itself (observed in+ // production: `lobe-local-system~~__runCommand` for+ // `lobe-local-system____runCommand`, mid-operation, after earlier steps+ // had spelled the same tool correctly). Nothing above can parse that,+ // and dropping it ends the turn with an empty assistant message.+ // Recover the name when it collapses to exactly one offered tool, then+ // resolve it through the normal path.+ const repairedName = this.repairToolName(toolCall.function.name, getRepairCandidates());+ if (!repairedName) return null;- // Step 2: Resolve hashed apiName if needed- if (apiName.startsWith(PLUGIN_SCHEMA_API_MD5_PREFIX) && manifests[identifier]) {- const md5 = apiName.replace(PLUGIN_SCHEMA_API_MD5_PREFIX, '');- const manifest = manifests[identifier];-- const api = manifest?.api.find(- (api: LobeChatPluginApi) => this.genHash(api.name) === md5,- );- if (api) {- apiName = api.name;- }- }+ return this.resolveOne(+ { ...toolCall, function: { ...toolCall.function, name: repairedName } },+ manifests,+ offeredSet,+ );+ })+ .filter(Boolean) as ChatToolPayload[];+ }++ /**+ * Comparison key for tool names: lowercase, letters and digits only. Both+ * `lobe-local-system~~__runCommand` and `lobe-local-system____runCommand`+ * collapse to `lobelocalsystemruncommand`, so a mangled separator still+ * matches the tool it was meant to name.+ */+ private squashToolName(name: string): string {+ return name.toLowerCase().replaceAll(/[^a-z0-9]/g, '');+ }++ /** Every tool name the manifests can produce; used when no offered list is given. */+ private listManifestToolNames(manifests: Record<string, LobeToolManifest>): string[] {+ const names: string[] = [];++ for (const [identifier, manifest] of Object.entries(manifests)) {+ for (const api of manifest?.api ?? []) {+ names.push(this.generate(identifier, api.name, manifest.type));+ }+ }++ return names;+ }++ /**+ * Recover a malformed tool name by squashed comparison. Only an unambiguous+ * match is accepted: when two candidates collapse to the same key the call+ * stays unresolved rather than guessing which tool to run.+ */+ private repairToolName(name: string, candidateNames: string[]): string | undefined {+ const squashed = this.squashToolName(name);+ if (!squashed) return undefined;- const manifest = manifests[identifier];- const matchedApi = manifest?.api.find((api: LobeChatPluginApi) => api.name === apiName);+ const matches = new Set(+ candidateNames.filter((candidate) => this.squashToolName(candidate) === squashed),+ );- // A tool explicitly offered by the server is already authoritative and- // may not have a prompt manifest. A stale namespaced call that was not- // offered this turn must still match a known manifest entry before it- // can be preserved for the downstream scope guard. This prevents a- // fabricated namespace/API pair from becoming a synthetic tool result.- if (offeredSet && !offeredSet.has(toolCall.function.name) && (!manifest || !matchedApi)) {- return null;+ return matches.size === 1 ? [...matches][0] : undefined;+ }++ /** Resolve a single tool call, or `null` when its name maps to no known tool. */+ private resolveOne(+ toolCall: MessageToolCall,+ manifests: Record<string, LobeToolManifest>,+ offeredSet: Set<string> | null,+ ): ChatToolPayload | null {+ const [initialIdentifier, initialApiName, type] =+ toolCall.function.name.split(PLUGIN_SCHEMA_SEPARATOR);+ let identifier = initialIdentifier;+ 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;+ }+ }- const payload: ChatToolPayload = {- apiName,- arguments: toolCall.function.arguments,- id: toolCall.id,- identifier,- thoughtSignature: toolCall.thoughtSignature,- type: (type ?? manifest?.type ?? 'builtin') as any,- };+ // Step 1: Resolve hashed identifier if needed+ if (identifier.startsWith(PLUGIN_SCHEMA_API_MD5_PREFIX)) {+ const identifierMd5 = identifier.replace(PLUGIN_SCHEMA_API_MD5_PREFIX, '');+ // Find the manifest by hashed identifier+ const foundIdentifier = Object.keys(manifests).find(+ (id) => this.genHash(id) === identifierMd5,+ );+ if (foundIdentifier) {+ identifier = foundIdentifier;+ }+ }- return payload;- })- .filter(Boolean) as ChatToolPayload[];+ // Step 2: Resolve hashed apiName if needed+ if (apiName.startsWith(PLUGIN_SCHEMA_API_MD5_PREFIX) && manifests[identifier]) {+ const md5 = apiName.replace(PLUGIN_SCHEMA_API_MD5_PREFIX, '');+ const manifest = manifests[identifier];++ const api = manifest?.api.find((api: LobeChatPluginApi) => this.genHash(api.name) === md5);+ if (api) {+ apiName = api.name;+ }+ }++ const manifest = manifests[identifier];+ const matchedApi = manifest?.api.find((api: LobeChatPluginApi) => api.name === apiName);++ // A tool explicitly offered by the server is already authoritative and+ // may not have a prompt manifest. A stale namespaced call that was not+ // offered this turn must still match a known manifest entry before it+ // can be preserved for the downstream scope guard. This prevents a+ // fabricated namespace/API pair from becoming a synthetic tool result.+ if (offeredSet && !offeredSet.has(toolCall.function.name) && (!manifest || !matchedApi)) {+ return null;+ }++ const payload: ChatToolPayload = {+ apiName,+ arguments: toolCall.function.arguments,+ id: toolCall.id,+ identifier,+ thoughtSignature: toolCall.thoughtSignature,+ type: (type ?? manifest?.type ?? 'builtin') as any,+ };++ return payload;}}diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.tsindex 77638c4f806..b55abb6f53b 100644--- a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts+++ b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts@@ -1100,6 +1100,127 @@ describe('ToolNameResolver', () => {});});+ describe('resolve - malformed separator repair', () => {+ const localSystem = {+ 'lobe-local-system': {+ api: [+ { description: 'Run a shell command', name: 'runCommand', parameters: {} },+ { description: 'Read a file', name: 'readFile', parameters: {} },+ ],+ identifier: 'lobe-local-system',+ meta: {},+ type: 'builtin' as const,+ },+ };++ // Production case: mid-operation the model emitted `~~__` where it had+ // written `____` correctly two steps earlier. Dropping the call finished+ // the operation with an empty assistant message.+ it('should recover a tool name whose separator the model garbled', () => {+ const result = resolver.resolve(+ [+ {+ function: { arguments: '{"command":"ls"}', name: 'lobe-local-system~~__runCommand' },+ id: 'call_1',+ type: 'function',+ },+ ],+ localSystem,+ ['lobe-local-system____runCommand', 'lobe-local-system____readFile'],+ );++ expect(result).toEqual([+ {+ apiName: 'runCommand',+ arguments: '{"command":"ls"}',+ id: 'call_1',+ identifier: 'lobe-local-system',+ type: 'builtin',+ },+ ]);+ });++ it('should repair against manifests when no offered list is given', () => {+ const result = resolver.resolve(+ [+ {+ function: { arguments: '{}', name: 'lobe-local-system..readFile' },+ id: 'call_1',+ type: 'function',+ },+ ],+ localSystem,+ );++ expect(result).toHaveLength(1);+ expect(result[0].identifier).toBe('lobe-local-system');+ expect(result[0].apiName).toBe('readFile');+ });++ it('should leave a well-formed call untouched', () => {+ const result = resolver.resolve(+ [+ {+ function: { arguments: '{}', name: 'lobe-local-system____readFile' },+ id: 'call_1',+ type: 'function',+ },+ ],+ localSystem,+ ['lobe-local-system____readFile'],+ );++ expect(result[0].apiName).toBe('readFile');+ });++ it('should refuse to guess when two tools collapse to the same key', () => {+ const manifests = {+ 'a': {+ api: [{ description: '', name: 'bc', parameters: {} }],+ identifier: 'a',+ meta: {},+ type: 'builtin' as const,+ },+ 'a-b': {+ api: [{ description: '', name: 'c', parameters: {} }],+ identifier: 'a-b',+ meta: {},+ type: 'builtin' as const,+ },+ };++ const result = resolver.resolve(+ [+ {+ function: { arguments: '{}', name: 'a~b__c' },+ id: 'call_1',+ type: 'function',+ },+ ],+ manifests,+ ['a____bc', 'a-b____c'],+ );++ expect(result).toEqual([]);+ });++ it('should still drop a name that matches no tool at all', () => {+ const result = resolver.resolve(+ [+ {+ function: { arguments: '{}', name: 'totally~~__madeUp' },+ id: 'call_1',+ type: 'function',+ },+ ],+ localSystem,+ ['lobe-local-system____runCommand'],+ );++ expect(result).toEqual([]);+ });+ });+describe('resolve - real-world integration', () => {it('should handle complete generate-resolve roundtrip', () => {const identifier = 'lobe-image-designer';