UNPKG

@mastra/core

Version:
581 lines • 27.3 kB
import type { LanguageModelV2Prompt } from '../../_types/@ai-sdk_provider@2.0.5/dist/index.js'; import type { LanguageModelV1Prompt, CoreMessage as CoreMessageV4 } from '../../_types/@internal_ai-sdk-v4@0.0.98/dist/index.js'; import type * as AIV4Type from '../../_types/@internal_ai-sdk-v4@0.0.98/dist/index.js'; import type { IMastraLogger } from '../../logger/index.js'; import type { AnySpan } from '../../observability/types/index.js'; import type { IdGeneratorContext } from '../../types/index.js'; import type { CreatedAgentSignal } from '../signals.js'; import type { StoredMessageLoader } from './memory-message-refs.js'; import type { MastraDBMessage, MastraMessagePart, MastraStepStartPart, MastraMessageV1, MessageSource, UIMessageWithMetadata, SerializedMessageListState } from './state/index.js'; import type { AIV5Type, AIV5ResponseMessage, AIV6Type, MessageListInput } from './types.js'; type MessageListAddOptions = { merge?: boolean; }; export declare class MessageList { #private; private messages; private messageIndex?; private systemMessages; private taggedSystemMessages; private memoryInfo; private stateManager; private get memoryMessages(); private get newUserMessages(); private get newResponseMessages(); private get userContextMessages(); private get memoryMessagesPersisted(); private get newUserMessagesPersisted(); private get newResponseMessagesPersisted(); private get userContextMessagesPersisted(); private assetDownloads; private unavailableAttachmentUpdates; private generateMessageId?; private _agentNetworkAppend; private filterIncompleteToolCalls; private logger?; private responseMessageSplits; private toAIV5UIMessages; private toAIV4UIMessages; private toAIV6UIMessages; private isRecording; private spanRecordings; private recordedEvents; constructor({ threadId, resourceId, generateMessageId, logger, filterIncompleteToolCalls, _agentNetworkAppend, }?: { threadId?: string; resourceId?: string; generateMessageId?: (context?: IdGeneratorContext) => string; logger?: IMastraLogger; filterIncompleteToolCalls?: boolean; }); /** * Start recording mutations to the MessageList for observability/tracing. * A span scopes recording to that async context, allowing parallel processors. */ startRecording(span?: AnySpan): void; hasRecordedEvents(): boolean; getRecordedEvents(): Array<{ type: 'add' | 'addSystem' | 'removeByIds' | 'clear'; source?: MessageSource; count?: number; ids?: string[]; text?: string; tag?: string; message?: CoreMessageV4; }>; /** * Stop recording and return the list of recorded events */ stopRecording(span?: AnySpan): Array<{ type: 'add' | 'addSystem' | 'removeByIds' | 'clear'; source?: MessageSource; count?: number; ids?: string[]; text?: string; tag?: string; message?: CoreMessageV4; }>; private recordMutation; addSignal(signal: CreatedAgentSignal, options?: { source?: MessageSource; }): CreatedAgentSignal; private removeMatchingTransientSignals; add(messages: MessageListInput, messageSource: MessageSource, options?: MessageListAddOptions): this; serialize(): SerializedMessageListState; /** * The run's record of messages already written to the semantic recall index, as * message id -> hash of the embedded text. Returned live: embedding writers add to it after a * successful write and skip messages recorded with the same text. * * @internal */ getEmbeddedMessages(): Map<string, string>; /** * Custom serialization for tracing/observability spans. * Returns a clean representation with just the essential data, * excluding internal state tracking, methods, and implementation details. * * This is automatically called by the span serialization system when * a MessageList instance appears in span input/output/attributes. */ serializeForSpan(): { messages: Array<{ role: string; content: unknown; }>; systemMessages: Array<{ role: string; content: unknown; tag?: string; }>; }; deserialize(state: SerializedMessageListState): this; /** @internal */ clone(): MessageList; /** * Return the transcript view that persistence-oriented output processors should store. * During final output processing, the current loop iteration may temporarily be exposed as a separate response * message so processors can transform it independently. This method coalesces that temporary split while preserving * the original response identity and order. */ cloneForPersistence(): MessageList; /** * Suspended tool calls are dropped from the prompt by default. When the caller opts out * they stay visible, but they are still paired with a pending result — providers reject a * tool call that has no result regardless of what the caller prefers. */ private get promptConversionMode(); /** * Whether tool calls without a result are dropped from the prompt (the default) rather than * paired with a pending placeholder result. Lets prompt-shape-aware processors reason about * what a trailing assistant message will look like once converted. */ get dropsIncompleteToolCalls(): boolean; private getMessagesForModelPrompt; private convertSignalForModelPrompt; makeMessageSourceChecker(): { memory: Set<string>; input: Set<string>; output: Set<string>; context: Set<string>; getSource: (message: MastraDBMessage) => MessageSource | null; }; /** * Ids of every message that entered this list from memory or as input, including messages * later promoted to the response or replaced by a copy with the same id. */ getRememberedAndInputMessageIds(): Set<string>; getLatestUserContent(): string | null; get get(): { all: { db: () => MastraDBMessage[]; v1: () => MastraMessageV1[]; aiV5: { model: () => AIV5Type.ModelMessage[]; ui: () => AIV5Type.UIMessage[]; prompt: () => AIV5Type.ModelMessage[]; llmPrompt: (options?: { downloadConcurrency?: number; downloadRetries?: number; supportedUrls?: Record<string, RegExp[]>; /** * Provider this prompt is being sent to. Lets conversion drop stored * provider-executed tool results a different provider produced. * @see https://github.com/mastra-ai/mastra/issues/23082 */ targetProvider?: string; /** * Replace user attachments that fail to download with a text placeholder * instead of failing the whole prompt, and record them as unavailable. */ skipUnavailableAttachments?: boolean; }) => Promise<LanguageModelV2Prompt>; }; aiV6: { ui: () => AIV6Type.UIMessage<unknown, AIV6Type.UIDataTypes, AIV6Type.UITools>[]; llmPrompt: (options?: { downloadConcurrency?: number; downloadRetries?: number; supportedUrls?: Record<string, RegExp[]>; targetProvider?: string; skipUnavailableAttachments?: boolean; }) => Promise<LanguageModelV2Prompt>; }; aiV7: { ui: () => AIV6Type.UIMessage<unknown, AIV6Type.UIDataTypes, AIV6Type.UITools>[]; llmPrompt: (options?: { downloadConcurrency?: number; downloadRetries?: number; supportedUrls?: Record<string, RegExp[]>; targetProvider?: string; skipUnavailableAttachments?: boolean; }) => Promise<LanguageModelV2Prompt>; }; prompt: () => CoreMessageV4[]; ui: () => UIMessageWithMetadata[]; core: () => CoreMessageV4[]; aiV4: { ui: () => UIMessageWithMetadata[]; core: () => CoreMessageV4[]; prompt: () => CoreMessageV4[]; llmPrompt: () => LanguageModelV1Prompt; }; }; remembered: { db: () => MastraDBMessage[]; v1: () => import("../../memory").MastraMessageV1[]; aiV5: { model: () => AIV5Type.ModelMessage[]; ui: () => AIV5Type.UIMessage[]; }; aiV6: { ui: () => AIV6Type.UIMessage<unknown, AIV6Type.UIDataTypes, AIV6Type.UITools>[]; }; ui: () => UIMessageWithMetadata[]; core: () => CoreMessageV4[]; aiV4: { ui: () => UIMessageWithMetadata[]; core: () => CoreMessageV4[]; }; }; input: { db: () => MastraDBMessage[]; v1: () => import("../../memory").MastraMessageV1[]; aiV5: { model: () => AIV5Type.ModelMessage[]; ui: () => AIV5Type.UIMessage[]; }; aiV6: { ui: () => AIV6Type.UIMessage<unknown, AIV6Type.UIDataTypes, AIV6Type.UITools>[]; }; ui: () => UIMessageWithMetadata[]; core: () => CoreMessageV4[]; aiV4: { ui: () => UIMessageWithMetadata[]; core: () => CoreMessageV4[]; }; }; response: { db: () => MastraDBMessage[]; v1: () => MastraMessageV1[]; aiV5: { ui: () => AIV5Type.UIMessage[]; model: () => AIV5ResponseMessage[]; modelContent: (stepNumber?: number, stepToolCallIds?: string[]) => AIV5Type.StepResult<any>['content']; stepContent: (message?: AIV5Type.ModelMessage) => AIV5Type.StepResult<any>['content']; }; aiV6: { ui: () => AIV6Type.UIMessage<unknown, AIV6Type.UIDataTypes, AIV6Type.UITools>[]; }; aiV4: { ui: () => UIMessageWithMetadata[]; core: () => CoreMessageV4[]; }; }; }; get getPersisted(): { remembered: { db: () => MastraDBMessage[]; v1: () => import("../../memory").MastraMessageV1[]; aiV5: { model: () => AIV5Type.ModelMessage[]; ui: () => AIV5Type.UIMessage[]; }; aiV6: { ui: () => AIV6Type.UIMessage<unknown, AIV6Type.UIDataTypes, AIV6Type.UITools>[]; }; ui: () => UIMessageWithMetadata[]; core: () => CoreMessageV4[]; aiV4: { ui: () => UIMessageWithMetadata[]; core: () => CoreMessageV4[]; }; }; input: { db: () => MastraDBMessage[]; v1: () => MastraMessageV1[]; aiV5: { model: () => AIV5Type.ModelMessage[]; ui: () => AIV5Type.UIMessage[]; }; aiV6: { ui: () => AIV6Type.UIMessage<unknown, AIV6Type.UIDataTypes, AIV6Type.UITools>[]; }; ui: () => UIMessageWithMetadata[]; core: () => CoreMessageV4[]; aiV4: { ui: () => UIMessageWithMetadata[]; core: () => CoreMessageV4[]; }; }; taggedSystemMessages: Record<string, AIV4Type.CoreSystemMessage[]>; response: { db: () => MastraDBMessage[]; aiV5: { model: () => AIV5Type.ModelMessage[]; ui: () => AIV5Type.UIMessage[]; }; aiV6: { ui: () => AIV6Type.UIMessage<unknown, AIV6Type.UIDataTypes, AIV6Type.UITools>[]; }; ui: () => UIMessageWithMetadata[]; aiV4: { ui: () => UIMessageWithMetadata[]; core: () => CoreMessageV4[]; }; }; }; get clear(): { all: { db: () => MastraDBMessage[]; }; input: { db: () => MastraDBMessage[]; }; response: { db: () => MastraDBMessage[]; }; }; /** * Remove messages by ID * @param ids - Array of message IDs to remove * @param options.pruned - The messages are only being dropped from the live context (e.g. after * observational memory has observed them). Response messages removed this way stay part of the * run's response reported by getRunResponseMessages(). * @returns Array of removed messages */ removeByIds(ids: string[], options?: { pruned?: boolean; }): MastraDBMessage[]; /** * Split an accumulated response message so result processors can transform the current loop iteration independently. * The original id stays with the earlier, potentially persisted parts so storage and client updates keep resolving * the same row while processors work with the current iteration under a temporary id. * @internal */ splitResponseMessageAtPartOffset(messageId: string, partOffset: number): { earlierMessageId: string; currentMessageId: string; } | undefined; /** * Restore a split processor view to the accumulated response shape used for persistence. * The original response id belongs to the earlier iteration and remains stable unless the * processor removes that half, in which case the current survivor inherits it. * @internal */ coalesceSplitResponseMessages(earlierMessageId: string, currentMessageId: string): void; /** * Roll a response message back to the boundary the caller's loop iteration opened, discarding * the parts produced by that step while keeping every earlier, completed step intact. * * Used by the processor-retry path: the rejected attempt must not survive into the next * prompt (PR #12799), but the accepted steps before it must. Removing the whole message * instead — as that path used to do — also destroyed the reasoning (`rs_…`) and * tool-invocation (`fc_…`) parts of accepted steps, leaving a persisted assistant message * with an OpenAI text `itemId` and no reasoning item to pair with it, which OpenAI rejects * with a non-retryable 400 on replay (issue #22291). * * The boundary must be the marker handed back by `openStepBoundary()`, not "the last * `step-start` in the message". Markers are also synthesized *within* a single response * whenever a tool call is followed by text, and nothing stored on the part says which writer * produced it, so the last marker is routinely an intra-response one. Anchoring on it splices * below the rejected step and leaves part of the rejected attempt behind — on a first * iteration, which opens no boundary at all, that is the whole bug: a rejected tool call * survives, unexecuted and still carrying its `fc_…` item id. * * Where no boundary can be located — a first iteration, which opens none; a sealed message; or * a marker `findBoundaryIndex` cannot resolve — the message is removed whole. That is not a * claim that no accepted step exists, only that this cannot tell where one ends, and it is the * pre-#12799 behaviour, so the fallback is never worse than the path it replaced. * * Mirrors: `content.content` and `content.toolInvocations` are re-derived below, because * `MessageMerger` keeps both in step with the parts as a turn streams. `content.reasoning` * and `content.experimental_attachments` are deliberately *not* touched: the merger never * writes them (they are set once when a DB message is built from model messages), so they * describe the first chunk of the message — which a rollback that keeps any parts has by * definition kept. `AIV5Adapter` only re-synthesizes a part from either field when no such * part survives, so there is nothing to resurrect today. If the merger is ever changed to * update them per step, as it does `content.content`, they will need the same treatment here. * `content.metadata.structuredOutput` is invalidated for the same reason `content.content` is * re-derived: it is written per step and a retry that emits no object never overwrites it. * * @param messageId - ID of the message to roll back * @param boundary - the marker returned by `openStepBoundary()` for the step being discarded * @returns true if a message was found and rolled back or removed */ rollbackToStepBoundary(messageId: string, boundary?: MastraStepStartPart): boolean; /** * Record the response as it stands now as the end of a completed step. Called by the loop when a * step finishes, before the next one can add to the response. * @internal */ markStepCompleted(): void; /** * A copy of this list holding the input and only the response of completed steps: the parts and * messages a step still in flight added since the last {@link markStepCompleted} are left out. * A step whose tool calls all have results (an aborted call records a notice) counts as completed * even though the loop never reached its step-finish, and is kept whole. When the step is cut, * or kept whole without the text it already streamed, `inFlightText` is added as its own assistant message, * returned as `inFlightMessageId` so the caller can run it through the step processors it never reached. * @internal */ cloneWithCompletedSteps(inFlightText?: string): { turn: MessageList; inFlightMessageId?: string; }; private all; private remembered; private rememberedPersisted; private input; private inputPersisted; private response; /** * Every response message this run produced, in order, including messages that were later pruned * from the live context (see removeByIds' `pruned` option). Use this to evaluate the whole run, * e.g. for scoring; use getPersisted.response for what is still in the list. * * A list restored from serialized state only knows pruned messages by id; `loadStoredMessages` * loads them from memory, where they were saved before being pruned. Pruned messages it cannot * load are left out. */ getRunResponseMessages(loadStoredMessages?: StoredMessageLoader): Promise<MastraDBMessage[]>; private responsePersisted; private recordUnavailableAttachment; /** * Returns and clears the attachments newly recorded as unavailable while building * prompts. The in-memory messages already carry the record; callers persist it for * messages that were loaded from storage. */ drainUnavailableAttachmentUpdates(): { messageId: string; urls: string[]; }[]; drainUnsavedMessages(): MastraDBMessage[]; /** * Same as {@link drainUnsavedMessages}, plus `restore`, which marks the drained * messages unsaved again so a later save writes them after this one failed. */ drainUnsavedMessagesForSave(): { messages: MastraDBMessage[]; restore: () => void; }; /** * Apply transcript payload transforms to messages without draining them. * * Persistence paths that read messages directly instead of draining (e.g. * the MessageHistory output processor persisting `get.response.db()`) must * apply the same transcript redaction as {@link drainUnsavedMessages}. * Otherwise the two writers race last-writer-wins on the same message id: a * background tool result committed via {@link updateToolInvocation} holds * the raw payload plus its transcript transform in providerMetadata, and a * direct save landing after the redacting save-queue flush would persist * the raw payload. The transform is idempotent — re-applying it to an * already-transformed message writes the same values. */ transformMessagesForTranscript(messages: MastraDBMessage[]): MastraDBMessage[]; private transformToolStateDataForTranscript; private transformMessageForTranscript; getEarliestUnsavedMessageTimestamp(): number | undefined; /** * Check if a message is a new user or response message that should be saved. * Checks by message ID to handle cases where the message object may be a copy. */ isNewMessage(messageOrId: MastraDBMessage | string): boolean; /** * Replace a tool-invocation part matching the given toolCallId with the * provided result part. Walks backwards through messages to find the match. * If the message was already persisted (e.g. as a memory message), it is * moved to the response source so it will be re-saved. * * @returns true if the tool call was found and updated, false otherwise. */ updateToolInvocation(inputPart: Extract<MastraMessagePart, { type: 'tool-invocation'; }>, metadata?: Record<string, unknown>): boolean; updateMessageMetadataByToolCallId(toolCallId: string, metadata: Record<string, unknown>): boolean; /** * Fail explicitly selected provider calls still in `call` or `partial-call` state. * Explicit IDs prevent masking unrelated missing-result bugs. Preserves args and * metadata, syncs legacy AIV4 invocations, and queues the message for persistence. * Returns whether any call changed. */ addOutputErrorsToProviderToolCalls(messageId: string, toolCallIds: string[], errorText?: string): boolean; /** * Merge a tool-result `inputPart` into the stored tool-invocation part at * `msg.content.parts[i]`: preserves the original call args, merges * providerExecuted/providerMetadata, merges per-toolCallId `backgroundTasks` * metadata, and moves the message to the response source so it is re-saved. * Shared by both the exact-toolCallId and provider-executed-toolName passes * of {@link updateToolInvocation}. */ private mergeToolResultIntoPart; /** * Append a `step-start` boundary to the last assistant message. * This marks the beginning of a new loop iteration so that * `convertToModelMessages` splits sequential tool-call turns into * separate message blocks instead of collapsing them into one. * * Respects sealed messages (post-observation) — if the last assistant * message is sealed, the step-start is not added. * * If the message was loaded from memory it is moved to the response * source so the updated content is re-saved. */ stepStart(): boolean; /** * Open the boundary for a new loop iteration and hand back the marker that delimits it. * * This is `stepStart()` with the marker returned instead of discarded, for callers that * need to name *their own* boundary later — `rollbackToStepBoundary` is the only one today. * The distinction matters because `step-start` has several writers and they are * indistinguishable once stored: besides this loop boundary, a marker is synthesized inside a * single model response whenever a tool call is followed by text * (`build-messages-from-chunks.ts`, `MessageMerger.pushNewPart`, `addStartStepPartsForAIV5`). * Nothing on the part records which writer produced it — `model` in particular does not, since * `MessageMerger` deliberately copies it from the preceding marker onto the synthetic one. * So "the last `step-start`" is not "the boundary this iteration opened", and only the caller * that opened one can tell them apart. The reference is the primary handle; a checkpoint is * recorded alongside it so `findBoundaryIndex` can still recognise the marker if a processor * hands the list a cloned copy of the parts. Nothing new is written to the part itself. * * When the last part is already a `step-start` the iteration begins at *that* marker — nothing * has been appended after it — so it is returned rather than duplicated. * * @returns the marker beginning this iteration, and whether it had to be appended */ openStepBoundary(): { boundary?: MastraStepStartPart; appended: boolean; }; /** * The parts of `message` written by the current loop iteration: those after the boundary the * latest `openStepBoundary()` opened, or all of them when that boundary is not in `message` * (a first iteration opens none, and a later one may have started a new message). * Intra-response `step-start` markers are not boundaries, so this never splits a single response. */ partsSinceStepBoundary(message: MastraDBMessage): MastraMessagePart[]; /** Sealing is not optional: a moved id whose boundary is missing folds the next response into the previous row. */ rotateResponseMessageId(sealMessageId?: string): string; markResponseMessageBoundary(messageId?: string): boolean; enrichLastStepStart(model: string): boolean; getSystemMessages(tag?: string): CoreMessageV4[]; /** * Get all system messages (both tagged and untagged) * @returns Array of all system messages */ getAllSystemMessages(): CoreMessageV4[]; /** * Clear system messages, optionally for a specific tag * @param tag - If provided, only clears messages with this tag. Otherwise clears untagged messages. */ clearSystemMessages(tag?: string): this; /** * Replace the untagged system message bucket with the provided array while * leaving tagged system message buckets (owned by other processors) intact. * @param messages - Array of system messages to set as untagged */ replaceAllSystemMessages(messages: CoreMessageV4[]): this; addSystem(messages: CoreMessageV4 | CoreMessageV4[] | AIV6Type.ModelMessage | AIV6Type.ModelMessage[] | AIV5Type.ModelMessage | AIV5Type.ModelMessage[] | MastraDBMessage | MastraDBMessage[] | string | string[] | null, tag?: string): this; private addOneSystem; private isDuplicateSystem; private getMessageIndex; private getMessagesWithId; private getMessageById; private appendMessage; private replaceMessageAt; private sortMessages; private shouldReplaceMessage; private addOne; private pushMessageToSource; private lastCreatedAt?; private seenAsStored; private livePlacement; private liveArrivals; private moveLiveMessagesPastStoredTies; private isAnchoredSignal; private updateLastCreatedAt; private generateCreatedAt; private newMessageId; private createAdapterContext; } export {}; //# sourceMappingURL=message-list.d.ts.map