import type { LanguageModelV2CallOptions, LanguageModelV2FunctionTool, LanguageModelV2ProviderDefinedTool, } from '@ai-sdk/provider-v5'; import { stepCountIs, tool } from '@internal/ai-sdk-v5'; import { convertArrayToReadableStream, mockId, mockValues } from '@internal/ai-sdk-v5/test'; import { MastraLanguageModelV2Mock as MockLanguageModelV2 } from './MastraLanguageModelV2Mock'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { z } from 'zod/v4'; import type { loop } from '../loop'; import type { ChunkType } from '../../stream/types'; import { createTestModels, testUsage, defaultSettings, modelWithSources, modelWithFiles, testUsage2, createMessageListWithUserMessage, stripMastraCreatedAt, } from './utils'; import { convertAsyncIterableToArray } from './stream-helpers'; export function optionsTests({ loopFn, runId }: { loopFn: typeof loop; runId: string }) { describe('options.abortSignal', () => { it('should forward abort signal to tool execution during streaming', async () => { const messageList = createMessageListWithUserMessage(); const abortController = new AbortController(); const toolExecuteMock = vi.fn().mockResolvedValue('tool result'); const result = loopFn({ methodType: 'stream', runId, models: createTestModels({ stream: convertArrayToReadableStream([ { type: 'tool-call', toolCallId: 'call-1', toolName: 'tool1', input: `{ "value": "value" }`, }, { type: 'finish', finishReason: 'stop', usage: testUsage, }, ]), }), tools: { tool1: { inputSchema: z.object({ value: z.string() }), execute: toolExecuteMock, }, }, messageList, options: { abortSignal: abortController.signal, }, agentId: 'agent-id', }); await convertAsyncIterableToArray(result.fullStream as any); abortController.abort(); // The tool is handed a signal derived from the caller's, not the caller's own // object: eager execution has to be able to cancel one call on its own without // aborting the run. What the tool depends on is that aborting the caller aborts // the signal it was given, so assert that rather than object identity. const toolAbortSignal = toolExecuteMock.mock.calls[0]?.[1]?.abortSignal as AbortSignal; expect(toolAbortSignal).toBeInstanceOf(AbortSignal); expect(toolAbortSignal.aborted).toBe(true); expect(toolExecuteMock).toHaveBeenCalledWith( { value: 'value' }, expect.objectContaining({ toolCallId: 'call-1', messages: expect.any(Array), outputWriter: expect.any(Function), requestContext: expect.any(Object), resumeData: undefined, suspend: expect.any(Function), tracingContext: undefined, workspace: undefined, }), ); }); }); describe('options.providerMetadata', () => { it('should pass provider metadata to model', async () => { const messageList = createMessageListWithUserMessage(); const result = loopFn({ methodType: 'stream', runId, models: [ { id: 'test-model', maxRetries: 0, model: new MockLanguageModelV2({ doStream: async ({ providerOptions }) => { expect(providerOptions).toStrictEqual({ aProvider: { someKey: 'someValue' }, }); return { stream: convertArrayToReadableStream([ { type: 'text-start', id: 'text-1' }, { type: 'text-delta', id: 'text-1', delta: 'provider metadata test', }, { type: 'text-end', id: 'text-1' }, { type: 'finish', finishReason: 'stop', usage: testUsage, }, ]), }; }, }), }, ], messageList, providerOptions: { aProvider: { someKey: 'someValue' }, }, agentId: 'agent-id', }); expect(await convertAsyncIterableToArray(result.textStream as any)).toEqual(['provider metadata test']); }); }); describe('options.stopWhen', () => { let result: any; let onFinishResult: any; let onStepFinishResults: any[]; let tracer: any; let stepInputs: Array; beforeEach(() => { stepInputs = []; }); describe('2 steps: initial, tool-result', () => { beforeEach(async () => { const messageList = createMessageListWithUserMessage(); result = undefined as any; onFinishResult = undefined as any; onStepFinishResults = []; let responseCount = 0; result = await loopFn({ methodType: 'stream', runId, models: [ { id: 'test-model', maxRetries: 0, model: new MockLanguageModelV2({ doStream: async ({ prompt, tools, toolChoice }) => { stepInputs.push({ prompt, tools, toolChoice }); switch (responseCount++) { case 0: { return { stream: convertArrayToReadableStream([ { type: 'response-metadata', id: 'id-0', modelId: 'mock-model-id', timestamp: new Date(0), }, { type: 'reasoning-start', id: '0' }, { type: 'reasoning-delta', id: '0', delta: 'thinking' }, { type: 'reasoning-end', id: '0' }, { type: 'tool-call', id: 'call-1', toolCallId: 'call-1', toolName: 'tool1', input: `{ "value": "value" }`, }, { type: 'finish', finishReason: 'tool-calls', usage: testUsage, }, ]), response: { headers: { call: '1' } }, }; } case 1: { return { stream: convertArrayToReadableStream([ { type: 'response-metadata', id: 'id-1', modelId: 'mock-model-id', timestamp: new Date(1000), }, { type: 'text-start', id: 'text-1' }, { type: 'text-delta', id: 'text-1', delta: 'Hello, ' }, { type: 'text-delta', id: 'text-1', delta: `world!` }, { type: 'text-end', id: 'text-1' }, { type: 'finish', finishReason: 'stop', usage: testUsage2, }, ]), response: { headers: { call: '2' } }, }; } default: throw new Error(`Unexpected response count: ${responseCount}`); } }, }), }, ], tools: { tool1: { inputSchema: z.object({ value: z.string() }), execute: async () => 'result1', }, }, messageList, options: { onFinish: async event => { expect(onFinishResult).to.be.undefined; onFinishResult = event as unknown as typeof onFinishResult; }, onStepFinish: async event => { onStepFinishResults.push(event); }, }, stopWhen: stepCountIs(3), _internal: { now: mockValues(0, 100, 500, 600, 1000), generateId: mockId({ prefix: 'id' }), }, agentId: 'agent-id', }); }); it('should contain correct step inputs', async () => { await result.consumeStream(); expect(stepInputs).toMatchInlineSnapshot(` [ { "prompt": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "test-input", "type": "text", }, ], "role": "user", }, ], "toolChoice": { "type": "auto", }, "tools": [ { "description": undefined, "inputSchema": { "$schema": "http://json-schema.org/draft-07/schema#", "additionalProperties": false, "properties": { "value": { "type": "string", }, }, "required": [ "value", ], "type": "object", }, "name": "tool1", "providerOptions": undefined, "type": "function", }, ], }, { "prompt": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "test-input", "type": "text", }, ], "role": "user", }, { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, ], "toolChoice": { "type": "auto", }, "tools": [ { "description": undefined, "inputSchema": { "$schema": "http://json-schema.org/draft-07/schema#", "additionalProperties": false, "properties": { "value": { "type": "string", }, }, "required": [ "value", ], "type": "object", }, "name": "tool1", "providerOptions": undefined, "type": "function", }, ], }, ] `); }); it('should contain assistant response message and tool message from all steps', async () => { expect(await convertAsyncIterableToArray(result.fullStream)).toMatchInlineSnapshot(` [ { "from": "AGENT", "payload": { "id": "agent-id", "messageId": "id-0", }, "runId": "test-run-id", "type": "start", }, { "from": "AGENT", "payload": { "messageId": "id-0", "modelId": "mock-model-id", "provider": "mock-provider", "request": {}, "startedAt": 1704067200000, "warnings": [], }, "runId": "test-run-id", "type": "step-start", }, { "from": "AGENT", "payload": { "id": "0", "providerMetadata": undefined, }, "runId": "test-run-id", "type": "reasoning-start", }, { "from": "AGENT", "payload": { "id": "0", "providerMetadata": undefined, "text": "thinking", }, "runId": "test-run-id", "type": "reasoning-delta", }, { "from": "AGENT", "payload": { "id": "0", "providerMetadata": undefined, }, "runId": "test-run-id", "type": "reasoning-end", }, { "from": "AGENT", "payload": { "args": { "value": "value", }, "providerExecuted": undefined, "providerMetadata": undefined, "toolCallId": "call-1", "toolName": "tool1", }, "runId": "test-run-id", "type": "tool-call", }, { "from": "AGENT", "payload": { "args": { "value": "value", }, "providerExecuted": undefined, "providerMetadata": undefined, "result": "result1", "toolCallId": "call-1", "toolName": "tool1", }, "runId": "test-run-id", "type": "tool-result", }, { "from": "AGENT", "payload": { "messageId": "id-0", "messages": { "all": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "test-input", "type": "text", }, ], "role": "user", }, { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, ], "nonUser": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, ], "user": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "test-input", "type": "text", }, ], "role": "user", }, ], }, "metadata": { "headers": { "call": "1", }, "id": "id-0", "modelId": "mock-model-id", "modelMetadata": { "modelId": "mock-model-id", "modelProvider": "mock-provider", "modelVersion": "v2", }, "providerMetadata": undefined, "request": {}, "timestamp": 1970-01-01T00:00:00.000Z, }, "output": { "steps": [ DefaultStepResult { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "finishReason": undefined, "providerMetadata": undefined, "request": {}, "response": { "headers": { "call": "1", }, "id": "id-0", "messages": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [], "role": "tool", }, ], "modelId": "mock-model-id", "timestamp": 1970-01-01T00:00:00.000Z, }, "tripwire": undefined, "usage": { "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": undefined, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": undefined, "totalTokens": 13, }, "totalTokens": 13, }, "warnings": [], }, DefaultStepResult { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "Hello, world!", "type": "text", }, ], "finishReason": undefined, "providerMetadata": undefined, "request": {}, "response": { "headers": { "call": "2", }, "id": "id-1", "messages": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "Hello, world!", "type": "text", }, ], "role": "assistant", }, ], "modelId": "mock-model-id", "timestamp": 1970-01-01T00:00:01.000Z, }, "tripwire": undefined, "usage": { "cachedInputTokens": 3, "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": 3, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": 10, "totalTokens": 23, }, "reasoningTokens": 10, "totalTokens": 23, }, "warnings": [], }, ], "text": "", "toolCalls": [ { "args": { "value": "value", }, "providerExecuted": undefined, "providerMetadata": undefined, "toolCallId": "call-1", "toolName": "tool1", }, ], "usage": { "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": undefined, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": undefined, "totalTokens": 13, }, "totalTokens": 13, }, }, "processorRetryCount": 0, "processorRetryFeedback": undefined, "stepResult": { "isContinued": true, "reason": "tool-calls", "warnings": undefined, }, }, "runId": "test-run-id", "type": "step-finish", }, { "from": "AGENT", "payload": { "messageId": "id-0", "modelId": "mock-model-id", "provider": "mock-provider", "request": {}, "startedAt": 1704067200000, "warnings": [], }, "runId": "test-run-id", "type": "step-start", }, { "from": "AGENT", "payload": { "id": "text-1", "providerMetadata": undefined, }, "runId": "test-run-id", "type": "text-start", }, { "from": "AGENT", "payload": { "id": "text-1", "providerMetadata": undefined, "text": "Hello, ", }, "runId": "test-run-id", "type": "text-delta", }, { "from": "AGENT", "payload": { "id": "text-1", "providerMetadata": undefined, "text": "world!", }, "runId": "test-run-id", "type": "text-delta", }, { "from": "AGENT", "payload": { "id": "text-1", "type": "text-end", }, "runId": "test-run-id", "type": "text-end", }, { "from": "AGENT", "payload": { "messageId": "id-0", "messages": { "all": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "test-input", "type": "text", }, ], "role": "user", }, { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "Hello, world!", "type": "text", }, ], "role": "assistant", }, ], "nonUser": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "Hello, world!", "type": "text", }, ], "role": "assistant", }, ], "user": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "test-input", "type": "text", }, ], "role": "user", }, ], }, "metadata": { "headers": { "call": "2", }, "id": "id-1", "modelId": "mock-model-id", "modelMetadata": { "modelId": "mock-model-id", "modelProvider": "mock-provider", "modelVersion": "v2", }, "providerMetadata": undefined, "request": {}, "timestamp": 1970-01-01T00:00:01.000Z, }, "output": { "steps": [ DefaultStepResult { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "finishReason": undefined, "providerMetadata": undefined, "request": {}, "response": { "headers": { "call": "1", }, "id": "id-0", "messages": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [], "role": "tool", }, ], "modelId": "mock-model-id", "timestamp": 1970-01-01T00:00:00.000Z, }, "tripwire": undefined, "usage": { "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": undefined, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": undefined, "totalTokens": 13, }, "totalTokens": 13, }, "warnings": [], }, DefaultStepResult { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "Hello, world!", "type": "text", }, ], "finishReason": undefined, "providerMetadata": undefined, "request": {}, "response": { "headers": { "call": "2", }, "id": "id-1", "messages": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "Hello, world!", "type": "text", }, ], "role": "assistant", }, ], "modelId": "mock-model-id", "timestamp": 1970-01-01T00:00:01.000Z, }, "tripwire": undefined, "usage": { "cachedInputTokens": 3, "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": 3, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": 10, "totalTokens": 23, }, "reasoningTokens": 10, "totalTokens": 23, }, "warnings": [], }, ], "text": "Hello, world!", "toolCalls": [], "usage": { "cachedInputTokens": 3, "inputTokens": 6, "outputTokens": 20, "raw": { "cachedInputTokens": 3, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": 10, "totalTokens": 23, }, "reasoningTokens": 10, "totalTokens": 36, }, }, "processorRetryCount": 0, "processorRetryFeedback": undefined, "stepResult": { "isContinued": false, "reason": "stop", "warnings": undefined, }, }, "runId": "test-run-id", "type": "step-finish", }, { "from": "AGENT", "payload": { "messageId": "id-0", "messages": { "all": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "test-input", "type": "text", }, ], "role": "user", }, { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "Hello, world!", "type": "text", }, ], "role": "assistant", }, ], "nonUser": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "Hello, world!", "type": "text", }, ], "role": "assistant", }, ], "user": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "test-input", "type": "text", }, ], "role": "user", }, ], }, "metadata": { "headers": { "call": "2", }, "id": "id-1", "modelId": "mock-model-id", "modelMetadata": { "modelId": "mock-model-id", "modelProvider": "mock-provider", "modelVersion": "v2", }, "providerMetadata": undefined, "request": {}, "timestamp": 1970-01-01T00:00:01.000Z, }, "output": { "steps": [ DefaultStepResult { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "finishReason": undefined, "providerMetadata": undefined, "request": {}, "response": { "headers": { "call": "1", }, "id": "id-0", "messages": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [], "role": "tool", }, ], "modelId": "mock-model-id", "timestamp": 1970-01-01T00:00:00.000Z, }, "tripwire": undefined, "usage": { "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": undefined, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": undefined, "totalTokens": 13, }, "totalTokens": 13, }, "warnings": [], }, DefaultStepResult { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "Hello, world!", "type": "text", }, ], "finishReason": undefined, "providerMetadata": undefined, "request": {}, "response": { "headers": { "call": "2", }, "id": "id-1", "messages": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "Hello, world!", "type": "text", }, ], "role": "assistant", }, ], "modelId": "mock-model-id", "timestamp": 1970-01-01T00:00:01.000Z, }, "tripwire": undefined, "usage": { "cachedInputTokens": 3, "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": 3, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": 10, "totalTokens": 23, }, "reasoningTokens": 10, "totalTokens": 23, }, "warnings": [], }, ], "text": "Hello, world!", "toolCalls": [], "usage": { "cachedInputTokens": 3, "inputTokens": 6, "outputTokens": 20, "raw": { "cachedInputTokens": 3, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": 10, "totalTokens": 23, }, "reasoningTokens": 10, "totalTokens": 36, }, }, "processorRetryCount": 0, "processorRetryFeedback": undefined, "stepResult": { "isContinued": false, "reason": "stop", "warnings": undefined, }, "stopCause": "model_finished", }, "runId": "test-run-id", "type": "finish", }, ] `); }); describe('value promises', () => { beforeEach(async () => { await result.consumeStream(); }); it('result.response.messages should contain response messages from all steps', async () => { expect((await result.response).messages).toMatchInlineSnapshot(` [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "thinking", "type": "reasoning", }, { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "Hello, world!", "type": "text", }, ], "role": "assistant", }, ] `); }); }); }); describe('2 steps: initial, tool-result with prepareStep', () => { let result: any; let doStreamCalls: Array; let prepareStepCalls: Array<{ model: { modelId: string; provider: string; specificationVersion: string; }; stepNumber: number; steps: Array; messages: Array; }>; beforeEach(async () => { const messageList = createMessageListWithUserMessage(); doStreamCalls = []; prepareStepCalls = []; result = loopFn({ ...defaultSettings(), methodType: 'stream', runId, models: [ { id: 'test-model', maxRetries: 0, model: new MockLanguageModelV2({ doStream: async options => { doStreamCalls.push(options); switch (doStreamCalls.length) { case 1: return { stream: convertArrayToReadableStream([ { type: 'response-metadata', id: 'id-0', modelId: 'mock-model-id', timestamp: new Date(0), }, { type: 'tool-call', toolCallId: 'call-1', toolName: 'tool1', input: `{ "value": "value" }`, }, { type: 'finish', finishReason: 'tool-calls', usage: testUsage, }, ]), response: { headers: { call: '1' } }, }; case 2: return { stream: convertArrayToReadableStream([ { type: 'response-metadata', id: 'id-1', modelId: 'mock-model-id', timestamp: new Date(1000), }, { type: 'text-start', id: 'text-2' }, { type: 'text-delta', id: 'text-2', delta: 'Hello, ' }, { type: 'text-delta', id: 'text-2', delta: `world!` }, { type: 'text-end', id: 'text-2' }, { type: 'finish', finishReason: 'stop', usage: testUsage2, }, ]), response: { headers: { call: '2' } }, }; default: throw new Error(`Unexpected response count: ${doStreamCalls.length}`); } }, }), }, ], agentId: 'agent-id', tools: { tool1: tool({ inputSchema: z.object({ value: z.string() }), execute: async () => 'result1', }), }, messageList, stopWhen: stepCountIs(3), options: { prepareStep: async ({ model, stepNumber, steps, messages }) => { prepareStepCalls.push({ model: { modelId: model.modelId, provider: model.provider, specificationVersion: model.specificationVersion, }, stepNumber, steps, messages, }); if (stepNumber === 0) { return { toolChoice: { type: 'tool', toolName: 'tool1' as const, }, messages: [ { id: 'sys-0', role: 'system' as const, createdAt: new Date(), content: { format: 2 as const, parts: [{ type: 'text' as const, text: 'system-message-0' }], }, }, { id: 'user-0', role: 'user' as const, createdAt: new Date(), content: { format: 2 as const, parts: [{ type: 'text' as const, text: 'new input from prepareStep' }], }, }, ], }; } if (stepNumber === 1) { return { activeTools: [], messages: [ { id: 'sys-1', role: 'system' as const, createdAt: new Date(), content: { format: 2 as const, parts: [{ type: 'text' as const, text: 'system-message-1' }], }, }, { id: 'user-1', role: 'user' as const, createdAt: new Date(), content: { format: 2 as const, parts: [{ type: 'text' as const, text: 'another new input from prepareStep 222' }], }, }, ], }; } return {}; }, }, }); }); it('should contain all prepareStep calls', async () => { await result.consumeStream(); expect(prepareStepCalls).toMatchInlineSnapshot(` [ { "messages": [ { "content": { "content": "test-input", "experimental_attachments": undefined, "format": 2, "metadata": undefined, "parts": [ { "createdAt": 1704067200000, "text": "test-input", "type": "text", }, ], "reasoning": undefined, "toolInvocations": undefined, }, "createdAt": 2024-01-01T00:00:00.000Z, "id": "msg-1", "resourceId": undefined, "role": "user", "threadId": undefined, }, ], "model": { "modelId": "mock-model-id", "provider": "mock-provider", "specificationVersion": "v2", }, "stepNumber": 0, "steps": [ DefaultStepResult { "content": [ { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "finishReason": undefined, "providerMetadata": undefined, "request": {}, "response": { "headers": { "call": "1", }, "id": "id-0", "messages": [ { "content": [ { "input": { "value": "value", }, "providerExecuted": undefined, "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [], "role": "tool", }, ], "modelId": "mock-model-id", "timestamp": 1970-01-01T00:00:00.000Z, }, "tripwire": undefined, "usage": { "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": undefined, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": undefined, "totalTokens": 13, }, "totalTokens": 13, }, "warnings": [], }, DefaultStepResult { "content": [], "finishReason": undefined, "providerMetadata": undefined, "request": {}, "response": { "headers": { "call": "2", }, "id": "id-1", "messages": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "Hello, world!", "type": "text", }, ], "role": "assistant", }, ], "modelId": "mock-model-id", "timestamp": 1970-01-01T00:00:01.000Z, }, "tripwire": undefined, "usage": { "cachedInputTokens": 3, "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": 3, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": 10, "totalTokens": 23, }, "reasoningTokens": 10, "totalTokens": 23, }, "warnings": [], }, ], }, { "messages": [ { "content": { "format": 2, "parts": [ { "createdAt": 1704067200000, "text": "new input from prepareStep", "type": "text", }, ], }, "createdAt": 2024-01-01T00:00:00.000Z, "id": "user-0", "role": "user", }, { "content": { "format": 2, "metadata": { "modelId": "mock-model-id", "provider": "mock-provider", }, "parts": [ { "toolInvocation": { "args": { "value": "value", }, "result": "result1", "state": "result", "toolCallId": "call-1", "toolName": "tool1", }, "type": "tool-invocation", "updatedAt": 1704067200000, }, { "createdAt": 1704067200000, "type": "step-start", }, ], }, "createdAt": 2024-01-01T00:00:00.002Z, "id": "msg-0", "role": "assistant", }, ], "model": { "modelId": "mock-model-id", "provider": "mock-provider", "specificationVersion": "v2", }, "stepNumber": 1, "steps": [ DefaultStepResult { "content": [ { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "finishReason": undefined, "providerMetadata": undefined, "request": {}, "response": { "headers": { "call": "1", }, "id": "id-0", "messages": [ { "content": [ { "input": { "value": "value", }, "providerExecuted": undefined, "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [], "role": "tool", }, ], "modelId": "mock-model-id", "timestamp": 1970-01-01T00:00:00.000Z, }, "tripwire": undefined, "usage": { "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": undefined, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": undefined, "totalTokens": 13, }, "totalTokens": 13, }, "warnings": [], }, DefaultStepResult { "content": [], "finishReason": undefined, "providerMetadata": undefined, "request": {}, "response": { "headers": { "call": "2", }, "id": "id-1", "messages": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "Hello, world!", "type": "text", }, ], "role": "assistant", }, ], "modelId": "mock-model-id", "timestamp": 1970-01-01T00:00:01.000Z, }, "tripwire": undefined, "usage": { "cachedInputTokens": 3, "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": 3, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": 10, "totalTokens": 23, }, "reasoningTokens": 10, "totalTokens": 23, }, "warnings": [], }, ], }, ] `); }); }); }); describe('options.onFinish', () => { it('should not prevent error from being forwarded', async () => { const messageList = createMessageListWithUserMessage(); const result = await loopFn({ methodType: 'stream', runId, agentId: 'agent-id', models: [ { id: 'test-model', maxRetries: 0, model: new MockLanguageModelV2({ doStream: async () => { throw new Error('test error'); }, }), }, ], modelSettings: { maxRetries: 0, }, messageList, options: { onFinish() {}, // just defined; do nothing onError: () => {}, }, _internal: { generateId: mockId({ prefix: 'id' }), }, }); expect((await convertAsyncIterableToArray(await result.fullStream)).slice(0, 3)).toStrictEqual([ { type: 'start', runId: 'test-run-id', from: 'AGENT', payload: { id: 'agent-id', messageId: 'id-0' }, }, { runId: 'test-run-id', from: 'AGENT', type: 'step-start', payload: { request: {}, warnings: [], messageId: 'id-0', startedAt: Date.now(), modelId: 'mock-model-id', provider: 'mock-provider', }, }, { type: 'error', runId: 'test-run-id', from: 'AGENT', payload: { type: 'error', error: new Error('test error'), }, }, ]); }); }); describe('options.onChunk', () => { let result: Array; beforeEach(async () => { const messageList = createMessageListWithUserMessage(); result = []; const resultObject = await loopFn({ methodType: 'stream', runId, agentId: 'agent-id', models: createTestModels({ stream: convertArrayToReadableStream([ { type: 'text-start', id: 'text-1' }, { type: 'text-delta', id: 'text-1', delta: 'Hello' }, { type: 'text-end', id: 'text-1' }, { type: 'tool-input-start', id: '2', toolName: 'tool1', providerMetadata: { provider: { custom: 'value' } }, }, { type: 'tool-input-delta', id: '2', delta: '{"value": "' }, { type: 'reasoning-start', id: '3' }, { type: 'reasoning-delta', id: '3', delta: 'Feeling clever' }, { type: 'reasoning-end', id: '3' }, { type: 'tool-input-delta', id: '2', delta: 'test' }, { type: 'tool-input-delta', id: '2', delta: '"}' }, { type: 'source', sourceType: 'url', id: '123', url: 'https://example.com', title: 'Example', providerMetadata: { provider: { custom: 'value' } }, }, { type: 'tool-input-end', id: '2' }, { type: 'tool-call', toolCallId: '2', toolName: 'tool1', input: `{ "value": "test" }`, providerMetadata: { provider: { custom: 'value' } }, }, { type: 'text-start', id: 'text-4' }, { type: 'text-delta', id: 'text-4', delta: ' World' }, { type: 'text-end', id: 'text-4' }, { type: 'finish', finishReason: 'stop', usage: testUsage2, }, ]), }), tools: { tool1: { inputSchema: z.object({ value: z.string() }), execute: async ({ value }) => `${value}-result`, }, }, messageList, options: { onChunk(chunk) { result.push(chunk); }, }, }); await resultObject.consumeStream(); }); it('should return events in order', async () => { expect(result).toMatchInlineSnapshot(` [ { "from": "AGENT", "payload": { "id": "text-1", "providerMetadata": undefined, "text": "Hello", }, "runId": "test-run-id", "type": "text-delta", }, { "from": "AGENT", "payload": { "dynamic": undefined, "providerExecuted": undefined, "providerMetadata": { "provider": { "custom": "value", }, }, "toolCallId": "2", "toolName": "tool1", }, "runId": "test-run-id", "type": "tool-call-input-streaming-start", }, { "from": "AGENT", "payload": { "argsTextDelta": "{"value": "", "providerMetadata": undefined, "toolCallId": "2", "toolName": "tool1", }, "runId": "test-run-id", "type": "tool-call-delta", }, { "from": "AGENT", "payload": { "id": "3", "providerMetadata": undefined, "text": "Feeling clever", }, "runId": "test-run-id", "type": "reasoning-delta", }, { "from": "AGENT", "payload": { "argsTextDelta": "test", "providerMetadata": undefined, "toolCallId": "2", "toolName": "tool1", }, "runId": "test-run-id", "type": "tool-call-delta", }, { "from": "AGENT", "payload": { "argsTextDelta": ""}", "providerMetadata": undefined, "toolCallId": "2", "toolName": "tool1", }, "runId": "test-run-id", "type": "tool-call-delta", }, { "from": "AGENT", "payload": { "filename": undefined, "id": "123", "mimeType": undefined, "providerMetadata": { "provider": { "custom": "value", }, }, "sourceType": "url", "title": "Example", "url": "https://example.com", }, "runId": "test-run-id", "type": "source", }, { "from": "AGENT", "payload": { "providerMetadata": undefined, "toolCallId": "2", }, "runId": "test-run-id", "type": "tool-call-input-streaming-end", }, { "from": "AGENT", "payload": { "args": { "value": "test", }, "dynamic": undefined, "providerExecuted": undefined, "providerMetadata": { "provider": { "custom": "value", }, }, "toolCallId": "2", "toolName": "tool1", }, "runId": "test-run-id", "type": "tool-call", }, { "from": "AGENT", "payload": { "id": "text-4", "providerMetadata": undefined, "text": " World", }, "runId": "test-run-id", "type": "text-delta", }, { "from": "AGENT", "payload": { "args": { "value": "test", }, "providerExecuted": undefined, "providerMetadata": { "provider": { "custom": "value", }, }, "result": "test-result", "toolCallId": "2", "toolName": "tool1", }, "runId": "test-run-id", "type": "tool-result", }, ] `); }); }); describe('raw chunks forwarding', () => { it('should forward raw chunks when includeRawChunks is enabled', async () => { const messageList = createMessageListWithUserMessage(); const modelWithRawChunks = createTestModels({ stream: convertArrayToReadableStream([ { type: 'stream-start', warnings: [] }, { type: 'raw', rawValue: { type: 'raw-data', content: 'should appear', }, }, { type: 'response-metadata', id: 'test-id', modelId: 'test-model', timestamp: new Date(0), }, { type: 'text-start', id: 'text-1' }, { type: 'text-delta', id: 'text-1', delta: 'Hello, world!' }, { type: 'text-end', id: 'text-1' }, { type: 'finish', finishReason: 'stop', usage: testUsage, }, ]), }); const result = await loopFn({ methodType: 'stream', agentId: 'agent-id', runId, models: modelWithRawChunks, messageList, includeRawChunks: true, }); const chunks = await convertAsyncIterableToArray(result.fullStream); expect(chunks.filter(chunk => chunk.type === 'raw')).toMatchInlineSnapshot(` [ { "from": "AGENT", "payload": { "content": "should appear", "type": "raw-data", }, "runId": "test-run-id", "type": "raw", }, ] `); }); it('should not forward raw chunks when includeRawChunks is disabled', async () => { const messageList = createMessageListWithUserMessage(); const modelWithRawChunks = createTestModels({ stream: convertArrayToReadableStream([ { type: 'stream-start', warnings: [] }, { type: 'raw', rawValue: { type: 'raw-data', content: 'should not appear', }, }, { type: 'response-metadata', id: 'test-id', modelId: 'test-model', timestamp: new Date(0), }, { type: 'text-start', id: 'text-1' }, { type: 'text-delta', id: 'text-1', delta: 'Hello, world!' }, { type: 'text-end', id: 'text-1' }, { type: 'finish', finishReason: 'stop', usage: testUsage, }, ]), }); const result = await loopFn({ methodType: 'stream', agentId: 'agent-id', runId, models: modelWithRawChunks, messageList, includeRawChunks: false, }); const chunks = await convertAsyncIterableToArray(result.fullStream); expect(chunks.filter(chunk => chunk.type === 'raw')).toHaveLength(0); }); it('should call onChunk with raw chunks when includeRawChunks is enabled', async () => { const messageList = createMessageListWithUserMessage(); const onChunkCalls: Array = []; const modelWithRawChunks = createTestModels({ stream: convertArrayToReadableStream([ { type: 'stream-start', warnings: [] }, { type: 'raw', rawValue: { type: 'stream-start', data: 'start' }, }, { type: 'raw', rawValue: { type: 'response-metadata', id: 'test-id', modelId: 'test-model', }, }, { type: 'raw', rawValue: { type: 'text-delta', content: 'Hello' }, }, { type: 'raw', rawValue: { type: 'text-delta', content: ', world!' }, }, { type: 'raw', rawValue: { type: 'finish', reason: 'stop' }, }, { type: 'response-metadata', id: 'test-id', modelId: 'test-model', timestamp: new Date(0), }, { type: 'text-start', id: 'text-1' }, { type: 'text-delta', id: 'text-1', delta: 'Hello, world!' }, { type: 'text-end', id: 'text-1' }, { type: 'finish', finishReason: 'stop', usage: testUsage, }, ]), }); const result = await loopFn({ methodType: 'stream', runId, agentId: 'agent-id', models: modelWithRawChunks, messageList, includeRawChunks: true, options: { onChunk(chunk) { onChunkCalls.push(chunk); }, }, }); await result.consumeStream(); expect(onChunkCalls).toMatchInlineSnapshot(` [ { "from": "AGENT", "payload": { "data": "start", "type": "stream-start", }, "runId": "test-run-id", "type": "raw", }, { "from": "AGENT", "payload": { "id": "test-id", "modelId": "test-model", "type": "response-metadata", }, "runId": "test-run-id", "type": "raw", }, { "from": "AGENT", "payload": { "content": "Hello", "type": "text-delta", }, "runId": "test-run-id", "type": "raw", }, { "from": "AGENT", "payload": { "content": ", world!", "type": "text-delta", }, "runId": "test-run-id", "type": "raw", }, { "from": "AGENT", "payload": { "reason": "stop", "type": "finish", }, "runId": "test-run-id", "type": "raw", }, { "from": "AGENT", "payload": { "id": "text-1", "providerMetadata": undefined, "text": "Hello, world!", }, "runId": "test-run-id", "type": "text-delta", }, ] `); }); it('should pass includeRawChunks flag correctly to the model', async () => { const messageList = createMessageListWithUserMessage(); let capturedOptions: any; const models = [ { id: 'test-model', maxRetries: 0, model: new MockLanguageModelV2({ doStream: async options => { capturedOptions = options; return { stream: convertArrayToReadableStream([ { type: 'stream-start', warnings: [] }, { type: 'response-metadata', id: 'test-id', modelId: 'test-model', timestamp: new Date(0), }, { type: 'text-start', id: 'text-1' }, { type: 'text-delta', id: 'text-1', delta: 'Hello' }, { type: 'text-end', id: 'text-1' }, { type: 'finish', finishReason: 'stop', usage: testUsage, }, ]), }; }, }), }, ]; const result = await loopFn({ methodType: 'stream', agentId: 'agent-id', runId, models, messageList, includeRawChunks: true, }); await result.consumeStream(); expect(capturedOptions.includeRawChunks).toBe(true); const result2 = await loopFn({ methodType: 'stream', agentId: 'agent-id', runId, models, messageList, includeRawChunks: false, }); await result2.consumeStream(); expect(capturedOptions.includeRawChunks).toBe(false); const result3 = await loopFn({ methodType: 'stream', agentId: 'agent-id', runId, models, messageList, }); await result3.consumeStream(); expect(capturedOptions.includeRawChunks).toBe(false); }); }); describe('mixed multi content streaming with interleaving parts', () => { describe('mixed text and reasoning blocks', () => { const messageList = createMessageListWithUserMessage(); let result: any; beforeEach(async () => { result = await loopFn({ methodType: 'stream', runId, agentId: 'agent-id', models: createTestModels({ stream: convertArrayToReadableStream([ { type: 'stream-start', warnings: [] }, { type: 'reasoning-start', id: '0' }, { type: 'text-start', id: 'text-1' }, { type: 'reasoning-delta', id: '0', delta: 'Thinking...' }, { type: 'text-delta', id: 'text-1', delta: 'Hello' }, { type: 'text-delta', id: 'text-1', delta: ', ' }, { type: 'text-start', id: 'text-2' }, { type: 'text-delta', id: 'text-2', delta: `This ` }, { type: 'text-delta', id: 'text-2', delta: `is ` }, { type: 'reasoning-start', id: '3' }, { type: 'reasoning-delta', id: '0', delta: `I'm thinking...` }, { type: 'reasoning-delta', id: '3', delta: `Separate thoughts` }, { type: 'text-delta', id: 'text-2', delta: `a` }, { type: 'text-delta', id: 'text-1', delta: `world!` }, { type: 'reasoning-end', id: '0' }, { type: 'text-delta', id: 'text-2', delta: ` test.` }, { type: 'text-end', id: 'text-2' }, { type: 'reasoning-end', id: '3' }, { type: 'text-end', id: 'text-1' }, { type: 'finish', finishReason: 'stop', usage: testUsage, }, ]), }), messageList, _internal: { currentDate: mockValues(new Date(2000)), generateId: mockId(), }, }); }); it('should return the full stream with the correct parts', async () => { expect(stripMastraCreatedAt(await convertAsyncIterableToArray(result.fullStream))).toMatchInlineSnapshot(` [ { "from": "AGENT", "payload": { "id": "agent-id", "messageId": "id-0", }, "runId": "test-run-id", "type": "start", }, { "from": "AGENT", "payload": { "messageId": "id-0", "modelId": "mock-model-id", "provider": "mock-provider", "request": {}, "warnings": [], }, "runId": "test-run-id", "type": "step-start", }, { "from": "AGENT", "payload": { "id": "0", "providerMetadata": undefined, }, "runId": "test-run-id", "type": "reasoning-start", }, { "from": "AGENT", "payload": { "id": "text-1", "providerMetadata": undefined, }, "runId": "test-run-id", "type": "text-start", }, { "from": "AGENT", "payload": { "id": "0", "providerMetadata": undefined, "text": "Thinking...", }, "runId": "test-run-id", "type": "reasoning-delta", }, { "from": "AGENT", "payload": { "id": "text-1", "providerMetadata": undefined, "text": "Hello", }, "runId": "test-run-id", "type": "text-delta", }, { "from": "AGENT", "payload": { "id": "text-1", "providerMetadata": undefined, "text": ", ", }, "runId": "test-run-id", "type": "text-delta", }, { "from": "AGENT", "payload": { "id": "text-2", "providerMetadata": undefined, }, "runId": "test-run-id", "type": "text-start", }, { "from": "AGENT", "payload": { "id": "text-2", "providerMetadata": undefined, "text": "This ", }, "runId": "test-run-id", "type": "text-delta", }, { "from": "AGENT", "payload": { "id": "text-2", "providerMetadata": undefined, "text": "is ", }, "runId": "test-run-id", "type": "text-delta", }, { "from": "AGENT", "payload": { "id": "3", "providerMetadata": undefined, }, "runId": "test-run-id", "type": "reasoning-start", }, { "from": "AGENT", "payload": { "id": "0", "providerMetadata": undefined, "text": "I'm thinking...", }, "runId": "test-run-id", "type": "reasoning-delta", }, { "from": "AGENT", "payload": { "id": "3", "providerMetadata": undefined, "text": "Separate thoughts", }, "runId": "test-run-id", "type": "reasoning-delta", }, { "from": "AGENT", "payload": { "id": "text-2", "providerMetadata": undefined, "text": "a", }, "runId": "test-run-id", "type": "text-delta", }, { "from": "AGENT", "payload": { "id": "text-1", "providerMetadata": undefined, "text": "world!", }, "runId": "test-run-id", "type": "text-delta", }, { "from": "AGENT", "payload": { "id": "0", "providerMetadata": undefined, }, "runId": "test-run-id", "type": "reasoning-end", }, { "from": "AGENT", "payload": { "id": "text-2", "providerMetadata": undefined, "text": " test.", }, "runId": "test-run-id", "type": "text-delta", }, { "from": "AGENT", "payload": { "id": "text-2", "type": "text-end", }, "runId": "test-run-id", "type": "text-end", }, { "from": "AGENT", "payload": { "id": "3", "providerMetadata": undefined, }, "runId": "test-run-id", "type": "reasoning-end", }, { "from": "AGENT", "payload": { "id": "text-1", "type": "text-end", }, "runId": "test-run-id", "type": "text-end", }, { "from": "AGENT", "payload": { "messageId": "id-0", "messages": { "all": [ { "content": [ { "text": "test-input", "type": "text", }, ], "role": "user", }, { "content": [ { "text": "Thinking...I'm thinking...", "type": "reasoning", }, { "text": "Hello, world!", "type": "text", }, { "text": "This is a test.", "type": "text", }, { "text": "Separate thoughts", "type": "reasoning", }, ], "role": "assistant", }, ], "nonUser": [ { "content": [ { "text": "Thinking...I'm thinking...", "type": "reasoning", }, { "text": "Hello, world!", "type": "text", }, { "text": "This is a test.", "type": "text", }, { "text": "Separate thoughts", "type": "reasoning", }, ], "role": "assistant", }, ], "user": [ { "content": [ { "text": "test-input", "type": "text", }, ], "role": "user", }, ], }, "metadata": { "headers": undefined, "id": "id-1", "modelId": "mock-model-id", "modelMetadata": { "modelId": "mock-model-id", "modelProvider": "mock-provider", "modelVersion": "v2", }, "modelProvider": "mock-provider", "modelVersion": "v2", "providerMetadata": undefined, "request": {}, "timestamp": 1970-01-01T00:00:02.000Z, }, "output": { "steps": [ { "content": [ { "text": "Thinking...I'm thinking...", "type": "reasoning", }, { "text": "Hello, world!", "type": "text", }, { "text": "This is a test.", "type": "text", }, { "text": "Separate thoughts", "type": "reasoning", }, ], "finishReason": undefined, "providerMetadata": undefined, "request": {}, "response": { "headers": undefined, "id": "id-1", "messages": [ { "content": [ { "text": "Thinking...I'm thinking...", "type": "reasoning", }, { "text": "Hello, world!", "type": "text", }, { "text": "This is a test.", "type": "text", }, { "text": "Separate thoughts", "type": "reasoning", }, ], "role": "assistant", }, ], "modelId": "mock-model-id", "modelProvider": "mock-provider", "modelVersion": "v2", "timestamp": 1970-01-01T00:00:02.000Z, }, "tripwire": undefined, "usage": { "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": undefined, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": undefined, "totalTokens": 13, }, "totalTokens": 13, }, "warnings": [], }, ], "text": "Hello, This is aworld! test.", "toolCalls": [], "usage": { "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": undefined, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": undefined, "totalTokens": 13, }, "totalTokens": 13, }, }, "processorRetryCount": 0, "processorRetryFeedback": undefined, "stepResult": { "isContinued": false, "reason": "stop", "warnings": [], }, }, "runId": "test-run-id", "type": "step-finish", }, { "from": "AGENT", "payload": { "messageId": "id-0", "messages": { "all": [ { "content": [ { "text": "test-input", "type": "text", }, ], "role": "user", }, { "content": [ { "text": "Thinking...I'm thinking...", "type": "reasoning", }, { "text": "Hello, world!", "type": "text", }, { "text": "This is a test.", "type": "text", }, { "text": "Separate thoughts", "type": "reasoning", }, ], "role": "assistant", }, ], "nonUser": [ { "content": [ { "text": "Thinking...I'm thinking...", "type": "reasoning", }, { "text": "Hello, world!", "type": "text", }, { "text": "This is a test.", "type": "text", }, { "text": "Separate thoughts", "type": "reasoning", }, ], "role": "assistant", }, ], "user": [ { "content": [ { "text": "test-input", "type": "text", }, ], "role": "user", }, ], }, "metadata": { "headers": undefined, "id": "id-1", "modelId": "mock-model-id", "modelMetadata": { "modelId": "mock-model-id", "modelProvider": "mock-provider", "modelVersion": "v2", }, "modelProvider": "mock-provider", "modelVersion": "v2", "providerMetadata": undefined, "request": {}, "timestamp": 1970-01-01T00:00:02.000Z, }, "output": { "steps": [ { "content": [ { "text": "Thinking...I'm thinking...", "type": "reasoning", }, { "text": "Hello, world!", "type": "text", }, { "text": "This is a test.", "type": "text", }, { "text": "Separate thoughts", "type": "reasoning", }, ], "finishReason": undefined, "providerMetadata": undefined, "request": {}, "response": { "headers": undefined, "id": "id-1", "messages": [ { "content": [ { "text": "Thinking...I'm thinking...", "type": "reasoning", }, { "text": "Hello, world!", "type": "text", }, { "text": "This is a test.", "type": "text", }, { "text": "Separate thoughts", "type": "reasoning", }, ], "role": "assistant", }, ], "modelId": "mock-model-id", "modelProvider": "mock-provider", "modelVersion": "v2", "timestamp": 1970-01-01T00:00:02.000Z, }, "tripwire": undefined, "usage": { "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": undefined, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": undefined, "totalTokens": 13, }, "totalTokens": 13, }, "warnings": [], }, ], "text": "Hello, This is aworld! test.", "toolCalls": [], "usage": { "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": undefined, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": undefined, "totalTokens": 13, }, "totalTokens": 13, }, }, "processorRetryCount": 0, "processorRetryFeedback": undefined, "stepResult": { "isContinued": false, "reason": "stop", "warnings": [], }, "stopCause": "model_finished", }, "runId": "test-run-id", "type": "finish", }, ] `); }); }); }); describe('abort signal', () => { describe('basic abort', () => { let result: any; let onAbortCalls: Array<{ steps: any[]; text?: string }> = []; beforeEach(async () => { const messageList = createMessageListWithUserMessage(); onAbortCalls = []; const abortController = new AbortController(); let pullCalls = 0; result = await loopFn({ methodType: 'stream', runId, agentId: 'agent-id', options: { abortSignal: abortController.signal, onAbort: event => { onAbortCalls.push(event); }, }, models: [ { id: 'test-model', maxRetries: 0, model: new MockLanguageModelV2({ doStream: async () => ({ stream: new ReadableStream({ async pull(controller) { await new Promise(resolve => setTimeout(resolve, 0)); switch (pullCalls++) { case 0: controller.enqueue({ type: 'stream-start', warnings: [], }); break; case 1: controller.enqueue({ type: 'text-start', id: '1', }); break; case 2: controller.enqueue({ type: 'text-delta', id: '1', delta: 'Hello', }); break; case 3: abortController.abort(); controller.error(new DOMException('The user aborted a request.', 'AbortError')); break; } }, }), }), }), }, ], messageList, _internal: { generateId: mockId({ prefix: 'id' }), }, }); }); it('should only stream initial chunks in full stream', async () => { expect(await convertAsyncIterableToArray(result.fullStream)).toMatchInlineSnapshot(` [ { "from": "AGENT", "payload": { "id": "agent-id", "messageId": "id-0", }, "runId": "test-run-id", "type": "start", }, { "from": "AGENT", "payload": { "messageId": "id-0", "modelId": "mock-model-id", "provider": "mock-provider", "request": {}, "startedAt": 1704067200000, "warnings": [], }, "runId": "test-run-id", "type": "step-start", }, { "from": "AGENT", "payload": { "id": "id-2", "providerMetadata": undefined, }, "runId": "test-run-id", "type": "text-start", }, { "from": "AGENT", "payload": { "id": "id-2", "providerMetadata": undefined, "text": "Hello", }, "runId": "test-run-id", "type": "text-delta", }, { "from": "AGENT", "payload": {}, "runId": "test-run-id", "type": "abort", }, { "from": "AGENT", "payload": { "messageId": "id-0", "messages": { "all": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "test-input", "type": "text", }, ], "role": "user", }, ], "nonUser": [], "user": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "test-input", "type": "text", }, ], "role": "user", }, ], }, "metadata": { "headers": undefined, "id": "id-1", "modelId": "mock-model-id", "modelMetadata": { "modelId": "mock-model-id", "modelProvider": "mock-provider", "modelVersion": "v2", }, "modelProvider": "mock-provider", "modelVersion": "v2", "providerMetadata": undefined, "request": {}, "timestamp": 2024-01-01T00:00:00.000Z, }, "output": { "steps": [], "text": "Hello", "toolCalls": [], "usage": { "inputTokens": undefined, "outputTokens": undefined, "totalTokens": undefined, }, }, "stepResult": { "isContinued": false, "reason": "abort", "warnings": undefined, }, }, "runId": "test-run-id", "type": "finish", }, ] `); }); }); describe('abort in 2nd step', () => { let result: any; let onAbortCalls: Array<{ steps: any[]; text?: string }> = []; beforeEach(async () => { onAbortCalls = []; const abortController = new AbortController(); let pullCalls = 0; let streamCalls = 0; result = loopFn({ methodType: 'stream', runId, messageList: createMessageListWithUserMessage(), models: [ { id: 'test-model', maxRetries: 0, model: new MockLanguageModelV2({ doStream: async () => ({ stream: new ReadableStream({ start() { streamCalls++; pullCalls = 0; }, pull: async function (controller) { if (streamCalls === 1) { switch (pullCalls++) { case 0: controller.enqueue({ type: 'stream-start', warnings: [], }); break; case 1: controller.enqueue({ type: 'tool-call', toolCallId: 'call-1', toolName: 'tool1', input: `{ "value": "value" }`, }); break; case 2: controller.enqueue({ type: 'finish', finishReason: 'tool-calls', usage: testUsage, }); controller.close(); break; } } else { await new Promise(resolve => setTimeout(resolve, 0)); switch (pullCalls++) { case 0: controller.enqueue({ type: 'stream-start', warnings: [], }); break; case 1: controller.enqueue({ type: 'text-start', id: '1', }); break; case 2: controller.enqueue({ type: 'text-delta', id: '1', delta: 'Hello', }); break; case 3: abortController.abort(); controller.error(new DOMException('The user aborted a request.', 'AbortError')); break; } } }, }), }), }), }, ], tools: { tool1: { inputSchema: z.object({ value: z.string() }), execute: async () => 'result1', }, }, stopWhen: stepCountIs(3), ...defaultSettings(), options: { abortSignal: abortController.signal, onAbort: event => { onAbortCalls.push(event); }, }, }); }); it('should only stream initial chunks in full stream', async () => { expect(await convertAsyncIterableToArray(result.fullStream)).toMatchInlineSnapshot(` [ { "from": "AGENT", "payload": { "id": "agent-id", "messageId": "msg-0", }, "runId": "test-run-id", "type": "start", }, { "from": "AGENT", "payload": { "messageId": "msg-0", "modelId": "mock-model-id", "provider": "mock-provider", "request": {}, "startedAt": 1704067200000, "warnings": [], }, "runId": "test-run-id", "type": "step-start", }, { "from": "AGENT", "payload": { "args": { "value": "value", }, "providerExecuted": undefined, "providerMetadata": undefined, "toolCallId": "call-1", "toolName": "tool1", }, "runId": "test-run-id", "type": "tool-call", }, { "from": "AGENT", "payload": { "args": { "value": "value", }, "providerExecuted": undefined, "providerMetadata": undefined, "result": "result1", "toolCallId": "call-1", "toolName": "tool1", }, "runId": "test-run-id", "type": "tool-result", }, { "from": "AGENT", "payload": { "messageId": "msg-0", "messages": { "all": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "test-input", "type": "text", }, ], "role": "user", }, { "content": [ { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, ], "nonUser": [ { "content": [ { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, ], "user": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "test-input", "type": "text", }, ], "role": "user", }, ], }, "metadata": { "headers": undefined, "id": "id-0", "modelId": "mock-model-id", "modelMetadata": { "modelId": "mock-model-id", "modelProvider": "mock-provider", "modelVersion": "v2", }, "modelProvider": "mock-provider", "modelVersion": "v2", "providerMetadata": undefined, "request": {}, "timestamp": 1970-01-01T00:00:00.000Z, }, "output": { "steps": [ DefaultStepResult { "content": [ { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "finishReason": undefined, "providerMetadata": undefined, "request": {}, "response": { "headers": undefined, "id": "id-0", "messages": [ { "content": [ { "input": { "value": "value", }, "providerExecuted": undefined, "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [], "role": "tool", }, ], "modelId": "mock-model-id", "modelProvider": "mock-provider", "modelVersion": "v2", "timestamp": 1970-01-01T00:00:00.000Z, }, "tripwire": undefined, "usage": { "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": undefined, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": undefined, "totalTokens": 13, }, "totalTokens": 13, }, "warnings": [], }, ], "text": "", "toolCalls": [ { "args": { "value": "value", }, "providerExecuted": undefined, "providerMetadata": undefined, "toolCallId": "call-1", "toolName": "tool1", }, ], "usage": { "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": undefined, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": undefined, "totalTokens": 13, }, "totalTokens": 13, }, }, "processorRetryCount": 0, "processorRetryFeedback": undefined, "stepResult": { "isContinued": true, "reason": "tool-calls", "warnings": undefined, }, }, "runId": "test-run-id", "type": "step-finish", }, { "from": "AGENT", "payload": { "messageId": "msg-0", "modelId": "mock-model-id", "provider": "mock-provider", "request": {}, "startedAt": 1704067200000, "warnings": [], }, "runId": "test-run-id", "type": "step-start", }, { "from": "AGENT", "payload": { "id": "id-2", "providerMetadata": undefined, }, "runId": "test-run-id", "type": "text-start", }, { "from": "AGENT", "payload": { "id": "id-2", "providerMetadata": undefined, "text": "Hello", }, "runId": "test-run-id", "type": "text-delta", }, { "from": "AGENT", "payload": {}, "runId": "test-run-id", "type": "abort", }, { "from": "AGENT", "payload": { "messageId": "msg-0", "messages": { "all": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "test-input", "type": "text", }, ], "role": "user", }, { "content": [ { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, ], "nonUser": [ { "content": [ { "input": { "value": "value", }, "providerExecuted": undefined, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-call", }, ], "role": "assistant", }, { "content": [ { "input": { "value": "value", }, "output": { "type": "text", "value": "result1", }, "toolCallId": "call-1", "toolName": "tool1", "type": "tool-result", }, ], "role": "tool", }, ], "user": [ { "content": [ { "providerOptions": { "mastra": { "createdAt": 1704067200000, }, }, "text": "test-input", "type": "text", }, ], "role": "user", }, ], }, "metadata": { "headers": undefined, "id": "id-1", "modelId": "mock-model-id", "modelMetadata": { "modelId": "mock-model-id", "modelProvider": "mock-provider", "modelVersion": "v2", }, "modelProvider": "mock-provider", "modelVersion": "v2", "providerMetadata": undefined, "request": {}, "timestamp": 1970-01-01T00:00:00.000Z, }, "output": { "steps": [], "text": "Hello", "toolCalls": [], "usage": { "inputTokens": 3, "outputTokens": 10, "raw": { "cachedInputTokens": undefined, "inputTokens": 3, "outputTokens": 10, "reasoningTokens": undefined, "totalTokens": 13, }, "totalTokens": 13, }, }, "stepResult": { "isContinued": false, "reason": "abort", "warnings": undefined, }, }, "runId": "test-run-id", "type": "finish", }, ] `); }); }); }); }