🤯 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): stop gracefully on consecutive unresolvable tool names (#23024)
Arvin Xu564a4b960511
diff --git a/apps/server/src/services/agentRuntime/__tests__/stepPresentation.test.ts b/apps/server/src/services/agentRuntime/__tests__/stepPresentation.test.tsindex d2824702000..0d8c93b63df 100644--- a/apps/server/src/services/agentRuntime/__tests__/stepPresentation.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/stepPresentation.test.ts@@ -103,6 +103,34 @@ describe('buildStepPresentation', () => {expect(presentation.toolsResult).toHaveLength(2);expect(presentation.toolsResult?.[1].output).toBe('{"x":1}');});++ // The final unresolvable tool names are rejected and the run stops in the+ // same step; the log line must not read like an ordinary tool step.+ it('appends the finish reason when the step also ended the run', () => {+ const { summary } = buildStepPresentation(+ {+ events: [{ reason: 'tool_name_unresolved', type: 'done' }],+ newState: baseState,+ nextContext: {+ payload: {+ toolCount: 1,+ toolResults: [+ {+ data: 'rejected',+ toolCall: { apiName: 'executeCode', identifier: 'lobe-skills' },+ },+ ],+ },+ phase: 'tools_batch_result',+ },+ },+ 5,+ );++ expect(summary).toBe(+ '[tools×1] lobe-skills/executeCode → [done] reason=tool_name_unresolved',+ );+ });});describe('phase=other / done event', () => {diff --git a/apps/server/src/services/agentRuntime/stepPresentation.ts b/apps/server/src/services/agentRuntime/stepPresentation.tsindex 9033267b44c..368a2b0372e 100644--- a/apps/server/src/services/agentRuntime/stepPresentation.ts+++ b/apps/server/src/services/agentRuntime/stepPresentation.ts@@ -40,6 +40,8 @@ export function buildStepPresentation(const { usage, cost } = stepResult.newState;const phase = stepResult.nextContext?.phase;const isToolPhase = phase === 'tool_result' || phase === 'tools_batch_result';+ const doneEvent = stepResult.events?.find((e) => e.type === 'done') as+ { reason?: string; reasonDetail?: string; type: 'done' } | undefined;let content: string | undefined;let reasoning: string | undefined;@@ -89,9 +91,6 @@ export function buildStepPresentation(summary = `[tools×${toolCount}] ${toolNames.join(', ')}`;} else {// Check for done event first (finish step with no next context).- const doneEvent = stepResult.events?.find((e) => e.type === 'done') as- { reason?: string; reasonDetail?: string; type: 'done' } | undefined;-if (doneEvent) {summary = `[done] reason=${doneEvent.reason ?? 'unknown'}`;} else {@@ -117,6 +116,11 @@ export function buildStepPresentation(}}+ // A step can settle tool calls and then finish (e.g. the last unresolvable+ // tool names are rejected, then the run stops): the tool phase decides the+ // presentation, but the log line must still say the run ended and why.+ if (isToolPhase && doneEvent) summary += ` → [done] reason=${doneEvent.reason ?? 'unknown'}`;+// Step-level usage from nextContext.stepUsage.const stepUsage = stepResult.nextContext?.stepUsage as Record<string, number> | undefined;diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 09e109ca81b..bc2b089be51 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -56,12 +56,16 @@ const unresolvedToolContent = (names: string) =>const REMOTE_DEVICE_IDENTIFIER = 'lobe-remote-device';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.+ * How many consecutive LLM turns may be answered with a rejected tool result+ * for unresolvable tool names before the operation stops retrying. The+ * feedback exists so the model can fix a garbled name; a model that keeps+ * emitting names nothing can match, turn after turn, is stuck, and ending the+ * run beats burning the step budget on it. Any resolved tool call in between+ * resets the count (see `resetUnresolvedToolFeedback`), so an isolated typo+ * late in a long, productive run never ends it.*/const UNRESOLVED_TOOL_FEEDBACK_LIMIT = 2;+const UNRESOLVED_TOOL_STOP_NOTE = `Stopped after ${UNRESOLVED_TOOL_FEEDBACK_LIMIT + 1} consecutive replies called tools that do not exist.`;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@@ -797,10 +801,9 @@ export class GeneralChatAgent implements Agent {};}- // 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) {+ // Nothing addressable to reject (nameless calls): fail the operation+ // so it surfaces as an error instead of a silent `done`.+ if (namedToolCalls.length === 0) {throw new Error(`LLM returned ${rawToolCalls.length} unresolvable tool_calls: ${unresolvedNames || 'unnamed'}`,);@@ -826,10 +829,16 @@ export class GeneralChatAgent implements Agent {.filter(Boolean).join('\n\n');- return {+ const rejection = {payload: {- blockedContent,+ blockedContent: overFeedbackLimit+ ? `${blockedContent}\n\n${UNRESOLVED_TOOL_STOP_NOTE}`+ : blockedContent,blockedReason: UNRESOLVED_TOOL_REASON,+ // A rejected tool card shows only its reason code, so the stop+ // note goes on the reply itself, the way the repeat-limit stop+ // reports itself (see `callLlmFinalizer`).+ ...(overFeedbackLimit && { parentNote: UNRESOLVED_TOOL_STOP_NOTE }),parentMessageId,unresolvedToolNames: true,toolsCalling: namedToolCalls.map((toolCall): ChatToolPayload => {@@ -851,6 +860,23 @@ export class GeneralChatAgent implements Agent {},type: 'resolve_blocked_tools',} satisfies AgentInstruction;++ if (!overFeedbackLimit) return rejection;++ // The model has been told on each of the previous consecutive turns+ // and still names nothing that exists. Stop retrying, but end the+ // run as `done`, not as an error: the work earlier steps produced+ // stays, the rejected rows still answer this turn's calls (so the+ // history stays well-formed for the next operation), and the reason+ // says why the run stopped.+ return [+ rejection,+ {+ reason: UNRESOLVED_TOOL_REASON,+ reasonDetail: `LLM returned ${rawToolCalls.length} unresolvable tool_calls after ${UNRESOLVED_TOOL_FEEDBACK_LIMIT} consecutive rejected rounds: ${unresolvedNames}`,+ type: 'finish',+ },+ ];}// No tool calls, conversation is completediff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex 35b1cbdb35d..a51b1d5eea2 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -419,186 +419,6 @@ describe('GeneralChatAgent', () => {);});- it('should reject unresolvable tool_calls so the model can retry', async () => {- const agent = new GeneralChatAgent(createAgentOptions(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: '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(createAgentOptions(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(createAgentOptions(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(createAgentOptions(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: '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(createAgentOptions(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(createAgentOptions(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 () => {const agent = new GeneralChatAgent(createAgentOptions(mockModelRuntimeConfig));diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.unresolvedToolNames.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.unresolvedToolNames.test.tsnew file mode 100644index 00000000000..7601c48aeb0--- /dev/null+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.unresolvedToolNames.test.ts@@ -0,0 +1,259 @@+import { describe, expect, it } from 'vitest';++import { type AgentRuntimeContext, type AgentState } from '../../types';+import { GeneralChatAgent } from '../GeneralChatAgent';++/**+ * The llm_result branch for tool calls whose names resolve to nothing: the+ * model gets a rejected tool result to retry with, and only a model that keeps+ * missing on consecutive turns ends the run. The budget's reset on executed+ * tools and the end-to-end run status live in+ * `core/__tests__/runtime.unresolvedToolNames.test.ts`.+ */+describe('GeneralChatAgent unresolvable tool names (llm_result phase)', () => {+ const createAgent = () =>+ new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ modelRuntimeConfig: { model: 'gpt-4o-mini', provider: 'openai' },+ operationId: 'test-session',+ });++ const createMockState = (overrides?: Partial<AgentState>): AgentState => ({+ operationId: 'test-session',+ status: 'running',+ messages: [],+ toolManifestMap: {},+ stepCount: 0,+ usage: {+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: { totalCalls: 0, totalTimeMs: 0, byTool: [] },+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ },+ cost: {+ calculatedAt: new Date().toISOString(),+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ total: 0,+ },+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ ...overrides,+ });++ const createMockContext = (+ phase: AgentRuntimeContext['phase'],+ payload?: any,+ ): AgentRuntimeContext => ({+ phase,+ payload,+ session: {+ sessionId: 'test-session',+ messageCount: 0,+ status: 'running',+ stepCount: 0,+ },+ });++ const unresolvedContext = (name: string) =>+ createMockContext('llm_result', {+ hasToolsCalling: true,+ toolsCalling: [],+ parentMessageId: 'msg-1',+ result: {+ content: '',+ tool_calls: [{ id: 't1', type: 'function', function: { name, arguments: '{}' } }],+ },+ });++ it('should reject unresolvable tool_calls so the model can retry', async () => {+ const agent = createAgent();++ 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: '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 keep retrying while the consecutive rounds are under the limit', async () => {+ const result = await createAgent().runner(+ unresolvedContext('lobe-skills____executeCode'),+ createMockState({ unresolvedToolFeedbackRounds: 1 }),+ );++ expect((result as any).type).toBe('resolve_blocked_tools');+ });++ // T-14100: the third consecutive miss used to throw, which marked the whole+ // operation `error` (an "Agent Execution Failed" 500) and discarded a run+ // that had already produced work.+ it('should finish as done, not throw, once consecutive rejections hit the limit', async () => {+ const result = await createAgent().runner(+ unresolvedContext('lobe-skills____executeCode'),+ createMockState({ unresolvedToolFeedbackRounds: 2 }),+ );++ expect(result).toEqual([+ {+ type: 'resolve_blocked_tools',+ payload: {+ blockedContent:+ 'Tool call rejected: no available tool is named lobe-skills____executeCode. Copy a name exactly as declared in the tools schema and call it again.' ++ '\n\n' ++ 'Stopped after 3 consecutive replies called tools that do not exist.',+ blockedReason: 'tool_name_unresolved',+ parentNote: 'Stopped after 3 consecutive replies called tools that do not exist.',+ parentMessageId: 'msg-1',+ unresolvedToolNames: true,+ toolsCalling: [+ {+ apiName: 'executeCode',+ arguments: '{}',+ id: 't1',+ identifier: 'lobe-skills',+ type: 'builtin',+ },+ ],+ },+ },+ {+ type: 'finish',+ reason: 'tool_name_unresolved',+ reasonDetail:+ 'LLM returned 1 unresolvable tool_calls after 2 consecutive rejected rounds: lobe-skills____executeCode',+ },+ ]);+ });++ // 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 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 createAgent().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 result = await createAgent().runner(+ unresolvedContext('activateTools'),+ createMockState({ forceFinish: true }),+ );++ expect(result).toEqual({+ type: 'finish',+ reason: 'max_steps_completed',+ reasonDetail: 'LLM returned 1 unresolvable tool_calls after max steps: activateTools',+ });+ });++ // forceFinish wins over the feedback limit: past max steps the run ends+ // with the max-steps reason whatever the rejection count is.+ it('should keep the max-steps finish when the feedback limit is also reached', async () => {+ const result = await createAgent().runner(+ unresolvedContext('activateTools'),+ createMockState({ forceFinish: true, unresolvedToolFeedbackRounds: 2 }),+ );++ expect(result).toEqual({+ type: 'finish',+ 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 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 result = await createAgent().runner(unresolvedContext('activateTools'), state);++ expect((result as any).type).toBe('resolve_blocked_tools');+ });++ it('should fail when unresolvable tool_calls carry no name to reject', async () => {+ await expect(createAgent().runner(unresolvedContext(''), createMockState())).rejects.toThrow(+ 'LLM returned 1 unresolvable tool_calls: unnamed',+ );+ });+});diff --git a/packages/agent-runtime/src/core/__tests__/runtime.unresolvedToolNames.test.ts b/packages/agent-runtime/src/core/__tests__/runtime.unresolvedToolNames.test.tsnew file mode 100644index 00000000000..bd17a15219e--- /dev/null+++ b/packages/agent-runtime/src/core/__tests__/runtime.unresolvedToolNames.test.ts@@ -0,0 +1,214 @@+import type { ChatToolPayload } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { GeneralChatAgent } from '../../agents/GeneralChatAgent';+import { createAgentRuntimeExecutors } from '../../executors/registry';+import { callTool } from '../../executors/tool';+import { createState, createToolExecutorFixture } from '../../executors/tool.testUtils';+import type { AgentEvent, AgentRuntimeContext, AgentState, InstructionExecutor } from '../../types';+import { AgentRuntime } from '../runtime';++/**+ * T-14100: a long run that had already produced work ended as an `error`+ * ("Agent Execution Failed") because the unresolved-tool-name budget counted+ * every miss in the operation, so two early misses plus one late typo — with+ * many successful tool calls in between — spent it and the agent threw.+ *+ * These replay the model's turns through the real runtime, agent and the+ * package's own executors (only the LLM is scripted), and assert how the+ * operation ends.+ */++type LlmReply =+ | { kind: 'text' }+ | { kind: 'tools'; calls: ChatToolPayload[] }+ | { kind: 'unresolved'; name: string };++const runCommandCall = (id: string): ChatToolPayload => ({+ apiName: 'runCommand',+ arguments: '{"command":"ls"}',+ id,+ identifier: 'lobe-skills',+ type: 'builtin',+});++const toolManifestMap = {+ 'lobe-skills': {+ api: [{ description: '', humanIntervention: 'never', name: 'runCommand', parameters: {} }],+ identifier: 'lobe-skills',+ meta: {},+ type: 'builtin',+ },+} as any;++const llmResultContext = (reply: LlmReply, index: number): AgentRuntimeContext => {+ const parentMessageId = `assistant-${index}`;+ const session = { messageCount: 1, sessionId: 'op-1', status: 'running' as const, stepCount: 0 };++ if (reply.kind === 'text') {+ return {+ payload: { hasToolsCalling: false, parentMessageId, result: { content: 'Done.' } },+ phase: 'llm_result',+ session,+ };+ }++ const toolCalls =+ reply.kind === 'tools'+ ? reply.calls.map((call) => ({ id: call.id, name: `${call.identifier}____${call.apiName}` }))+ : [{ id: `call-${index}`, name: reply.name }];++ return {+ payload: {+ hasToolsCalling: reply.kind === 'tools',+ parentMessageId,+ result: {+ content: '',+ tool_calls: toolCalls.map(({ id, name }) => ({+ function: { arguments: '{}', name },+ id,+ type: 'function',+ })),+ },+ toolsCalling: reply.kind === 'tools' ? reply.calls : [],+ },+ phase: 'llm_result',+ session,+ };+};++const replay = async (replies: LlmReply[]) => {+ const fixture = createToolExecutorFixture();+ let llmTurn = 0;+ // Only the model is scripted; every other instruction runs the package's+ // real executor against an in-memory host.+ const callLlm: InstructionExecutor = async (_instruction, state) => {+ const reply = replies[llmTurn];+ if (!reply) throw new Error(`LLM called more times than scripted (${llmTurn + 1})`);+ llmTurn += 1;+ return {+ events: [],+ newState: structuredClone(state),+ nextContext: llmResultContext(reply, llmTurn),+ };+ };++ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ modelRuntimeConfig: { model: 'gpt-4o-mini', provider: 'openai' },+ operationId: 'op-1',+ });+ const runtime = new AgentRuntime(agent, {+ executors: { ...createAgentRuntimeExecutors(fixture.host), call_llm: callLlm },+ });++ let state: AgentState = createState({+ messages: [{ content: 'Build the report', id: 'msg-user', role: 'user' }],+ toolManifestMap,+ });+ let context: AgentRuntimeContext | undefined = {+ payload: {},+ phase: 'user_input',+ session: { messageCount: 1, sessionId: 'op-1', status: 'running', stepCount: 0 },+ };+ const events: AgentEvent[] = [];++ for (let step = 0; context && state.status === 'running' && step < 30; step++) {+ const result = await runtime.step(state, context);+ events.push(...result.events);+ state = result.newState;+ context = result.nextContext;+ }++ return { events, fixture, llmTurns: llmTurn, state };+};++describe('AgentRuntime with unresolvable tool names', () => {+ it('keeps going when a typo follows two misses with a successful tool call in between', async () => {+ const { events, fixture, llmTurns, state } = await replay([+ { kind: 'unresolved', name: 'lobe-cloud-sandbox____writeFile' },+ { kind: 'unresolved', name: 'lobe-cloud-sandbox____runCommand' },+ { kind: 'tools', calls: [runCommandCall('call-ok')] },+ { kind: 'unresolved', name: 'lobe-skills____executeCode' },+ { kind: 'text' },+ ]);++ expect(state.status).toBe('done');+ expect(events.find((event) => event.type === 'error')).toBeUndefined();+ expect(events.at(-1)).toMatchObject({ reason: 'completed', type: 'done' });+ // The late typo still got its rejection, and the model used it to answer.+ expect(llmTurns).toBe(5);+ expect(fixture.runTool).toHaveBeenCalledTimes(1);+ expect(state.unresolvedToolFeedbackRounds).toBe(1);+ });++ it('ends as done with a tool_name_unresolved reason after three consecutive misses', async () => {+ const { events, fixture, llmTurns, state } = await replay([+ { kind: 'tools', calls: [runCommandCall('call-ok')] },+ { kind: 'unresolved', name: 'lobe-skills____executeCode' },+ { kind: 'unresolved', name: 'lobe-skills____executeCode' },+ { kind: 'unresolved', name: 'lobe-skills____executeCode' },+ ]);++ expect(state.status).toBe('done');+ expect(events.find((event) => event.type === 'error')).toBeUndefined();+ expect(events.at(-1)).toMatchObject({+ reason: 'tool_name_unresolved',+ reasonDetail:+ 'LLM returned 1 unresolvable tool_calls after 2 consecutive rejected rounds: lobe-skills____executeCode',+ type: 'done',+ });+ expect(llmTurns).toBe(4);+ // The final turn's call is still answered with a rejected row, so the+ // persisted history stays well-formed for the next operation.+ const rejectedRows = fixture.createToolMessage.mock.calls.filter(+ ([params]) => params.pluginIntervention?.status === 'rejected',+ );+ expect(rejectedRows).toHaveLength(3);+ expect(rejectedRows.at(-1)?.[0].content).toContain(+ 'Stopped after 3 consecutive replies called tools that do not exist.',+ );+ // A rejected card shows only its reason code, so the reply carries the+ // human-readable stop note; earlier rejections leave the reply alone.+ const replyUpdates = (fixture.host.transports.messages.update as any).mock.calls;+ expect(replyUpdates.filter(([, params]: any) => 'content' in params)).toEqual([+ [+ 'assistant-4',+ expect.objectContaining({+ content: 'Stopped after 3 consecutive replies called tools that do not exist.',+ }),+ ],+ ]);+ });++ it('resets the count when a batch of resolved tools runs', async () => {+ const { fixture, state } = await replay([+ { kind: 'unresolved', name: 'lobe-cloud-sandbox____writeFile' },+ { kind: 'unresolved', name: 'lobe-cloud-sandbox____runCommand' },+ { kind: 'tools', calls: [runCommandCall('call-a'), runCommandCall('call-b')] },+ { kind: 'text' },+ ]);++ expect(state.status).toBe('done');+ expect(fixture.runTool).toHaveBeenCalledTimes(2);+ expect(state.unresolvedToolFeedbackRounds).toBe(0);+ });++ // The reset happens on executor entry, so a call that fails (or parks for a+ // sub-agent / client) still proves the model named a real tool.+ it('resets the count even when the resolved tool throws', async () => {+ const fixture = createToolExecutorFixture();+ fixture.runTool.mockRejectedValueOnce(new Error('sandbox unreachable'));++ const result = await callTool(fixture.host)(+ {+ payload: { parentMessageId: 'assistant-1', toolCalling: runCommandCall('call-1') },+ type: 'call_tool',+ },+ createState({ toolManifestMap, unresolvedToolFeedbackRounds: 2 }),+ );++ expect(result.events.some((event) => event.type === 'error')).toBe(true);+ expect(result.newState.unresolvedToolFeedbackRounds).toBe(0);+ });+});diff --git a/packages/agent-runtime/src/executors/resolveTools.test.ts b/packages/agent-runtime/src/executors/resolveTools.test.tsindex 882a0ed1d0c..9d03a167b4f 100644--- a/packages/agent-runtime/src/executors/resolveTools.test.ts+++ b/packages/agent-runtime/src/executors/resolveTools.test.ts@@ -229,6 +229,71 @@ describe('resolveTools executors', () => {expect(result.newState.unresolvedToolFeedbackRounds).toBe(2);});+ describe('stop note on the parent reply', () => {+ const stopInstruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ parentNote: 'Stopped after 3 consecutive replies called tools that do not exist.',+ toolsCalling: [createToolCall()],+ unresolvedToolNames: true,+ },+ type: 'resolve_blocked_tools',+ };++ it('appends the note to the text the reply already has', async () => {+ host.transports.messages.findById = vi+ .fn()+ .mockResolvedValue({ content: 'Running the script now.', id: 'assistant-msg-1' });++ await resolveBlockedTools(host)(stopInstruction, createState());++ expect(host.transports.messages.update).toHaveBeenCalledWith('assistant-msg-1', {+ content:+ 'Running the script now.\n\nStopped after 3 consecutive replies called tools that do not exist.',+ tools: [createToolCall()],+ });+ });++ // The completion lifecycle reads the final assistant text from the runtime+ // state and only recovers the row when that text is empty, so a reply that+ // already carried text must carry the note in state as well.+ it('mirrors the note into the runtime state reply', async () => {+ host.transports.messages.findById = vi+ .fn()+ .mockResolvedValue({ content: 'Running the script now.', id: 'assistant-msg-1' });++ const result = await resolveBlockedTools(host)(+ stopInstruction,+ createState({+ messages: [+ { content: 'Running the script now.', id: 'assistant-msg-1', role: 'assistant' },+ ],+ }),+ );++ const reply = result.newState.messages.find((message) => message.id === 'assistant-msg-1');+ expect(reply?.content).toBe(+ 'Running the script now.\n\nStopped after 3 consecutive replies called tools that do not exist.',+ );+ });++ // Image replies store serialized content parts; overwriting them with+ // text would drop the images.+ it('leaves a multimodal reply content alone', async () => {+ host.transports.messages.findById = vi.fn().mockResolvedValue({+ content: '[{"type":"image"}]',+ id: 'assistant-msg-1',+ metadata: { isMultimodal: true },+ });++ await resolveBlockedTools(host)(stopInstruction, createState());++ expect(host.transports.messages.update).toHaveBeenCalledWith('assistant-msg-1', {+ tools: [createToolCall()],+ });+ });+ });+it('leaves the parent untouched for ordinary blocked tools', async () => {const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> =createBlockedInstruction(createToolCall());diff --git a/packages/agent-runtime/src/executors/resolveTools.ts b/packages/agent-runtime/src/executors/resolveTools.tsindex 985a164165b..385e9f1214f 100644--- a/packages/agent-runtime/src/executors/resolveTools.ts+++ b/packages/agent-runtime/src/executors/resolveTools.ts@@ -24,6 +24,19 @@ const createSession = (state: AgentState, operationId: string): RuntimeSessionWistepCount: state.stepCount + 1,});+/**+ * A resolved tool call reached a tool executor, so the model is naming real+ * tools again: clear the unresolved-name feedback count so it only ever+ * measures consecutive rejected turns. Without this, two early misses from a+ * tool surface that changed under the model would let a single typo many+ * successful steps later end the run.+ *+ * Applied on executor entry, before any branch, so every outcome of the call+ * (run, failed, deferred to a sub-agent or client, aborted) carries the reset.+ */+export const resetUnresolvedToolFeedback = (state: AgentState): AgentState =>+ state.unresolvedToolFeedbackRounds ? { ...state, unresolvedToolFeedbackRounds: 0 } : state;+/*** `resolve_blocked_tools` executor — turns policy-blocked tool calls into* persisted rejected tool messages so the runtime can continue planning.@@ -58,9 +71,32 @@ export const resolveBlockedTools =// never learns its tool name was wrong.if (payload.unresolvedToolNames) {try {+ let content: string | undefined;+ if (payload.parentNote) {+ const parent = await transports.messages.findById(payload.parentMessageId);+ // A multimodal reply stores serialized content parts, not text to+ // append to; its rejected tool rows still carry the note.+ if (!parent?.metadata?.isMultimodal) {+ content = [parent?.content, payload.parentNote].filter(Boolean).join('\n\n');+ }+ }await transports.messages.update(payload.parentMessageId, {+ ...(content !== undefined && { content }),tools: payload.toolsCalling,});++ // Mirror the persisted note into the runtime state: the completion+ // lifecycle derives \`lastAssistantContent\` from \`state.messages\` and+ // only falls back to the row when that text is empty, so a reply that+ // already carried text would reach the user without the stop reason.+ if (content !== undefined) {+ const parentIndex = newState.messages.findIndex(+ (message) => message?.id === payload.parentMessageId,+ );+ if (parentIndex !== -1) {+ newState.messages[parentIndex] = { ...newState.messages[parentIndex], content };+ }+ }} catch (error) {await publishPersistError(host, error);throw error;diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.tsindex 7364b02ec8e..225537eed6a 100644--- a/packages/agent-runtime/src/executors/tool.ts+++ b/packages/agent-runtime/src/executors/tool.ts@@ -21,6 +21,7 @@ import {} from '../utils';import { selectEffectiveToolManifestMap, selectToolSourceMap } from '../utils/operationToolSet';import { settleAbortedToolRows } from './abortedToolRows';+import { resetUnresolvedToolFeedback } from './resolveTools';import {createToolMessage,isBlockedBeforeExecution,@@ -451,7 +452,8 @@ const persistActivatedTools = ({export const callTool =(host: AgentRuntimeHost): InstructionExecutor =>- async (instruction, state, runtimeContext) => {+ async (instruction, entryState, runtimeContext) => {+ const state = resetUnresolvedToolFeedback(entryState);const { payload } = instruction as Extract<AgentInstruction, { type: 'call_tool' }>;const tools = requireToolTransport(host);const tool = payload.toolCalling;@@ -754,7 +756,8 @@ export const callTool =export const callToolsBatch =(host: AgentRuntimeHost): InstructionExecutor =>- async (instruction, state, runtimeContext) => {+ async (instruction, entryState, runtimeContext) => {+ const state = resetUnresolvedToolFeedback(entryState);const { payload } = instruction as Extract<AgentInstruction, { type: 'call_tools_batch' }>;const parentMessageId = payload.parentMessageId as string;const toolsCalling = payload.toolsCalling as ChatToolPayload[];diff --git a/packages/agent-runtime/src/types/event.ts b/packages/agent-runtime/src/types/event.tsindex c66c39e87fe..86416a6556b 100644--- a/packages/agent-runtime/src/types/event.ts+++ b/packages/agent-runtime/src/types/event.ts@@ -79,6 +79,7 @@ export type FinishReason =| 'agent_decision' // Agent decided to finish| 'queued_message_interrupt' // Soft interrupt: user queued a message during execution| 'error_recovery' // Finished due to unrecoverable error+ | 'tool_name_unresolved' // Stopped after consecutive tool calls named tools that do not exist| 'system_shutdown'; // System is shutting downexport interface AgentEventDone {diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.tsindex bf3decb7b4d..ed8a5956923 100644--- a/packages/agent-runtime/src/types/instruction.ts+++ b/packages/agent-runtime/src/types/instruction.ts@@ -312,6 +312,12 @@ export interface AgentInstructionResolveBlockedTools extends AgentInstructionBasblockedContentByCallId?: Record<string, string>;/** Optional machine-readable blocked reason */blockedReason?: string;+ /**+ * Appended to the parent assistant's stored text, in the same write that+ * advertises the tools when {@link unresolvedToolNames} is set. Used when+ * the run stops on these calls, so the reply itself says why.+ */+ parentNote?: string;/** Parent message ID (assistant message) */parentMessageId: string;/** Tool calls that were blocked and need tool results */@@ -327,7 +333,8 @@ export interface AgentInstructionResolveBlockedTools extends AgentInstructionBas* 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}.+ * {@link AgentState.unresolvedToolFeedbackRounds}, which a later+ * resolved tool call resets.*/unresolvedToolNames?: boolean;};diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.tsindex da6e0dd9988..63f385ee1a0 100644--- a/packages/agent-runtime/src/types/state.ts+++ b/packages/agent-runtime/src/types/state.ts@@ -644,8 +644,10 @@ export interface AgentState {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+ * How many consecutive LLM turns this operation has answered unresolvable+ * tool calls with a rejected tool result. Any resolved tool call reaching a+ * tool executor resets it to 0, so it measures a model stuck on names that do not exist,+ * not the run's lifetime total of typos. 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.