import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { Mock } from 'vitest'; import { z } from 'zod/v4'; import type { MessageList } from '../../../agent/message-list'; import { RequestContext } from '../../../request-context'; import { ToolStream } from '../../../tools/stream'; import { PUBSUB_SYMBOL, STREAM_FORMAT_SYMBOL } from '../../../workflows/constants'; import type { ExecuteFunctionParams } from '../../../workflows/step'; import { createStep } from '../../../workflows/workflow'; import { createLLMMappingStep } from './llm-mapping-step'; type ToolCallOutput = { toolCallId: string; toolName: string; args: Record; result?: any; error?: Error; aborted?: boolean; providerMetadata?: Record; providerExecuted?: boolean; approval?: { id: string; approved: boolean; reason?: string }; }; describe('createLLMMappingStep HITL behavior', () => { let controller: { enqueue: Mock }; let messageList: MessageList; let llmExecutionStep: any; let bail: Mock; let getStepResultAsync: Mock; let llmMappingStep: ReturnType; // Helper function to create properly typed execute params const createExecuteParams = ( inputData: ToolCallOutput[], ): ExecuteFunctionParams<{}, ToolCallOutput[], any, any, any> => ({ runId: 'test-run', workflowId: 'test-workflow', mastra: {} as any, requestContext: new RequestContext(), state: {}, setState: vi.fn(), retryCount: 1, tracingContext: {} as any, getInitData: vi.fn(), getStepResult: vi.fn(), getStepResultAsync, suspend: vi.fn(), bail, abort: vi.fn(), engine: 'default' as any, abortSignal: new AbortController().signal, writer: new ToolStream({ prefix: 'tool', callId: 'test-call-id', name: 'test-tool', runId: 'test-run', }), validateSchemas: false, inputData, [PUBSUB_SYMBOL]: {} as any, [STREAM_FORMAT_SYMBOL]: undefined, }); beforeEach(() => { controller = { enqueue: vi.fn(), }; messageList = { get: { all: { aiV5: { model: () => [], }, }, input: { aiV5: { model: () => [], }, }, response: { aiV5: { model: () => [], }, }, }, add: vi.fn(), updateToolInvocation: vi.fn(), } as unknown as MessageList; llmExecutionStep = createStep({ id: 'test-llm-execution', inputSchema: z.any(), outputSchema: z.any(), execute: async () => ({ stepResult: { isContinued: true, reason: undefined, }, metadata: {}, }), }); bail = vi.fn(data => data); getStepResultAsync = vi.fn(async () => ({ stepResult: { isContinued: true, reason: undefined, }, metadata: {}, })); llmMappingStep = createLLMMappingStep( { models: {} as any, controller, messageList, runId: 'test-run', _internal: { generateId: () => 'test-message-id', }, } as any, llmExecutionStep, ); }); it('should bail when ALL tools have no result (all HITL tools)', async () => { // Arrange: Two tools without execute function (HITL) const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'updateSummary', args: { summary: 'test' }, result: undefined, }, { toolCallId: 'call-2', toolName: 'updateDescription', args: { description: 'test' }, result: undefined, }, ]; // Act const result = await llmMappingStep.execute(createExecuteParams(inputData)); // Assert: Should bail (suspend execution) and NOT emit tool-result chunks expect(bail).toHaveBeenCalled(); expect(controller.enqueue).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'tool-result' })); expect(result.stepResult.isContinued).toBe(false); }); it('should continue when ALL tools have results', async () => { // Arrange: Two tools with execute functions const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'updateTitle', args: { title: 'test' }, result: { success: true }, }, { toolCallId: 'call-2', toolName: 'updateStatus', args: { status: 'active' }, result: { success: true }, }, ]; // Act await llmMappingStep.execute(createExecuteParams(inputData)); // Assert: Should NOT bail and SHOULD emit tool-result for both tools expect(bail).not.toHaveBeenCalled(); expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-result', payload: expect.objectContaining({ toolCallId: 'call-1', result: { success: true }, }), }), ); expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-result', payload: expect.objectContaining({ toolCallId: 'call-2', result: { success: true }, }), }), ); }); it('should bail when SOME tools have results and SOME do not (mixed scenario)', async () => { // Arrange: One tool with execute, one without (the bug scenario) const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'updateTitle', args: { title: 'test' }, result: { success: true }, // Has result (has execute function) }, { toolCallId: 'call-2', toolName: 'updateSummary', args: { summary: 'test' }, result: undefined, // No result (HITL, no execute function) }, ]; // Act const result = await llmMappingStep.execute(createExecuteParams(inputData)); // Assert: Should bail (suspend execution) because updateSummary needs HITL expect(bail).toHaveBeenCalled(); expect(result.stepResult.isContinued).toBe(false); // ...but the tool that DID resolve must still be streamed and persisted before bailing, // otherwise its result is lost for good (issue #21637). expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-result', payload: expect.objectContaining({ toolCallId: 'call-1' }) }), ); expect(messageList.updateToolInvocation).toHaveBeenCalledWith( expect.objectContaining({ toolInvocation: expect.objectContaining({ toolCallId: 'call-1', state: 'result' }), }), ); // The still-pending tool must not be recorded or emitted. expect(controller.enqueue).not.toHaveBeenCalledWith( expect.objectContaining({ payload: expect.objectContaining({ toolCallId: 'call-2' }) }), ); expect(messageList.updateToolInvocation).not.toHaveBeenCalledWith( expect.objectContaining({ toolInvocation: expect.objectContaining({ toolCallId: 'call-2' }) }), ); }); it('should flush a completed server tool result before bailing for a pending client tool (#21637)', async () => { // The reporter's scenario: the model calls a server-side tool (createTool with execute) // and a client-side tool (forwarded via toolsets, no execute) in the same step. The // server tool finishes before the stream closes; its result must reach the client and // the message list, or the client waits forever on an `input-available` part that never // resolves and history claims the tool never ran. const inputData: ToolCallOutput[] = [ { toolCallId: 'call-server', toolName: 'get_record', args: { id: '42' }, result: { record: { id: '42', name: 'Acme' } }, }, { toolCallId: 'call-client', toolName: 'get_record_status', args: { id: '42' }, result: undefined, // resolved later by the browser }, ]; const result = await llmMappingStep.execute(createExecuteParams(inputData)); // The completed server tool is streamed as a terminal result... expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-result', payload: expect.objectContaining({ toolCallId: 'call-server', toolName: 'get_record', result: { record: { id: '42', name: 'Acme' } }, }), }), ); // ...and committed to history so a later turn knows it ran. expect(messageList.updateToolInvocation).toHaveBeenCalledWith( expect.objectContaining({ toolInvocation: expect.objectContaining({ toolCallId: 'call-server', state: 'result', result: { record: { id: '42', name: 'Acme' } }, }), }), ); // The turn still ends so the pending client tool can be resolved by the client. expect(bail).toHaveBeenCalled(); expect(result.stepResult.isContinued).toBe(false); }); it('should enqueue tool-output-denied when a requireApproval tool is declined (#20880)', async () => { const inputData: ToolCallOutput[] = [ { toolCallId: 'call-denied', toolName: 'sensitive-op', args: { action: 'delete' }, result: undefined, approval: { id: 'approval-1', approved: false, reason: 'Tool call was not approved by the user', }, }, ]; const result = await llmMappingStep.execute(createExecuteParams(inputData)); expect(messageList.updateToolInvocation).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-invocation', toolInvocation: expect.objectContaining({ state: 'output-denied', toolCallId: 'call-denied', toolName: 'sensitive-op', approval: expect.objectContaining({ approved: false }), }), }), ); expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-output-denied', payload: expect.objectContaining({ toolCallId: 'call-denied', toolName: 'sensitive-op', approval: expect.objectContaining({ approved: false }), }), }), ); expect(result.stepResult.isContinued).toBe(true); }); it('should emit tool-error for tools with errors and continue the loop for self-recovery', async () => { // Arrange: Tools without results but with errors const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'brokenTool', args: { param: 'test' }, result: undefined, error: new Error('Tool execution failed'), }, ]; // Act const result = await llmMappingStep.execute(createExecuteParams(inputData)); // Assert: Should emit tool-error chunk expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-error', payload: expect.objectContaining({ toolCallId: 'call-1', error: expect.any(Error), }), }), ); // Should NOT bail — the agentic loop should continue so the model can see the error and retry expect(bail).not.toHaveBeenCalled(); expect(result.stepResult.isContinued).toBe(true); // Should record the failure as `output-error` with the message in `errorText`, // not as a successful `result`, so it stays distinguishable on recall/replay. expect(messageList.updateToolInvocation).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-invocation', toolInvocation: expect.objectContaining({ state: 'output-error', toolCallId: 'call-1', toolName: 'brokenTool', errorText: 'Tool execution failed', }), }), ); }); it('should NOT record a result and should bail when a tool was aborted (no fabricated success)', async () => { // An `aborted` tool (cancelled by request abort) has no result/error. It must not be // recorded as a result, emit a tool-error, or be mistaken for a pending HITL tool — // the loop bails, leaving the call incomplete. const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'slowServerTool', args: { q: 'important' }, result: undefined, aborted: true, }, ]; const result = await llmMappingStep.execute(createExecuteParams(inputData)); // No fabricated success: the message history is never updated with a result for the // aborted call (this is what gets persisted, so it is the meaningful assertion). expect(messageList.updateToolInvocation).not.toHaveBeenCalled(); // No result/error chunks emitted for the aborted call. expect(controller.enqueue).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'tool-result' })); expect(controller.enqueue).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'tool-error' })); // The loop ends rather than continuing or suspending for input that will never arrive. expect(bail).toHaveBeenCalled(); expect(result.stepResult.isContinued).toBe(false); }); it('should not let an aborted tool force a suspend when a real error needs the loop to continue', async () => { // An aborted tool is neither a retryable error nor a pending HITL call. Sharing a turn // with a genuinely errored tool, it must not be misclassified as pending HITL and // suppress the loop continuation that lets the model recover from the real error. const inputData: ToolCallOutput[] = [ { toolCallId: 'aborted-1', toolName: 'slowServerTool', args: { q: 'important' }, result: undefined, aborted: true, }, { toolCallId: 'err-1', toolName: 'brokenTool', args: { param: 'test' }, result: undefined, error: new Error('Tool execution failed'), }, ]; const result = await llmMappingStep.execute(createExecuteParams(inputData)); // The real error is surfaced and the loop continues (self-recovery), rather than bailing. expect(bail).not.toHaveBeenCalled(); expect(result.stepResult.isContinued).toBe(true); expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-error', payload: expect.objectContaining({ toolCallId: 'err-1' }) }), ); // The aborted tool itself is never recorded as a result. expect(messageList.updateToolInvocation).not.toHaveBeenCalledWith( expect.objectContaining({ toolInvocation: expect.objectContaining({ toolCallId: 'aborted-1' }) }), ); }); it('should keep a pending client tool suspendable while NOT recording an aborted server tool', async () => { // The reporter's scenario: a server tool aborted in the same turn as a pending client // (HITL) tool. The client tool must still drive the bail/suspend (so it can resume via // addToolOutput), but the aborted server tool must not be recorded as a result. const inputData: ToolCallOutput[] = [ { toolCallId: 'srv-1', toolName: 'slowServerTool', args: { q: 'important' }, result: undefined, aborted: true, }, { toolCallId: 'cli-1', toolName: 'clientTool', args: { topic: 'x' }, result: undefined, // pending HITL, resolved later from the browser }, ]; const result = await llmMappingStep.execute(createExecuteParams(inputData)); // Bail (suspend) so the pending client tool can be resumed. expect(bail).toHaveBeenCalled(); expect(result.stepResult.isContinued).toBe(false); // The aborted server tool is never recorded as a result, and no error/result chunk is emitted. expect(messageList.updateToolInvocation).not.toHaveBeenCalled(); expect(controller.enqueue).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'tool-result' })); expect(controller.enqueue).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'tool-error' })); }); it('should continue the agentic loop (not bail) when all errors are tool-not-found', async () => { // Arrange: Tool call with ToolNotFoundError (set by tool-call-step when tool name is hallucinated) const { ToolNotFoundError } = await import('../errors'); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'creating:view', args: { param: 'test' }, result: undefined, error: new ToolNotFoundError( 'Tool "creating:view" not found. Available tools: view, list. Call tools by their exact name only.', ), }, ]; // Act const result = await llmMappingStep.execute(createExecuteParams(inputData)); // Assert: Should NOT bail — the agentic loop should continue so the model can self-correct expect(bail).not.toHaveBeenCalled(); // Should still emit tool-error chunk so the error is visible in the stream expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-error', payload: expect.objectContaining({ toolCallId: 'call-1', error: expect.any(Error), }), }), ); // Should update the tool invocation in the messageList so the model can see it expect(messageList.updateToolInvocation).toHaveBeenCalled(); // isContinued should be true to keep the loop going expect(result.stepResult.isContinued).toBe(true); }); it('should sanitize invalid tool names before persisting tool-error history', async () => { const { ToolNotFoundError } = await import('../errors'); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: '$FUNCTION_NAME', args: { param: 'test' }, result: undefined, error: new ToolNotFoundError('Tool "$FUNCTION_NAME" not found.'), }, ]; await llmMappingStep.execute(createExecuteParams(inputData)); expect(messageList.updateToolInvocation).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-invocation', toolInvocation: expect.objectContaining({ toolCallId: 'call-1', toolName: 'unknown_tool', }), }), ); }); it('should emit successful tool results alongside tool-not-found errors in the same turn', async () => { // Arrange: One valid tool with result + one hallucinated tool-not-found error const { ToolNotFoundError } = await import('../errors'); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'existingTool', args: { param: 'test' }, result: { success: true }, }, { toolCallId: 'call-2', toolName: 'creating:view', args: { param: 'test' }, result: undefined, error: new ToolNotFoundError( 'Tool "creating:view" not found. Available tools: existingTool. Call tools by their exact name only.', ), }, ]; // Act const result = await llmMappingStep.execute(createExecuteParams(inputData)); // Assert: Should NOT bail — this is a tool-not-found scenario expect(bail).not.toHaveBeenCalled(); expect(result.stepResult.isContinued).toBe(true); // Should emit tool-error for the hallucinated tool expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-error', payload: expect.objectContaining({ toolCallId: 'call-2', toolName: 'creating:view', }), }), ); // Should also emit tool-result for the successful tool expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-result', payload: expect.objectContaining({ toolCallId: 'call-1', toolName: 'existingTool', result: { success: true }, }), }), ); // Should update both error and result tool invocations in the messageList expect(messageList.updateToolInvocation).toHaveBeenCalledTimes(2); }); it('should bail when tool-not-found errors are mixed with pending HITL tools', async () => { // Arrange: One hallucinated tool (ToolNotFoundError) + one HITL tool (no result, no error) const { ToolNotFoundError } = await import('../errors'); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'creating:view', args: { param: 'test' }, result: undefined, error: new ToolNotFoundError('Tool "creating:view" not found.'), }, { toolCallId: 'call-2', toolName: 'updateSummary', args: { summary: 'test' }, result: undefined, // No result (HITL, no execute function) }, ]; // Act const result = await llmMappingStep.execute(createExecuteParams(inputData)); // Assert: Should bail (suspend) because HITL tool needs human input, // even though the other error is a tool-not-found expect(bail).toHaveBeenCalled(); expect(result.stepResult.isContinued).toBe(false); }); it('should continue when provider-executed tools are mixed with regular tools', async () => { // Arrange: One regular tool with result + one provider-executed tool with fallback result // This is the scenario from #13125 — after the fix in tool-call-step, provider-executed // tools get a non-undefined result, so they should not trigger the bail path const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'get_company_info', args: { name: 'test' }, result: { company: 'Acme' }, }, { toolCallId: 'call-2', toolName: 'web_search_20250305', args: { query: 'test' }, result: { providerExecuted: true, toolName: 'web_search_20250305' }, providerExecuted: true, }, ]; // Act await llmMappingStep.execute(createExecuteParams(inputData)); // Assert: Should NOT bail — both tools have results expect(bail).not.toHaveBeenCalled(); // Should emit tool-result for both tools expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-result', payload: expect.objectContaining({ toolCallId: 'call-1', result: { company: 'Acme' }, }), }), ); expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-result', payload: expect.objectContaining({ toolCallId: 'call-2', result: { providerExecuted: true, toolName: 'web_search_20250305' }, }), }), ); }); it('should continue the loop when errors are a mix of tool-not-found and other errors', async () => { // Arrange: One tool-not-found error and one execution error const { ToolNotFoundError } = await import('../errors'); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'creating:view', args: { param: 'test' }, result: undefined, error: new ToolNotFoundError('Tool "creating:view" not found.'), }, { toolCallId: 'call-2', toolName: 'existingTool', args: { param: 'test' }, result: undefined, error: new Error('Execution timeout'), }, ]; // Act const result = await llmMappingStep.execute(createExecuteParams(inputData)); // Assert: Should NOT bail — error messages are in the messageList, // the model can see them and self-correct or retry expect(bail).not.toHaveBeenCalled(); expect(result.stepResult.isContinued).toBe(true); }); }); describe('createLLMMappingStep tool execution error self-recovery (issue #9815)', () => { let controller: { enqueue: Mock }; let messageList: MessageList; let llmExecutionStep: any; let bail: Mock; let getStepResultAsync: Mock; let llmMappingStep: ReturnType; const createExecuteParams = ( inputData: ToolCallOutput[], ): ExecuteFunctionParams<{}, ToolCallOutput[], any, any, any> => ({ runId: 'test-run', workflowId: 'test-workflow', mastra: {} as any, requestContext: new RequestContext(), state: {}, setState: vi.fn(), retryCount: 1, tracingContext: {} as any, getInitData: vi.fn(), getStepResult: vi.fn(), getStepResultAsync, suspend: vi.fn(), bail, abort: vi.fn(), engine: 'default' as any, abortSignal: new AbortController().signal, writer: new ToolStream({ prefix: 'tool', callId: 'test-call-id', name: 'test-tool', runId: 'test-run', }), validateSchemas: false, inputData, [PUBSUB_SYMBOL]: {} as any, [STREAM_FORMAT_SYMBOL]: undefined, }); beforeEach(() => { controller = { enqueue: vi.fn(), }; messageList = { get: { all: { aiV5: { model: () => [], }, }, input: { aiV5: { model: () => [], }, }, response: { aiV5: { model: () => [], }, }, }, add: vi.fn(), updateToolInvocation: vi.fn(), } as unknown as MessageList; llmExecutionStep = createStep({ id: 'test-llm-execution', inputSchema: z.any(), outputSchema: z.any(), execute: async () => ({ stepResult: { isContinued: true, reason: undefined, }, metadata: {}, }), }); bail = vi.fn(data => data); getStepResultAsync = vi.fn(async () => ({ stepResult: { isContinued: true, reason: undefined, }, metadata: {}, })); llmMappingStep = createLLMMappingStep( { models: {} as any, controller, messageList, runId: 'test-run', _internal: { generateId: () => 'test-message-id', }, } as any, llmExecutionStep, ); }); it('should continue the agentic loop when a tool throws an execution error, allowing the model to self-recover', async () => { // Issue #9815: When a tool execution fails (e.g., invalid args, runtime error), // the error should be returned to the model so it can self-correct, // NOT bail and terminate the agentic loop. const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'myTool', args: { invalidParam: 'wrong type' }, result: undefined, error: new Error('Invalid arguments: expected "count" to be a number, got string'), }, ]; const result = await llmMappingStep.execute(createExecuteParams(inputData)); // The error should be emitted as a tool-error chunk expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-error', payload: expect.objectContaining({ toolCallId: 'call-1', toolName: 'myTool', error: expect.any(Error), }), }), ); // The error should be updated in the messageList so the model can see it expect(messageList.updateToolInvocation).toHaveBeenCalled(); // CRITICAL: The loop should NOT bail — it should continue so the model can self-correct expect(bail).not.toHaveBeenCalled(); expect(result.stepResult.isContinued).toBe(true); }); it('should continue the loop when a tool execution error occurs alongside successful tool results', async () => { // Mixed scenario: one tool succeeds, one throws at runtime. // The model should see both the success and the error, and be allowed to retry. const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'fetchData', args: { url: 'https://example.com' }, result: { data: 'some content' }, }, { toolCallId: 'call-2', toolName: 'processData', args: { data: null }, result: undefined, error: new Error('Cannot process null data'), }, ]; const result = await llmMappingStep.execute(createExecuteParams(inputData)); // Should emit tool-error for the failed tool expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-error', payload: expect.objectContaining({ toolCallId: 'call-2', toolName: 'processData', }), }), ); // Should also emit tool-result for the successful tool expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-result', payload: expect.objectContaining({ toolCallId: 'call-1', toolName: 'fetchData', result: { data: 'some content' }, }), }), ); // Both error and success tool invocations should be updated in messageList expect(messageList.updateToolInvocation).toHaveBeenCalled(); // Loop should continue for self-recovery expect(bail).not.toHaveBeenCalled(); expect(result.stepResult.isContinued).toBe(true); }); it('should continue the loop when multiple tool execution errors occur in the same turn', async () => { // Multiple tools fail in the same turn. The model should see all errors and recover. const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'toolA', args: { x: 1 }, result: undefined, error: new Error('Network timeout'), }, { toolCallId: 'call-2', toolName: 'toolB', args: { y: 2 }, result: undefined, error: new TypeError('Cannot read property "foo" of undefined'), }, ]; const result = await llmMappingStep.execute(createExecuteParams(inputData)); // Both errors should be emitted as tool-error chunks expect(controller.enqueue).toHaveBeenCalledTimes(2); // Errors should be updated in messageList for the model to see expect(messageList.updateToolInvocation).toHaveBeenCalled(); // Loop should continue — model should see the errors and adapt expect(bail).not.toHaveBeenCalled(); expect(result.stepResult.isContinued).toBe(true); }); it('should continue and persist provider-executed result when tool-not-found co-occurs with provider-executed tool', async () => { // Arrange: One hallucinated tool (ToolNotFoundError) + one provider-executed tool with result const { ToolNotFoundError } = await import('../errors'); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'creating:view', args: { param: 'test' }, result: undefined, error: new ToolNotFoundError('Tool "creating:view" not found.'), }, { toolCallId: 'call-2', toolName: 'web_search_20250305', args: { query: 'test' }, result: { providerExecuted: true, toolName: 'web_search_20250305' }, providerExecuted: true, }, ]; // Act const result = await llmMappingStep.execute(createExecuteParams(inputData)); // Assert: Should NOT bail — tool-not-found should self-correct expect(bail).not.toHaveBeenCalled(); expect(result.stepResult.isContinued).toBe(true); // Should only update the error tool invocation — provider-executed tools are handled by llm-execution-step expect(messageList.updateToolInvocation).toHaveBeenCalledTimes(1); const updatedPart = (messageList.updateToolInvocation as ReturnType).mock.calls[0][0]; expect(updatedPart.toolInvocation.toolName).toBe('unknown_tool'); // sanitized from 'creating:view' }); }); describe('createLLMMappingStep provider-executed tool message filtering', () => { let controller: { enqueue: ReturnType }; let messageList: MessageList; let llmExecutionStep: any; let bail: ReturnType; let getStepResultAsync: ReturnType; let llmMappingStep: ReturnType; const createExecuteParams = ( inputData: ToolCallOutput[], ): ExecuteFunctionParams<{}, ToolCallOutput[], any, any, any> => ({ runId: 'test-run', workflowId: 'test-workflow', mastra: {} as any, requestContext: new RequestContext(), state: {}, setState: vi.fn(), retryCount: 1, tracingContext: {} as any, getInitData: vi.fn(), getStepResult: vi.fn(), getStepResultAsync, suspend: vi.fn(), bail, abort: vi.fn(), engine: 'default' as any, abortSignal: new AbortController().signal, writer: new ToolStream({ prefix: 'tool', callId: 'test-call-id', name: 'test-tool', runId: 'test-run', }), validateSchemas: false, inputData, [PUBSUB_SYMBOL]: {} as any, [STREAM_FORMAT_SYMBOL]: undefined, }); beforeEach(() => { controller = { enqueue: vi.fn() }; messageList = { get: { all: { aiV5: { model: () => [] } }, input: { aiV5: { model: () => [] } }, response: { aiV5: { model: () => [] } }, }, add: vi.fn(), updateToolInvocation: vi.fn(), } as unknown as MessageList; llmExecutionStep = createStep({ id: 'test-llm-execution', inputSchema: z.any(), outputSchema: z.any(), execute: async () => ({ stepResult: { isContinued: true, reason: undefined }, metadata: {}, }), }); bail = vi.fn(data => data); getStepResultAsync = vi.fn(async () => ({ stepResult: { isContinued: true, reason: undefined }, metadata: {}, })); llmMappingStep = createLLMMappingStep( { models: {} as any, controller, messageList, runId: 'test-run', _internal: { generateId: () => 'test-message-id', }, } as any, llmExecutionStep, ); }); it('should only call updateToolInvocation for client-executed tools (provider-executed tools are handled by llm-execution-step)', async () => { const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'get_company_info', args: { name: 'test' }, result: { company: 'Acme' }, }, { toolCallId: 'call-2', toolName: 'web_search_20250305', args: { query: 'test' }, result: { providerExecuted: true, toolName: 'web_search_20250305' }, providerExecuted: true, }, ]; await llmMappingStep.execute(createExecuteParams(inputData)); // Only one updateToolInvocation call — for the client-executed tool expect(messageList.updateToolInvocation).toHaveBeenCalledTimes(1); const call = (messageList.updateToolInvocation as ReturnType).mock.calls[0][0]; expect(call.toolInvocation.toolName).toBe('get_company_info'); }); it('should not call updateToolInvocation when only provider-executed tools are present', async () => { const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'web_search_20250305', args: { query: 'test' }, result: { providerExecuted: true, toolName: 'web_search_20250305' }, providerExecuted: true, }, ]; await llmMappingStep.execute(createExecuteParams(inputData)); // No updateToolInvocation calls — provider tools are already state:'result' from llm-execution-step expect(messageList.updateToolInvocation).not.toHaveBeenCalled(); }); it('should emit stream chunks for provider-executed tools even though they are excluded from the client tool-result message', async () => { const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'get_company_info', args: { name: 'test' }, result: { company: 'Acme' }, }, { toolCallId: 'call-2', toolName: 'web_search_20250305', args: { query: 'test' }, result: { providerExecuted: true, toolName: 'web_search_20250305' }, providerExecuted: true, }, ]; await llmMappingStep.execute(createExecuteParams(inputData)); // Stream chunks should be emitted for BOTH tools expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-result', payload: expect.objectContaining({ toolCallId: 'call-1' }), }), ); expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-result', payload: expect.objectContaining({ toolCallId: 'call-2' }), }), ); }); }); describe('createLLMMappingStep toModelOutput', () => { let controller: { enqueue: Mock }; let messageList: MessageList; let llmExecutionStep: any; let bail: Mock; let getStepResultAsync: Mock; const createExecuteParams = ( inputData: ToolCallOutput[], ): ExecuteFunctionParams<{}, ToolCallOutput[], any, any, any> => ({ runId: 'test-run', workflowId: 'test-workflow', mastra: {} as any, requestContext: new RequestContext(), state: {}, setState: vi.fn(), retryCount: 1, tracingContext: {} as any, getInitData: vi.fn(), getStepResult: vi.fn(), getStepResultAsync, suspend: vi.fn(), bail, abort: vi.fn(), engine: 'default' as any, abortSignal: new AbortController().signal, writer: new ToolStream({ prefix: 'tool', callId: 'test-call-id', name: 'test-tool', runId: 'test-run', }), validateSchemas: false, inputData, [PUBSUB_SYMBOL]: {} as any, [STREAM_FORMAT_SYMBOL]: undefined, }); beforeEach(() => { controller = { enqueue: vi.fn() }; messageList = { get: { all: { aiV5: { model: () => [] } }, input: { aiV5: { model: () => [] } }, response: { aiV5: { model: () => [] } }, }, add: vi.fn(), updateToolInvocation: vi.fn(), } as unknown as MessageList; llmExecutionStep = createStep({ id: 'test-llm-execution', inputSchema: z.any(), outputSchema: z.any(), execute: async () => ({ stepResult: { isContinued: true, reason: undefined }, metadata: {}, }), }); bail = vi.fn(data => data); getStepResultAsync = vi.fn(async () => ({ stepResult: { isContinued: true, reason: undefined }, metadata: {}, })); }); it('should call toModelOutput and store result on providerMetadata.mastra.modelOutput', async () => { const toModelOutputMock = vi.fn((output: unknown) => ({ type: 'text', value: `Transformed: ${JSON.stringify(output)}`, })); const llmMappingStep = createLLMMappingStep( { models: {} as any, controller, messageList, runId: 'test-run', _internal: { generateId: () => 'test-message-id' }, tools: { weather: { execute: async () => ({ temperature: 72 }), toModelOutput: toModelOutputMock, inputSchema: z.object({ city: z.string() }), }, }, } as any, llmExecutionStep, ); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'weather', args: { city: 'NYC' }, result: { temperature: 72, conditions: 'sunny' }, }, ]; await llmMappingStep.execute(createExecuteParams(inputData)); // toModelOutput should have been called with the raw result expect(toModelOutputMock).toHaveBeenCalledWith({ temperature: 72, conditions: 'sunny' }); // The tool invocation should be updated with providerMetadata.mastra.modelOutput expect(messageList.updateToolInvocation).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-invocation', toolInvocation: expect.objectContaining({ toolCallId: 'call-1', result: { temperature: 72, conditions: 'sunny' }, // raw result preserved }), providerMetadata: expect.objectContaining({ mastra: expect.objectContaining({ modelOutput: { type: 'text', value: 'Transformed: {"temperature":72,"conditions":"sunny"}', }, }), }), }), ); // The emitted tool-result chunk should also carry modelOutput on providerMetadata // so harness consumers (e.g. mastracode TUI) can read it without going through the messageList. expect(controller.enqueue).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-result', payload: expect.objectContaining({ toolCallId: 'call-1', providerMetadata: expect.objectContaining({ mastra: expect.objectContaining({ modelOutput: { type: 'text', value: 'Transformed: {"temperature":72,"conditions":"sunny"}', }, }), }), }), }), ); }); it('should preserve media parts in toModelOutput', async () => { const toModelOutputMock = vi.fn(() => ({ type: 'content', value: [ { type: 'media', data: 'base64png', mediaType: 'image/png' }, { type: 'media', data: 'base64pdf', mediaType: 'application/pdf' }, { type: 'text', text: 'caption' }, ], })); const llmMappingStep = createLLMMappingStep( { models: {} as any, controller, messageList, runId: 'test-run', _internal: { generateId: () => 'test-message-id' }, tools: { screenshot: { execute: async () => ({ base64: 'abc' }), toModelOutput: toModelOutputMock, inputSchema: z.object({}), }, }, } as any, llmExecutionStep, ); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'screenshot', args: {}, result: { base64: 'abc' }, }, ]; await llmMappingStep.execute(createExecuteParams(inputData)); expect(messageList.updateToolInvocation).toHaveBeenCalledWith( expect.objectContaining({ providerMetadata: expect.objectContaining({ mastra: expect.objectContaining({ modelOutput: { type: 'content', value: [ { type: 'media', data: 'base64png', mediaType: 'image/png' }, { type: 'media', data: 'base64pdf', mediaType: 'application/pdf' }, { type: 'text', text: 'caption' }, ], }, }), }), }), ); }); it('should not throw when toModelOutput returns malformed content entries', async () => { const toModelOutputMock = vi.fn(() => ({ type: 'content', value: [null, undefined, 'not-an-object', { type: 'media', data: 'abc', mediaType: 'image/png' }], })); const llmMappingStep = createLLMMappingStep( { models: {} as any, controller, messageList, runId: 'test-run', _internal: { generateId: () => 'test-message-id' }, tools: { screenshot: { execute: async () => ({ base64: 'abc' }), toModelOutput: toModelOutputMock, inputSchema: z.object({}), }, }, } as any, llmExecutionStep, ); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'screenshot', args: {}, result: { base64: 'abc' }, }, ]; await expect(llmMappingStep.execute(createExecuteParams(inputData))).resolves.not.toThrow(); expect(messageList.updateToolInvocation).toHaveBeenCalledWith( expect.objectContaining({ providerMetadata: expect.objectContaining({ mastra: expect.objectContaining({ modelOutput: { type: 'content', value: [null, undefined, 'not-an-object', { type: 'media', data: 'abc', mediaType: 'image/png' }], }, }), }), }), ); }); it('should NOT call toModelOutput for tools without it defined', async () => { const llmMappingStep = createLLMMappingStep( { models: {} as any, controller, messageList, runId: 'test-run', _internal: { generateId: () => 'test-message-id' }, tools: { plainTool: { execute: async () => ({ done: true }), inputSchema: z.object({ input: z.string() }), }, }, } as any, llmExecutionStep, ); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'plainTool', args: { input: 'test' }, result: { done: true }, }, ]; await llmMappingStep.execute(createExecuteParams(inputData)); // Tool invocation should be updated without providerMetadata expect(messageList.updateToolInvocation).toHaveBeenCalledWith( expect.objectContaining({ type: 'tool-invocation', toolInvocation: expect.objectContaining({ toolCallId: 'call-1', result: { done: true }, }), }), ); // providerMetadata should not be set on the part const updatedPart = (messageList.updateToolInvocation as Mock).mock.calls[0]![0]; expect(updatedPart.providerMetadata).toBeUndefined(); }); it('should call toModelOutput for mixed tools (only the ones that define it)', async () => { const toModelOutputMock = vi.fn((_output: unknown) => ({ type: 'text', value: 'transformed', })); const llmMappingStep = createLLMMappingStep( { models: {} as any, controller, messageList, runId: 'test-run', _internal: { generateId: () => 'test-message-id' }, tools: { withTransform: { execute: async () => ({ data: 'raw' }), toModelOutput: toModelOutputMock, inputSchema: z.object({}), }, withoutTransform: { execute: async () => ({ data: 'raw' }), inputSchema: z.object({}), }, }, } as any, llmExecutionStep, ); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'withTransform', args: {}, result: { data: 'raw' }, }, { toolCallId: 'call-2', toolName: 'withoutTransform', args: {}, result: { data: 'raw' }, }, ]; await llmMappingStep.execute(createExecuteParams(inputData)); expect(toModelOutputMock).toHaveBeenCalledTimes(1); expect(toModelOutputMock).toHaveBeenCalledWith({ data: 'raw' }); const calls = (messageList.updateToolInvocation as Mock).mock.calls; const withTransformPart = calls.find(([p]: [any]) => p.toolInvocation.toolName === 'withTransform')?.[0]; const withoutTransformPart = calls.find(([p]: [any]) => p.toolInvocation.toolName === 'withoutTransform')?.[0]; // First tool should have modelOutput expect(withTransformPart.providerMetadata?.mastra?.modelOutput).toEqual({ type: 'text', value: 'transformed', }); // Second tool should NOT have providerMetadata expect(withoutTransformPart.providerMetadata).toBeUndefined(); }); it('should call toModelOutput for tools loaded dynamically via _internal.stepTools (e.g. ToolSearchProcessor)', async () => { const toModelOutputMock = vi.fn((_output: unknown) => ({ type: 'text', value: 'summarized', })); // Simulate ToolSearchProcessor: tools is empty, dynamically loaded tools are in _internal.stepTools const llmMappingStep = createLLMMappingStep( { models: {} as any, controller, messageList, runId: 'test-run', _internal: { generateId: () => 'test-message-id', stepTools: { 'dynamic-tool': { execute: async () => ({ heavy: 'data' }), toModelOutput: toModelOutputMock, inputSchema: z.object({}), }, }, }, tools: {}, // Empty — simulates tools: {} on agent with ToolSearchProcessor } as any, llmExecutionStep, ); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'dynamic-tool', args: {}, result: { heavy: 'data' }, }, ]; await llmMappingStep.execute(createExecuteParams(inputData)); expect(toModelOutputMock).toHaveBeenCalledTimes(1); expect(toModelOutputMock).toHaveBeenCalledWith({ heavy: 'data' }); const calls = (messageList.updateToolInvocation as Mock).mock.calls; const dynamicToolPart = calls.find(([p]: [any]) => p.toolInvocation.toolName === 'dynamic-tool')?.[0]; expect(dynamicToolPart.providerMetadata?.mastra?.modelOutput).toEqual({ type: 'text', value: 'summarized', }); }); it('should NOT call toModelOutput when tool result is null/undefined', async () => { const toModelOutputMock = vi.fn(); const llmMappingStep = createLLMMappingStep( { models: {} as any, controller, messageList, runId: 'test-run', _internal: { generateId: () => 'test-message-id' }, tools: { hitlTool: { toModelOutput: toModelOutputMock, inputSchema: z.object({}), }, }, } as any, llmExecutionStep, ); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'hitlTool', args: {}, result: undefined, // HITL — no result yet }, ]; await llmMappingStep.execute(createExecuteParams(inputData)); // toModelOutput should NOT be called for undefined results expect(toModelOutputMock).not.toHaveBeenCalled(); }); // ---- MAPPING span coverage (issue #15486) ---- type MockChildSpan = { createOptions: any; endOptions?: any; errorOptions?: any; ended: boolean; errored: boolean; end: Mock; error: Mock; }; function createMockParentSpan() { const childSpans: MockChildSpan[] = []; const parentSpan: any = { createChildSpan: vi.fn((opts: any) => { const child: MockChildSpan = { createOptions: opts, ended: false, errored: false, end: vi.fn(), error: vi.fn(), }; child.end = vi.fn((endOpts: any) => { child.endOptions = endOpts; child.ended = true; }) as any; child.error = vi.fn((errOpts: any) => { child.errorOptions = errOpts; child.errored = true; }) as any; childSpans.push(child); return child; }), }; return { parentSpan, childSpans }; } it('should emit a MAPPING child span when toModelOutput is defined and runs', async () => { const { parentSpan, childSpans } = createMockParentSpan(); const toModelOutputMock = vi.fn((output: any) => ({ type: 'text', value: output.temperature })); const llmMappingStep = createLLMMappingStep( { models: {} as any, controller, messageList, runId: 'test-run', _internal: { generateId: () => 'test-message-id' }, tools: { weather: { execute: async () => ({ temperature: 72 }), toModelOutput: toModelOutputMock, inputSchema: z.object({}), }, }, modelSpanTracker: { getTracingContext: () => ({ currentSpan: parentSpan }), }, } as any, llmExecutionStep, ); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'weather', args: {}, result: { temperature: 72 } }, ]; await llmMappingStep.execute(createExecuteParams(inputData)); expect(parentSpan.createChildSpan).toHaveBeenCalledTimes(1); expect(childSpans).toHaveLength(1); const [span] = childSpans; expect(span.createOptions).toMatchObject({ type: 'mapping', name: "tool output mapping: 'weather'", entityType: 'tool', entityId: 'weather', entityName: 'weather', input: { temperature: 72 }, attributes: { mappingType: 'toModelOutput', toolCallId: 'call-1', }, }); expect(span.ended).toBe(true); expect(span.endOptions).toEqual({ output: { type: 'text', value: 72 } }); expect(span.errored).toBe(false); }); it('should NOT emit a MAPPING span when the tool has no toModelOutput', async () => { const { parentSpan, childSpans } = createMockParentSpan(); const llmMappingStep = createLLMMappingStep( { models: {} as any, controller, messageList, runId: 'test-run', _internal: { generateId: () => 'test-message-id' }, tools: { plain: { execute: async () => ({ temperature: 72 }), inputSchema: z.object({}), }, }, modelSpanTracker: { getTracingContext: () => ({ currentSpan: parentSpan }), }, } as any, llmExecutionStep, ); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'plain', args: {}, result: { temperature: 72 } }, ]; await llmMappingStep.execute(createExecuteParams(inputData)); expect(parentSpan.createChildSpan).not.toHaveBeenCalled(); expect(childSpans).toHaveLength(0); }); it('should NOT emit a MAPPING span when tool result is null/undefined even if toModelOutput is defined', async () => { const { parentSpan, childSpans } = createMockParentSpan(); const llmMappingStep = createLLMMappingStep( { models: {} as any, controller, messageList, runId: 'test-run', _internal: { generateId: () => 'test-message-id' }, tools: { hitlTool: { toModelOutput: vi.fn(), inputSchema: z.object({}), }, }, modelSpanTracker: { getTracingContext: () => ({ currentSpan: parentSpan }), }, } as any, llmExecutionStep, ); const inputData: ToolCallOutput[] = [{ toolCallId: 'call-1', toolName: 'hitlTool', args: {}, result: undefined }]; await llmMappingStep.execute(createExecuteParams(inputData)); expect(parentSpan.createChildSpan).not.toHaveBeenCalled(); expect(childSpans).toHaveLength(0); }); it('should mark the MAPPING span as errored and re-throw when toModelOutput throws', async () => { const { parentSpan, childSpans } = createMockParentSpan(); const failure = new Error('transform failed'); const toModelOutputMock = vi.fn(() => { throw failure; }); const llmMappingStep = createLLMMappingStep( { models: {} as any, controller, messageList, runId: 'test-run', _internal: { generateId: () => 'test-message-id' }, tools: { broken: { execute: async () => ({ data: 'raw' }), toModelOutput: toModelOutputMock, inputSchema: z.object({}), }, }, modelSpanTracker: { getTracingContext: () => ({ currentSpan: parentSpan }), }, } as any, llmExecutionStep, ); const inputData: ToolCallOutput[] = [ { toolCallId: 'call-1', toolName: 'broken', args: {}, result: { data: 'raw' } }, ]; // A toModelOutput failure fails the run on every engine. await expect(llmMappingStep.execute(createExecuteParams(inputData))).rejects.toBe(failure); expect(childSpans).toHaveLength(1); const [span] = childSpans; expect(span.ended).toBe(false); expect(span.errored).toBe(true); expect(span.errorOptions).toEqual({ error: failure, endSpan: true }); }); });