@mastra/core
Version:
409 lines • 18.1 kB
TypeScript
import { ReadableStream } from 'node:stream/web';
import type { StepResult } from '../../_types/@internal_ai-sdk-v5@0.0.98/dist/index.js';
import type { MessageList, MastraDBMessage } from '../../agent/message-list/index.js';
import { MastraBase } from '../../base.js';
import type { ScorerRunInputForAgent, ScorerRunOutputForAgent } from '../../evals/index.js';
import { ProcessorRunner } from '../../processors/runner.js';
import type { WorkflowRunStatus } from '../../workflows/index.js';
import type { ConsumeStreamOptions } from '../aisdk/v5/compat/index.js';
import type { ChunkType, LanguageModelUsage, LLMStepResult, MastraModelOutputOptions, ProviderMetadata, StreamTransport, StepTripwireData, ToolCallChunk } from '../types.js';
/**
* Helper function to create a destructurable version of MastraModelOutput.
* This wraps the output to ensure properties maintain their context when destructured.
*/
export declare function createDestructurableOutput<OUTPUT = undefined>(output: MastraModelOutput<OUTPUT>): MastraModelOutput<OUTPUT>;
/**
* Persist a non-transient `data-*` chunk emitted by an output processor's
* `writer.custom()` onto the assistant message, so the chunk survives in
* thread history instead of being stream-only (#19375). Transient chunks
* and non-data chunks are left untouched.
*
* Exported for the durable engine, whose producer-side processor writers
* persist into the workflow-side MessageList (the one serialized into
* `messageListState` and flushed to memory at finalize).
*/
export declare function persistProcessorDataChunk(messageList: MessageList, messageId: string, chunk: {
type: string;
data?: unknown;
id?: string;
transient?: boolean;
}): void;
type ToolCallStreamingMeta = {
toolName: string;
providerExecuted?: boolean;
providerMetadata?: ProviderMetadata;
dynamic?: boolean;
title?: string;
observability?: ToolCallChunk['payload']['observability'];
};
type PromiseResults<OUTPUT = undefined> = Pick<LLMStepResult<OUTPUT>, 'text' | 'reasoning' | 'sources' | 'files' | 'toolCalls' | 'toolResults' | 'content' | 'usage' | 'warnings' | 'providerMetadata' | 'response' | 'request'> & {
suspendPayload: any;
resumeSchema: any;
object: OUTPUT;
reasoningText: string | undefined;
totalUsage: LLMStepResult<OUTPUT>['usage'];
steps: LLMStepResult<OUTPUT>[];
finishReason: LLMStepResult<OUTPUT>['finishReason'];
};
/**
* The complete output returned by `getFullOutput()`.
*/
export type FullOutput<OUTPUT = undefined> = {
/** The text output from all steps, excluding rejected responses */
text: string;
/** Token usage for the last step */
usage: PromiseResults<OUTPUT>['usage'];
/** All LLM steps executed during the stream */
steps: LLMStepResult<OUTPUT>[];
/** The reason the stream finished */
finishReason: PromiseResults<OUTPUT>['finishReason'];
/** Any warnings from the model */
warnings: PromiseResults<OUTPUT>['warnings'];
/** Provider-specific metadata */
providerMetadata: PromiseResults<OUTPUT>['providerMetadata'];
/** The request that was sent to model */
request: PromiseResults<OUTPUT>['request'];
/** Reasoning details from the model */
reasoning: PromiseResults<OUTPUT>['reasoning'];
/** Combined reasoning text */
reasoningText: string | undefined;
/** Tool calls made during execution */
toolCalls: PromiseResults<OUTPUT>['toolCalls'];
/** Results from tool executions */
toolResults: PromiseResults<OUTPUT>['toolResults'];
/** Sources referenced by model */
sources: PromiseResults<OUTPUT>['sources'];
/** Files generated by the model */
files: PromiseResults<OUTPUT>['files'];
/** Response metadata from the model */
response: PromiseResults<OUTPUT>['response'];
/** Total token usage across all steps */
totalUsage: PromiseResults<OUTPUT>['totalUsage'];
/** The structured object output (when using structured output) */
object: OUTPUT;
/**
* True when `object` is the configured `fallbackValue`, substituted because the model
* output failed schema validation — or the separate structuring model failed — under
* `errorStrategy: 'fallback'`.
*/
usedFallbackValue: boolean;
/** Error if the stream failed */
error: Error | undefined;
/** Tripwire data if content was blocked */
tripwire: StepTripwireData | undefined;
/** Scoring data for evals (when returnScorerData is enabled) */
scoringData?: {
input: Omit<ScorerRunInputForAgent, 'runId'>;
output: ScorerRunOutputForAgent;
};
/** Trace ID for this execution. */
traceId: string | undefined;
/** Root span ID for this execution, identifying the top-level span in the trace. */
spanId: string | undefined;
/** Run ID for this execution */
runId: string | undefined;
/** Payload for resuming suspended tool calls */
suspendPayload: any;
/** Resume schema of suspended step if available */
resumeSchema?: any;
/** All messages from this execution (input + memory history + response) */
messages: MastraDBMessage[];
/** Only messages loaded from memory (conversation history) */
rememberedMessages: MastraDBMessage[];
};
/**
* Resolve the output text from the latest response message, skipping internal
* completion-check feedback so it can't become the final text.
* The completionResult metadata only exists on DB-format messages, and the
* message is converted alone so adjacent assistant messages aren't merged.
*
* Converting to model messages splits an assistant message at every tool
* result, so when the current loop iteration called a tool the last converted
* message holds only the text after the call, or nothing if the step ended on
* it. In that case the text is read from the DB message's parts after the
* iteration's boundary instead. The last `step-start` is not that boundary:
* one is also inserted inside a single response whenever text follows a tool call.
*
* Returns `undefined` only when there is no response message to read text from,
* so callers can distinguish "no processed output exists" from an output
* processor deliberately clearing the text to `''`. Never collapse the two with
* a truthiness check: a redacting processor must be able to produce empty text.
*/
export declare function resolveOutputMessageSkippingCompletionChecks(messageList: MessageList): MastraDBMessage | undefined;
/**
* A failed completion check moves the answer to a new message, but this output keeps the id it
* was built with. Resolve at write time so processor data lands on the answer that is returned.
*/
export declare function resolveProcessorWriterMessageId(messageList: MessageList, fallbackMessageId: string, explicitMessageId?: string): string;
export declare class MastraModelOutput<OUTPUT = undefined> extends MastraBase {
/**
* Unique identifier for this execution run.
*/
runId: string;
/**
* The processor runner for this stream.
*/
processorRunner?: ProcessorRunner;
/**
* The message list for this stream.
*/
messageList: MessageList;
/**
* Trace ID for this execution.
*/
traceId?: string;
/**
* Root span ID for this execution, identifying the top-level span in the trace.
*/
spanId?: string;
messageId: string;
constructor({ model: _model, stream, messageList, options, messageId, initialState, initialToolCalls, resumedText, finishUsageIsTotal, onFinishComplete, getTerminalRequest, onTracingTripwire, }: {
model: {
modelId: string | undefined;
provider: string | undefined;
version: 'v2' | 'v3' | 'v4';
};
stream: ReadableStream<ChunkType<OUTPUT>>;
messageList: MessageList;
options: MastraModelOutputOptions<OUTPUT>;
messageId: string;
initialState?: any;
initialToolCalls?: ToolCallChunk[];
/**
* Text a resumed stream segment inherits from before its suspension: the run's text so far
* and the suspended step's part of it. Used when no serialized `initialState` is available.
*/
resumedText?: {
priorText: string;
stepText: string;
};
finishUsageIsTotal?: boolean;
/** @internal Successful loop cleanup, after the agent's awaited final memory save. */
onFinishComplete?: () => Promise<void>;
/** @internal Caller-local terminal metadata, taking precedence over queued step chunks. */
getTerminalRequest?: () => LLMStepResult<OUTPUT>['request'] | undefined;
/** Internal tracing state, never serialized into finish chunks. */
onTracingTripwire?: import('../../loop/types').LoopOptions['onTracingTripwire'];
});
private resolvePromise;
private resolvePromises;
/**
* Resolves to the complete text response after streaming completes.
*/
get text(): Promise<string>;
/**
* Resolves to reasoning parts array for models that support reasoning.
*/
get reasoning(): Promise<import("..").ReasoningChunk[]>;
/**
* Resolves to complete reasoning text for models that support reasoning.
*/
get reasoningText(): Promise<string | undefined>;
get sources(): Promise<import("..").SourceChunk[]>;
get files(): Promise<import("..").FileChunk[]>;
get steps(): Promise<LLMStepResult<OUTPUT>[]>;
get suspendPayload(): Promise<any>;
get resumeSchema(): Promise<any>;
/**
* Stream of all chunks. Provides complete control over stream processing.
*/
get fullStream(): ReadableStream<ChunkType<OUTPUT>>;
/** @internal Shared fanout must retain signal chunks, with the existing transforms applied. */
__getUnfilteredFullStream(): ReadableStream<ChunkType<OUTPUT>>;
/**
* Resolves to the reason generation finished.
*/
get finishReason(): Promise<string | undefined>;
/**
* Resolves to array of all tool calls made during execution.
*/
get toolCalls(): Promise<ToolCallChunk[]>;
/**
* Resolves to array of all tool execution results.
*/
get toolResults(): Promise<import("..").ToolResultChunk[]>;
/**
* Resolves to token usage statistics including inputTokens, outputTokens, and totalTokens.
*/
get usage(): Promise<LanguageModelUsage>;
/**
* Resolves to array of all warnings generated during execution.
*/
get warnings(): Promise<import("../../_types/@ai-sdk_provider@2.0.5/dist/index.js").LanguageModelV2CallWarning[]>;
/**
* Resolves to provider metadata generated during execution.
*/
get providerMetadata(): Promise<ProviderMetadata | undefined>;
/**
* Resolves to the complete response from the model.
*/
get response(): Promise<{
[]: unknown;
headers?: Record<string, string>;
messages?: StepResult<import("../../_types/@internal_ai-sdk-v5@0.0.98/dist/index.js").ToolSet>['response']['messages'];
dbMessages?: MastraDBMessage[];
uiMessages?: import("../../_types/@internal_ai-sdk-v5@0.0.98/dist/index.js").UIMessage<[OUTPUT] extends [undefined] ? undefined : {
structuredOutput?: OUTPUT | undefined;
} & Record<string, unknown>, import("../../_types/@internal_ai-sdk-v5@0.0.98/dist/index.js").UIDataTypes, import("../../_types/@internal_ai-sdk-v5@0.0.98/dist/index.js").UITools>[] | undefined;
id?: string;
timestamp?: Date;
modelId?: string;
}>;
/**
* Resolves to the complete request sent to the model.
*/
get request(): Promise<{
body?: unknown;
}>;
/**
* Transport handle for the current stream (when available).
*/
get transport(): StreamTransport | undefined;
/**
* Resolves to an error if an error occurred during streaming.
*/
get error(): Error | undefined;
updateUsageCount(usage: Partial<LanguageModelUsage>): void;
populateUsageCount(usage: Partial<LanguageModelUsage>): void;
consumeStream(options?: ConsumeStreamOptions): Promise<void>;
/**
* Returns complete output including text, usage, tool calls, and all metadata.
*/
getFullOutput(): Promise<FullOutput<OUTPUT>>;
/**
* Tripwire data if the stream was aborted due to an output processor blocking the content.
* Returns undefined if no tripwire was triggered.
*/
get tripwire(): StepTripwireData | undefined;
/**
* The total usage of the stream.
*/
get totalUsage(): Promise<LanguageModelUsage>;
get content(): Promise<LLMStepResult['content']>;
/**
* Stream of valid JSON chunks. The final JSON result is validated against the output schema when the stream ends.
*
* @example
* ```typescript
* const stream = await agent.stream("Extract data", {
* structuredOutput: {
* schema: z.object({ name: z.string(), age: z.number() }),
* model: 'gpt-4o-mini' // optional to use a model for structuring json output
* }
* });
* // partial json chunks
* for await (const data of stream.objectStream) {
* console.log(data); // { name: 'John' }, { name: 'John', age: 30 }
* }
* ```
*/
get objectStream(): ReadableStream<Partial<OUTPUT>>;
/**
* Stream of individual array elements when output schema is an array type.
*/
get elementStream(): ReadableStream<OUTPUT extends Array<infer T> ? T : never>;
/**
* Stream of only text content, filtering out metadata and other chunk types.
*/
get textStream(): ReadableStream<string>;
/**
* Resolves to the complete object response from the model. Validated against the 'output' schema when the stream ends.
*
* @example
* ```typescript
* const stream = await agent.stream("Extract data", {
* structuredOutput: {
* schema: z.object({ name: z.string(), age: z.number() }),
* model: 'gpt-4o-mini' // optionally use a model for structuring json output
* }
* });
* // final validated json
* const data = await stream.object // { name: 'John', age: 30 }
* ```
*/
get object(): Promise<OUTPUT>;
/** @internal */
_getImmediateToolCalls(): ToolCallChunk[];
/** @internal */
_getImmediateToolResults(): import("..").ToolResultChunk[];
/** @internal */
_getImmediateText(): string;
/** @internal */
_getImmediateObject(): OUTPUT | undefined;
/**
* Whether the structured object is the configured `fallbackValue`, substituted because
* the model output failed schema validation — or the separate structuring model failed —
* under `errorStrategy: 'fallback'`.
*
* Starts `false` and reflects the most recently processed object. On a live stream, await
* `stream.object` or `stream.getFullOutput()` before reading it.
*/
get usedFallbackValue(): boolean;
/** @internal */
_getImmediateUsage(): LanguageModelUsage;
/** @internal */
_getImmediateWarnings(): import("../../_types/@ai-sdk_provider@2.0.5/dist/index.js").LanguageModelV2CallWarning[];
/** @internal */
_getImmediateFinishReason(): string | undefined;
/** @internal */
_getImmediateProviderMetadata(): ProviderMetadata | undefined;
/** @internal */
_getBaseStream(): ReadableStream<ChunkType<OUTPUT>>;
/** @internal */
_waitUntilFinished(): Promise<void>;
get status(): WorkflowRunStatus;
/**
* @param pendingSuspension A suspension chunk the step has emitted but this output may not have
* processed yet. Tool suspension snapshots the stream state right after emitting the chunk, so
* the state is serialized as if the chunk was processed; otherwise a resumed run would not know
* which usage its suspended leg already reported.
*/
serializeState(pendingSuspension?: {
usage?: LanguageModelUsage;
}): {
status: WorkflowRunStatus;
bufferedSteps: LLMStepResult<OUTPUT>[];
bufferedStepRequests: unknown[] | undefined;
bufferedReasoningDetails: Record<string, import("..").ReasoningChunk>;
bufferedByStepReasoningDetails: Record<string, import("..").ReasoningChunk>;
bufferedByStep: LLMStepResult<OUTPUT>;
bufferedText: string[];
bufferedTextAtStepStart: number;
bufferedTextChunks: Record<string, string[]>;
bufferedSources: import("..").SourceChunk[];
bufferedReasoning: import("..").ReasoningChunk[];
bufferedFiles: import("..").FileChunk[];
toolCallArgsDeltas: Record<string, string[]>;
toolCallDeltaIdNameMap: Record<string, string>;
toolCallStreamingMeta: Record<string, ToolCallStreamingMeta>;
pendingToolCalls: Record<string, {
meta: ToolCallStreamingMeta;
args: Record<string, unknown>;
streamed: boolean;
runId: string;
from: ToolCallChunk['from'];
}>;
replaceableToolCallIds: string[];
attemptToolCallIds: string[];
toolCalls: ToolCallChunk[];
toolResults: import("..").ToolResultChunk[];
warnings: import("../../_types/@ai-sdk_provider@2.0.5/dist/index.js").LanguageModelV2CallWarning[];
finishReason: string | undefined;
request: {
body?: unknown;
};
usageCount: LanguageModelUsage;
usageCountMissing: ("inputTokens" | "outputTokens" | "totalTokens")[];
lastStepUsage: LanguageModelUsage | undefined;
suspendedStepUsage: LanguageModelUsage | undefined;
generationReportedUsage: LanguageModelUsage | undefined;
generationReportedStepCount: number;
tripwire: StepTripwireData | undefined;
wasSuspended: boolean;
messageList: import("../../agent/message-list/state").SerializedMessageListState;
};
deserializeState(state: any): void;
}
export {};
//# sourceMappingURL=output.d.ts.map