@mastra/core
Version:
932 lines • 48.1 kB
TypeScript
import type { LanguageModelV2, LanguageModelV2CallWarning, LanguageModelV2Prompt } from '../_types/@ai-sdk_provider@2.0.5/dist/index.js';
import type { CoreMessage as CoreMessageV4 } from '../_types/@internal_ai-sdk-v4@0.0.98/dist/index.js';
import type { StepResult, ToolChoice } from '../_types/@internal_ai-sdk-v5@0.0.98/dist/index.js';
import type { Agent } from '../agent/index.js';
import type { MessageList, MastraDBMessage } from '../agent/message-list/index.js';
import type { AgentSignalInput, AgentStateSignalInput, CreatedAgentSignal } from '../agent/signals.js';
import type { ApplyStateSignalResult } from '../agent/state-signals.js';
import type { TripWireOptions } from '../agent/trip-wire.js';
import type { ModelRouterModelId, MastraModelSettings } from '../llm/model/index.js';
import type { MastraLanguageModel, OpenAICompatibleConfig, SharedProviderOptions } from '../llm/model/shared.types.js';
import type { Mastra } from '../mastra/index.js';
import type { MastraMemory } from '../memory/memory.js';
import type { ObservabilityContext, ProcessorSpanPhase as ObservabilityProcessorSpanPhase, ProcessorSpanType, SpanTypeMap, TracingContext } from '../observability/index.js';
import type { RequestContext } from '../request-context/index.js';
import type { InferStandardSchemaOutput, StandardSchemaWithJSON } from '../schema/index.js';
import type { ChunkType } from '../stream/index.js';
import type { DataChunkType, LanguageModelUsage, LLMStepResult, ProviderMetadata } from '../stream/types.js';
import type { Workflow } from '../workflows/index.js';
import type { OutputWriter } from '../workflows/types.js';
import type { AnyWorkspace } from '../workspace/workspace.js';
import type { StructuredOutputOptions } from './processors/index.js';
import type { ProcessorState } from './runner.js';
import type { ProcessorStepOutput } from './step-schema.js';
/**
* Options forwarded alongside a custom chunk emitted via ProcessorStreamWriter.
* Mirrors the options accepted by the underlying `OutputWriter` so processors can
* pass them through type-safely. The runtime may override fields it owns (for
* example, `messageId` is overridden with the step-owned response id).
*/
export type ProcessorStreamWriterOptions = {
messageId?: string;
};
/**
* Writer interface for processors to emit custom data chunks to the stream.
* This enables real-time streaming of processor-specific data (e.g., observation markers).
*/
export interface ProcessorStreamWriter {
/**
* Emit a custom data chunk to the stream.
* The chunk type must start with 'data-' prefix.
* @param data - The data chunk to emit
* @param options - Optional options forwarded to the underlying output writer
* (e.g. `messageId`). Fields the runtime owns may be overridden.
*/
custom<T extends {
type: string;
}>(data: T extends {
type: `data-${string}`;
} ? DataChunkType : T, options?: ProcessorStreamWriterOptions): Promise<void>;
}
/**
* Base context shared by all processor methods
*/
export interface ProcessorContext<TTripwireMetadata = unknown> extends Partial<ObservabilityContext> {
/**
* Function to abort processing with an optional reason and options.
* @param reason - The reason for aborting
* @param options - Options including retry flag and metadata
*/
abort: (reason?: string, options?: TripWireOptions<TTripwireMetadata>) => never;
/** Optional runtime context with execution metadata */
requestContext?: RequestContext;
/** Real agent instance when processors are running inside an agent execution. Processor-only workflow contexts may omit it. */
agent?: Agent<any, any, any, any>;
/**
* Add a signal to the message list, rotate the response message id when supported,
* and emit the signal as a data-* stream part when a writer is available.
*/
sendSignal?: (signal: AgentSignalInput) => Promise<CreatedAgentSignal>;
/**
* Add a named state signal to the message list, stream it when possible, and update
* thread-level state tracking metadata.
*/
sendStateSignal?: (signal: AgentStateSignalInput | (Omit<AgentStateSignalInput, 'id'> & {
id?: string;
})) => Promise<CreatedAgentSignal | ApplyStateSignalResult>;
/**
* Number of times processors have triggered retry for this generation.
* Use this to implement retry limits within your processor.
*/
retryCount: number;
/**
* Optional stream writer for emitting custom data chunks.
* Available when the agent is streaming and outputWriter is provided.
* Use writer.custom() to emit data-* chunks that will be streamed to the client.
*/
writer?: ProcessorStreamWriter;
/**
* Optional abort signal from the parent agent execution.
* Processors should pass this to any long-running operations (e.g., LLM calls)
* so they can be canceled when the parent agent is aborted.
*/
abortSignal?: AbortSignal;
}
/**
* Context for message-based processor methods (processInput, processOutputResult, processInputStep)
*/
export interface ProcessorMessageContext<TTripwireMetadata = unknown> extends ProcessorContext<TTripwireMetadata> {
/** The current messages being processed */
messages: MastraDBMessage[];
/** MessageList instance for managing message sources */
messageList: MessageList;
}
/**
* Return type for processInput that includes modified untagged system messages.
* Tagged system messages owned by other processors are preserved.
*/
export interface ProcessInputResultWithSystemMessages {
messages: MastraDBMessage[];
systemMessages: CoreMessageV4[];
}
/**
* Return type for message-based processor methods
* - MessageList: Return the same messageList instance passed in (indicates you've mutated it)
* - MastraDBMessage[]: Return transformed messages array (for simple transformations)
*/
export type ProcessorMessageResult = Promise<MessageList | MastraDBMessage[]> | MessageList | MastraDBMessage[];
/**
* Possible return types from processInput
*/
export type ProcessInputResult = MessageList | MastraDBMessage[] | ProcessInputResultWithSystemMessages;
/**
* Arguments for processInput method
*/
export interface ProcessInputArgs<TTripwireMetadata = unknown> extends ProcessorMessageContext<TTripwireMetadata> {
/** Untagged system messages for read/modify access. Tagged processor-owned messages remain on messageList. */
systemMessages: CoreMessageV4[];
/** Per-processor state that persists across all method calls within this request */
state: Record<string, unknown>;
}
/**
* Resolved generation result passed to processOutputResult.
* Contains the same data available in the onFinish callback.
*/
export interface OutputResult {
/** The accumulated text from all steps */
text: string;
/** Token usage (cumulative across all steps) */
usage: LanguageModelUsage;
/** Why the generation finished (e.g. 'stop', 'tool-calls', 'length') */
finishReason: string;
/** All LLM step results (each contains text, toolCalls, toolResults, usage, sources, files, reasoning, etc.) */
steps: LLMStepResult[];
/**
* @deprecated No longer set. `MessageHistory` no longer drops failed turns it receives; check `finishReason === 'error'` to detect failed runs.
*/
inputAccepted?: boolean;
}
/**
* Arguments for processOutputResult method
*/
export interface ProcessOutputResultArgs<TTripwireMetadata = unknown> extends ProcessorMessageContext<TTripwireMetadata> {
/** Per-processor state that persists across all method calls within this request */
state: Record<string, unknown>;
/** Resolved generation result with usage, text, steps, and finish reason */
result: OutputResult;
}
/**
* Arguments for processInputStep method
*
* Note: structuredOutput.schema is typed as OutputSchema (not the specific OUTPUT type) because
* processors run in a chain and any previous processor may have modified structuredOutput.
* The actual schema type is only known at the generate()/stream() call site.
*/
export interface ProcessInputStepArgs<TTripwireMetadata = unknown> extends ProcessorMessageContext<TTripwireMetadata> {
/** The active agent run ID, when this processor is running inside an agent loop */
runId?: string;
/** The current step number (0-indexed) */
stepNumber: number;
steps: Array<StepResult<any>>;
/** The active assistant response message ID for this step, when this processor is running inside an agent loop */
messageId?: string;
/** Mark the current assistant response message ID as complete and rotate to a fresh one, when supported by the caller */
rotateResponseMessageId?: () => string;
/** Untagged system messages for read/modify access. Tagged processor-owned messages remain on messageList. */
systemMessages: CoreMessageV4[];
/** Per-processor state that persists across all method calls within this request */
state: Record<string, unknown>;
/**
* When true, this processor will also have processLLMRequest called after
* processInputStep. Processors that implement both methods can skip
* pre-conversion trimming here and defer it to the prompt stage, where it
* accounts for earlier prompt processors (e.g. ToolCallFilter).
*/
llmRequestStage?: boolean;
/**
* Current model for this step.
* Can be a resolved MastraLanguageModelV2 or an unresolved config (string, OpenAI-compatible config).
*/
model: MastraLanguageModel;
/** Current tools available for this step */
tools?: Record<string, unknown>;
toolChoice?: ToolChoice<any>;
activeTools?: string[];
providerOptions?: SharedProviderOptions;
modelSettings?: MastraModelSettings;
/**
* Structured output configuration. The schema type is StandardSchemaWithJSON (not the specific OUTPUT)
* because processors can modify it, and the actual type is only known at runtime.
*/
structuredOutput?: StructuredOutputOptions<InferStandardSchemaOutput<StandardSchemaWithJSON>>;
/**
* Number of times processors have triggered retry for this generation.
* Use this to implement retry limits within your processor.
*/
retryCount: number;
}
export type RunProcessInputStepArgs = Omit<ProcessInputStepArgs, 'messages' | 'systemMessages' | 'abort' | 'state' | 'messageId' | 'rotateResponseMessageId' | 'retryCount'> & {
messageId?: string;
rotateResponseMessageId?: () => string;
retryCount?: number;
memory?: MastraMemory;
resourceId?: string;
threadId?: string;
/**
* IDs of processors whose processLLMRequest will run for this step.
* The runner sets llmRequestStage for these processors, including when they
* run inside a processor workflow.
*/
llmRequestProcessorIds?: ReadonlySet<string>;
};
/**
* Result from processInputStep method
*
* Note: structuredOutput.schema is typed as StandardSchemaWithJSON (not the specific OUTPUT type) because
* processors can modify it dynamically, and the actual type is only known at runtime.
*/
export type ProcessInputStepResult = {
model?: LanguageModelV2 | ModelRouterModelId | OpenAICompatibleConfig | MastraLanguageModel;
/** Override the active assistant response message ID for this step */
messageId?: string;
/** Replace tools for this step - accepts both AI SDK tools and Mastra createTool results */
tools?: Record<string, unknown>;
toolChoice?: ToolChoice<any>;
activeTools?: string[];
messages?: MastraDBMessage[];
messageList?: MessageList;
/**
* Replace untagged system messages with these while preserving tagged system messages
* owned by other processors.
*/
systemMessages?: CoreMessageV4[];
providerOptions?: SharedProviderOptions;
modelSettings?: MastraModelSettings;
/**
* Structured output configuration. The schema type is StandardSchemaWithJSON (not the specific OUTPUT)
* because processors can modify it, and the actual type is only known at runtime.
*/
structuredOutput?: StructuredOutputOptions<InferStandardSchemaOutput<StandardSchemaWithJSON>>;
/**
* Number of times processors have triggered retry for this generation.
* Use this to implement retry limits within your processor.
*/
retryCount?: number;
};
export type RunProcessInputStepResult = Omit<ProcessInputStepResult, 'model'> & {
model?: MastraLanguageModel;
};
/**
* Arguments for processLLMRequest method.
*
* Called *after* `MessageList` has been converted to the LLM-shaped prompt
* (`LanguageModelV2Prompt`) and *before* the prompt is forwarded to the
* provider. Mutations affect only what is sent to the model on this call —
* they are *not* persisted back to the message list, so reasoning,
* tool-result formats, etc. can be rewritten transiently without losing data
* in memory, UI, or future model swaps.
*/
export type ProcessorStateSignal = Omit<AgentStateSignalInput, 'id'> & {
id?: string;
};
export type ProcessorActiveStateSignal = CreatedAgentSignal & {
type: 'state';
metadata?: Record<string, unknown> & {
state?: {
id?: string;
threadId?: string;
cacheKey?: string;
version?: number;
mode?: 'snapshot' | 'delta';
};
};
};
/**
* Arguments for computeStateSignal method.
*
* Called once per model input step after normal per-step input processing and
* before the LLM request is finalized. State signals require memory-backed
* threads so the runtime can track versions on thread metadata.
*/
export interface ComputeStateSignalArgs<TTripwireMetadata = unknown> extends ProcessorMessageContext<TTripwireMetadata> {
/** The current step number (0-indexed) */
stepNumber: number;
/** All completed steps so far. */
steps: Array<StepResult<any>>;
/** Per-processor state that persists across all method calls within this request */
state: Record<string, unknown>;
/** Memory resource id for the active thread. */
resourceId: string;
/** Memory thread id that scopes this processor's state signal identity. */
threadId: string;
/** Active state signal copies for this processor/thread currently known to the runtime. */
activeStateSignals: ProcessorActiveStateSignal[];
/** Facts derived from the active message context window for this processor/thread. */
contextWindow: {
/** Whether the active message window already contains a snapshot for this processor/thread. */
hasSnapshot: boolean;
};
/** Latest snapshot signal for this processor/thread, resolved from message history when needed. */
lastSnapshot?: ProcessorActiveStateSignal;
/** Delta signals accepted after the latest snapshot for this processor/thread. */
deltasSinceSnapshot: ProcessorActiveStateSignal[];
/** Last persisted tracking metadata for this processor/thread. */
tracking?: ProcessorStateSignalTracking;
}
/**
* Thread metadata stored under metadata.mastra.stateSignals[stateId].
*/
export type ProcessorStateSignalTracking = {
currentCacheKey?: string;
currentMode?: 'snapshot' | 'delta';
version?: number;
lastSignalId?: string;
lastSnapshotSignalId?: string;
updatedAt?: string;
activeCopies?: Array<{
id: string;
cacheKey?: string;
mode?: 'snapshot' | 'delta';
version?: number;
}>;
};
export type ComputeStateSignalResult = ProcessorStateSignal | undefined | void;
export interface ProcessLLMRequestArgs<TTripwireMetadata = unknown> extends ProcessorContext<TTripwireMetadata> {
/** The LLM request prompt that will be sent to the provider on this call. Processors may return a modified copy. */
prompt: LanguageModelV2Prompt;
/** The model the prompt is being sent to. Use to scope provider-specific rewrites. */
model: MastraLanguageModel;
/**
* Provider id of the API the prompt is sent to, e.g. `openai.chat`, `groq.chat` or `openai.responses`.
* Unlike `model.provider`, router models (`'groq/...'`) report the model they resolve to, so a
* processor can tell a Chat Completions endpoint from a Responses one. Undefined when it couldn't be resolved.
*/
apiProviderId?: string;
/** The message list the prompt was built from, for provenance that the converted prompt no longer carries (e.g. per-message metadata stamps). */
messageList?: MessageList;
/** The workspace of this step, the one the agent's tools use. Undefined when the agent has none. */
workspace?: AnyWorkspace;
/** The current step number (0-indexed) within the agentic loop. */
stepNumber: number;
/** All completed steps so far. */
steps: Array<StepResult<any>>;
/** Per-processor state that persists across all method calls within this request. */
state: Record<string, unknown>;
}
/**
* Result from processLLMRequest method. Returning `undefined` (or `void`)
* indicates no changes — the original prompt is forwarded as-is.
*
* When `response` is set, the agentic loop will skip the model call entirely
* and synthesize a stream from the cached chunks. This enables response
* caching at the provider boundary: a processor reads from a cache in
* `processLLMRequest` and writes to it in `processLLMResponse` after a real
* call completes.
*/
export type ProcessLLMRequestResult = {
/** The prompt to forward to the provider for this call. */
prompt?: LanguageModelV2Prompt;
/**
* When set, the loop emits these chunks instead of invoking the model.
* The cached chunks must be in the same shape `MastraModelOutput`
* receives from a live model — typically captured via
* `processLLMResponse` on a previous call.
*/
response?: CachedLLMStepResponse;
} | undefined | void;
/**
* Portable shape used to cache and replay LLM step chunks across runs.
*
* Only the fields required to rebuild the response are persisted —
* per-run metadata such as `runId` and `from` is reattached at replay time
* by the loop, so cached values are stable across runs and machines.
*/
export interface CachedLLMStepChunk {
type: string;
payload: unknown;
}
/**
* Cached LLM step response, replayable in place of a live model call.
*
* Returned from `processLLMRequest` when a cache hit occurs and captured by
* `processLLMResponse` after a live call completes so future cache hits can
* replay the same response.
*/
export interface CachedLLMStepResponse {
/**
* The chunks produced by the LLM call, in original order. Replayed via a
* synthetic `ReadableStream` on cache hit. Stored in stripped form
* (`{ type, payload }`); the loop reattaches `runId`/`from` on replay.
*/
chunks: CachedLLMStepChunk[];
/** Warnings reported by the language model call (e.g. unsupported settings). */
warnings?: LanguageModelV2CallWarning[];
/** Provider request body captured for tracing/observability. */
request?: unknown;
/** Raw provider response captured for tracing/observability. */
rawResponse?: unknown;
}
/**
* Arguments for processLLMResponse method.
*
* Called *after* the LLM step completes (or a cached response is replayed)
* and *after* output processors have collected the response chunks. Use this
* hook for side effects on the actual response the model produced (or that
* was replayed) — typically to write to a response cache.
*
* The `state` object is shared with `processLLMRequest` for the same request,
* so a processor can stash a cache key in `processLLMRequest` and read it
* back here to write the response.
*/
export interface ProcessLLMResponseArgs<TTripwireMetadata = unknown> extends ProcessorContext<TTripwireMetadata> {
/**
* Chunks produced by the LLM call (or replayed from cache) for this step.
* Stored in stripped form (`{ type, payload }`) so cached values are stable
* across runs.
*/
chunks: CachedLLMStepChunk[];
/** The model that produced (or would have produced) the response. */
model: MastraLanguageModel;
/** The current step number (0-indexed). */
stepNumber: number;
/** All completed steps so far (including this step). */
steps: Array<StepResult<any>>;
/** Per-processor state shared with `processLLMRequest`. */
state: Record<string, unknown>;
/** Warnings reported by the language model call. */
warnings?: LanguageModelV2CallWarning[];
/** Provider request body, when available. */
request?: unknown;
/** Raw provider response, when available. */
rawResponse?: unknown;
/**
* `true` when this response was replayed from a cache via
* `processLLMRequest` returning `{ response }`. Processors that write to a
* cache should typically skip writes when this is `true`.
*/
fromCache: boolean;
}
/**
* Result from processLLMResponse method. Returning `undefined` (or `void`)
* is the only supported result today; this exists for future extensibility.
*/
export type ProcessLLMResponseResult = undefined | void;
/**
* Arguments for processOutputStream method
*/
export interface ProcessOutputStreamArgs<TTripwireMetadata = unknown> extends ProcessorContext<TTripwireMetadata> {
/** The current chunk being processed */
part: ChunkType;
/** All chunks seen so far */
streamParts: ChunkType[];
/** Mutable state object that persists across chunks */
state: Record<string, unknown>;
/** Optional MessageList instance for accessing conversation history */
messageList?: MessageList;
}
/**
* Tool call information for processOutputStep
*/
export interface ToolCallInfo {
toolName: string;
toolCallId: string;
args: unknown;
}
/**
* Arguments for processOutputStep method.
* Called after each LLM response in the agentic loop, before tool execution.
*/
export interface ProcessOutputStepArgs<TTripwireMetadata = unknown> extends ProcessorMessageContext<TTripwireMetadata> {
/** The current step number (0-indexed) */
stepNumber: number;
/** The finish reason from the LLM (stop, tool-use, length, etc.) */
finishReason?: string;
/**
* Provider-specific metadata for the step that just finished (e.g. AWS
* Bedrock guardrail trace under `providerMetadata.bedrock.trace.guardrail`).
* Present whenever the underlying model step produced it — including
* `content-filter` blocks, for which `steps` is empty.
*/
providerMetadata?: ProviderMetadata;
/** Tool calls made in this step (if any) */
toolCalls?: ToolCallInfo[];
/** Generated text from this step */
text?: string;
/** Token usage for the current step (input tokens, output tokens, etc.) */
usage: LanguageModelUsage;
/** Untagged system messages. Tagged processor-owned messages remain on messageList. */
systemMessages: CoreMessageV4[];
/** All completed steps so far (including the current step) */
steps: Array<StepResult<any>>;
/** Mutable state object that persists across steps */
state: Record<string, unknown>;
}
/**
* Arguments for processToolResult method.
* Called after each tool's execute() returns successfully and before the
* result is appended to the message list / fed to the next LLM call.
* Symmetric with processOutputStep, which fires before tool execution.
*/
export interface ProcessToolResultArgs<TTripwireMetadata = unknown> extends ProcessorMessageContext<TTripwireMetadata> {
/** The current step number (0-indexed) */
stepNumber: number;
/** Name of the tool that was executed */
toolName: string;
/** Unique identifier for this specific tool call */
toolCallId: string;
/** Arguments the LLM passed to the tool */
args: unknown;
/**
* Value returned by the tool. For client-executed tools this is the output of
* `tool.execute()` after it has passed through `ensureSerializable`. For
* provider-executed tools (e.g. Anthropic `web_search`) it is the raw result
* from the provider stream, which is not run through `ensureSerializable`.
*/
result: unknown;
/**
* The tool's `toModelOutput` mapping of `result`: what the next model call
* and stored history read in place of the raw result. `undefined` when the
* tool has no `toModelOutput` or it returned nothing.
*
* To replace it (e.g. resize or remove images), commit a `result`-state
* part with `messageList.updateToolInvocation` that carries the new value in
* `providerMetadata.mastra.modelOutput`; `null` there drops the mapping so
* the model reads the raw result. Replacing only `result` re-runs
* `toModelOutput` on the new value.
*/
modelOutput?: unknown;
/** Whether this result came from a provider-executed tool (e.g. Anthropic web_search) */
providerExecuted?: boolean;
/** All system messages */
systemMessages: CoreMessageV4[];
/** All completed steps so far */
steps: Array<StepResult<any>>;
/** Per-processor state that persists across all method calls within this request */
state: Record<string, unknown>;
}
/**
* Arguments for processAPIError method.
* Called when the LLM API call fails with a non-retryable error (API rejection).
* This is distinct from network errors or retryable server errors (which are handled by p-retry).
*/
export interface ProcessAPIErrorArgs<TTripwireMetadata = unknown> extends ProcessorMessageContext<TTripwireMetadata> {
/** The error that occurred during the LLM API call */
error: unknown;
/** The current step number (0-indexed) */
stepNumber: number;
/** All completed steps so far */
steps: Array<StepResult<any>>;
/** The active assistant response message ID for this step, when this processor is running inside an agent loop */
messageId?: string;
/** Mark the current assistant response message ID as complete and rotate to a fresh one, when supported by the caller */
rotateResponseMessageId?: () => string;
/** Per-processor state that persists across all method calls within this request */
state: Record<string, unknown>;
/** The current retry count for this error handler */
retryCount: number;
}
/**
* Result from processAPIError method.
*/
export type ProcessAPIErrorResult = {
/** Whether to retry the LLM call after applying modifications */
retry: boolean;
};
/**
* Processor interface for transforming messages and stream chunks.
*
* @template TId - The processor's unique identifier type
* @template TTripwireMetadata - The type of metadata passed when calling abort()
*/
/**
* A violation event emitted by a processor when it detects a policy breach.
* Generic enough to be used by any processor (cost guard, moderation, PII, etc.).
*/
export interface ProcessorViolation<TDetail = unknown> {
/** The processor that detected the violation */
processorId: string;
/** Human-readable description of the violation */
message: string;
/** Processor-specific violation details */
detail: TDetail;
}
/**
* Pipeline phase a processor span is created for. One value per site where the
* processor runner creates a span, so a processor that runs in more than one
* phase can name and describe each of them differently.
*
* Defined in the observability types because `ProcessorPipelineAttributes`
* records it on the span; re-exported here as the name processors use.
*/
export type ProcessorSpanPhase = ObservabilityProcessorSpanPhase;
export interface Processor<TId extends string = string, TTripwireMetadata = unknown> {
readonly id: TId;
readonly name?: string;
readonly description?: string;
/**
* Declares that this processor owns skill discovery and instruction loading.
* Agents use this to avoid adding eager skill context and overlapping skill tools.
*/
readonly providesSkillDiscovery?: 'on-demand';
/**
* Span type the runner should use for this processor's span, instead of the
* default `PROCESSOR_RUN`.
*
* Processors Mastra derives from agent config (skills, workspace
* instructions, memory, task state) are an implementation detail of how a
* subsystem injects context — the user never wrote the word "processor". A
* declared span type labels the span with the subsystem it came from, so the
* trace shows where it originated instead of an anonymous processor entry.
*
* The runner keeps setting `entityType` and the `ProcessorPipelineAttributes`
* fields either way — including `processorPhase`, which is what a reader
* narrows the span's payloads on — so retyping never loses the processor's
* position in the chain, its mutation log, or the readable view of its
* input and output.
*/
readonly spanType?: ProcessorSpanType;
/**
* Span name for this processor's span, instead of the runner's default
* `<phase> processor: <id>`. Pair this with `spanType` so the name matches
* the subsystem the span is labelled as.
*
* Pass a function to name each phase separately. A processor that runs in
* more than one phase usually does something different in each — the
* observational memory processor recalls context on the input step and
* persists observations on the output result — and one static name would
* describe both wrongly.
*/
readonly spanName?: string | ((phase: ProcessorSpanPhase) => string);
/**
* Attributes the runner sets when it creates this processor's span.
*
* Needed because a declared `spanType` may have required attributes of its
* own — `WORKSPACE_ACTION.category`, `SKILL_ACTION.operation` — that only the
* processor knows. Setting them here means the span carries them from
* creation rather than being patched in later by the processor body.
*
* Note the pairing with `spanType` is not enforced by the type system: this
* accepts a partial of any processor-declarable attributes, so declaring
* `WORKSPACE_ACTION` alongside a `SKILL_ACTION` field will not be caught at
* compile time.
*/
readonly spanAttributes?: Partial<SpanTypeMap[ProcessorSpanType]> | ((phase: ProcessorSpanPhase) => Partial<SpanTypeMap[ProcessorSpanType]>);
/** Index of this processor in the workflow (set at runtime when combining processors) */
processorIndex?: number;
/** When true, this processor will also receive `data-*` chunks in processOutputStream. Default: false. */
processDataParts?: boolean;
/**
* Optional callback invoked when this processor detects a violation, regardless of strategy.
* Use for side effects like alerting, logging to external systems, or emailing users.
* Errors thrown by this callback are silently caught to prevent interfering with processor logic.
*/
onViolation?: (violation: ProcessorViolation) => void | Promise<void>;
/**
* Process input messages before they are sent to the LLM
*
* @returns Either:
* - MessageList: The same messageList instance passed in (indicates you've mutated it)
* - MastraDBMessage[]: Transformed messages array (for simple transformations)
* - { messages, systemMessages }: Object with both messages and modified system messages
*/
processInput?(args: ProcessInputArgs<TTripwireMetadata>): Promise<ProcessInputResult> | ProcessInputResult;
/**
* Process output stream chunks with built-in state management
* This allows processors to accumulate chunks and make decisions based on larger context
* Return null or undefined to skip emitting the part
*/
processOutputStream?(args: ProcessOutputStreamArgs<TTripwireMetadata>): Promise<ChunkType | null | undefined>;
/**
* Process the complete output result after streaming/generate is finished
*
* @returns Either:
* - MessageList: The same messageList instance passed in (indicates you've mutated it)
* - MastraDBMessage[]: Transformed messages array (for simple transformations)
*/
processOutputResult?(args: ProcessOutputResultArgs<TTripwireMetadata>): ProcessorMessageResult;
/**
* Process input messages at each step of the agentic loop, before they are sent to the LLM.
* Unlike processInput which runs once at the start, this runs at every step (including tool call continuations).
*
* @returns Either:
* - ProcessInputStepResult object with model, toolChoice, messages, etc.
* - MessageList: The same messageList instance passed in (indicates you've mutated it)
* - MastraDBMessage[]: Transformed messages array (for simple transformations)
* - undefined/void: No changes
*/
processInputStep?(args: ProcessInputStepArgs<TTripwireMetadata>): Promise<ProcessInputStepResult | MessageList | MastraDBMessage[] | undefined | void> | ProcessInputStepResult | MessageList | MastraDBMessage[] | void | undefined;
/**
* State lane id used for `computeStateSignal` history and tracking. Defaults to the processor id.
*/
stateId?: string;
/**
* Compute this processor's thread-scoped state signal for the current model input step.
*
* Called after this processor's `processInputStep` hook and before the model request is finalized.
* The runtime persists version/cache-key tracking on memory thread metadata keyed by state id.
* Returning `undefined` means the state has not changed for this step.
*/
computeStateSignal?(args: ComputeStateSignalArgs<TTripwireMetadata>): Promise<ComputeStateSignalResult> | ComputeStateSignalResult;
/**
* Process the LLM-shaped prompt after `MessageList` has been converted to
* `LanguageModelV2Prompt` and immediately before it is forwarded to the
* provider on this call.
*
* Unlike `processInputStep`, mutations made here are *not* persisted to the
* message list — they affect only what is sent to the model on this call.
* This makes the hook ideal for transient, model-aware rewrites such as:
*
* - Stripping fields a specific provider rejects (e.g. `reasoning_content`
* on Cerebras) without losing reasoning traces in memory or UI.
* - Re-shaping tool-result formats when switching between providers mid-loop.
* - Trimming or coalescing roles to match per-provider input requirements.
*
* Return `{ prompt }` to forward your modified prompt, or `undefined`/`void`
* to pass the original prompt through unchanged.
*/
processLLMRequest?(args: ProcessLLMRequestArgs<TTripwireMetadata>): Promise<ProcessLLMRequestResult> | ProcessLLMRequestResult;
/**
* Process the LLM response immediately after the step completes (or after a
* cached response is replayed) and after output processors collect the
* chunks. Pairs with {@link Processor.processLLMRequest}: the same `state`
* object is shared between the two calls for the same request, so a
* processor can stash a cache key in `processLLMRequest` and read it back
* here to write the response.
*
* Use this hook for response-level side effects — typically:
*
* - Writing to a response cache so the next `processLLMRequest` call can
* short-circuit by returning `{ response }`.
* - Mirroring response chunks to an external sink for replay (test
* recorders, audit logs).
*
* Skip writes when `args.fromCache` is `true` — that response did not come
* from the model on this call.
*
* Return `undefined`/`void`. Errors thrown here propagate to the caller.
*/
processLLMResponse?(args: ProcessLLMResponseArgs<TTripwireMetadata>): Promise<ProcessLLMResponseResult> | ProcessLLMResponseResult;
/**
* Process output after each LLM response in the agentic loop, before tool execution.
* Unlike processOutputResult which runs once at the end, this runs at every step.
*
* This is the ideal place to implement guardrails that can trigger retries:
* - Validate tone, format, or content of LLM responses
* - Check for policy violations before tools are executed
* - Implement self-correction by calling abort({ retry: true })
*
* @returns Either:
* - MessageList: The same messageList instance passed in (indicates you've mutated it)
* - MastraDBMessage[]: Transformed messages array (for simple transformations)
*/
processOutputStep?(args: ProcessOutputStepArgs<TTripwireMetadata>): ProcessorMessageResult;
/**
* Process a tool's result after tool.execute() returns successfully and before
* the result is added to the message list or fed to the next LLM call.
*
* Symmetric with processOutputStep (which runs before tool execution). Use this
* hook to scan tool output for prompt injection / sensitive data, redact fields,
* or abort the run with abort({ retry: true }).
*
* To replace the tool's result, mutate messageList in place via
* messageList.updateToolInvocation. The runtime re-reads the post-processor
* result from the message list and overwrites the downstream tool-result
* stream chunk before it's enqueued, so streaming clients see the processed
* value, not the raw one.
*
* Note: this hook does not fire when tool.execute() throws — it is called only
* for successful tool executions where a result is available.
*
* @returns Either:
* - MessageList: The same messageList instance passed in (indicates you've mutated it)
* - MastraDBMessage[]: Transformed messages array (for simple transformations)
* - undefined/void: No changes (passthrough)
*/
processToolResult?(args: ProcessToolResultArgs<TTripwireMetadata>): Promise<MessageList | MastraDBMessage[] | undefined | void> | MessageList | MastraDBMessage[] | void | undefined;
/**
* Process an LLM API rejection error before it's surfaced as a final error.
* Only called for non-retryable API rejections (e.g., 400/422 status codes),
* NOT for network errors or retryable server errors (which are handled by p-retry).
*
* This allows processors to inspect the error, modify the request (e.g., append messages),
* and signal a retry. Unlike processOutputStep which runs after successful responses,
* this runs when the API call is rejected.
*
* @returns ProcessAPIErrorResult indicating whether to retry with the modified state,
* or void/undefined to not handle the error
*/
processAPIError?(args: ProcessAPIErrorArgs<TTripwireMetadata>): Promise<ProcessAPIErrorResult | void> | ProcessAPIErrorResult | void;
/**
* Internal method called when the processor is registered with a Mastra instance.
* This allows processors to access Mastra services like knowledge, storage, etc.
* @internal
*/
__registerMastra?(mastra: Mastra<any, any, any, any, any, any, any, any, any, any>): void;
}
/**
* Base class for processors that need access to Mastra services.
* Extend this class to automatically get access to the Mastra instance
* when the processor is registered with an agent.
*
* @example
* ```typescript
* class MyProcessor extends BaseProcessor<'my-processor'> {
* readonly id = 'my-processor';
*
* async processInput(args: ProcessInputArgs) {
* // Access Mastra services via this.mastra
* const knowledge = this.mastra?.getKnowledge();
* // ...
* }
* }
* ```
*/
export declare abstract class BaseProcessor<TId extends string = string, TTripwireMetadata = unknown> implements Processor<TId, TTripwireMetadata> {
abstract readonly id: TId;
readonly name?: string;
/**
* The Mastra instance this processor is registered with.
* Available after the processor is registered via __registerMastra.
*/
protected mastra?: Mastra<any, any, any, any, any, any, any, any, any, any>;
/**
* Called when the processor is registered with a Mastra instance.
* @internal
*/
__registerMastra(mastra: Mastra<any, any, any, any, any, any, any, any, any, any>): void;
}
type WithRequired<T, K extends keyof T> = T & {
[P in K]-?: NonNullable<T[P]>;
};
export type InputProcessor<TTripwireMetadata = unknown> = (WithRequired<Processor<string, TTripwireMetadata>, 'id' | 'processInput'> & Processor<string, TTripwireMetadata>) | (WithRequired<Processor<string, TTripwireMetadata>, 'id' | 'processInputStep'> & Processor<string, TTripwireMetadata>) | (WithRequired<Processor<string, TTripwireMetadata>, 'id' | 'computeStateSignal'> & Processor<string, TTripwireMetadata>) | (WithRequired<Processor<string, TTripwireMetadata>, 'id' | 'processLLMRequest'> & Processor<string, TTripwireMetadata>) | (WithRequired<Processor<string, TTripwireMetadata>, 'id' | 'processLLMResponse'> & Processor<string, TTripwireMetadata>);
export type OutputProcessor<TTripwireMetadata = unknown> = (WithRequired<Processor<string, TTripwireMetadata>, 'id' | 'processOutputStream'> & Processor<string, TTripwireMetadata>) | (WithRequired<Processor<string, TTripwireMetadata>, 'id' | 'processOutputResult'> & Processor<string, TTripwireMetadata>) | (WithRequired<Processor<string, TTripwireMetadata>, 'id' | 'processOutputStep'> & Processor<string, TTripwireMetadata>) | (WithRequired<Processor<string, TTripwireMetadata>, 'id' | 'processToolResult'> & Processor<string, TTripwireMetadata>);
export type ErrorProcessor<TTripwireMetadata = unknown> = WithRequired<Processor<string, TTripwireMetadata>, 'id' | 'processAPIError'> & Processor<string, TTripwireMetadata>;
export type ProcessorTypes<TTripwireMetadata = unknown> = InputProcessor<TTripwireMetadata> | OutputProcessor<TTripwireMetadata> | ErrorProcessor<TTripwireMetadata>;
/** @internal Context consumed by processor step adapters, without workflow engine machinery. */
export type ProcessorStepExecutor<TInput = ProcessorStepOutput> = (args: {
inputData: TInput;
requestContext?: RequestContext;
tracingContext?: TracingContext;
outputWriter?: OutputWriter;
}) => Promise<ProcessorStepOutput>;
/**
* A Workflow that can be used as a processor.
* The workflow must accept ProcessorStepInput and return ProcessorStepOutput.
*/
export type ProcessorWorkflow = Workflow<any, any, string, any, ProcessorStepOutput, ProcessorStepOutput, any> & {
/** @internal Processors in a combined workflow that compute state signals after input-step execution. */
__stateSignalProcessors?: Processor[];
/** @internal Whether a framework-generated workflow needs per-chunk execution. Unknown workflows always execute. */
__processOutputStream?: boolean;
/**
* @internal Whether any wrapped processor runs after the model stream ends
* (`processOutputStep` / `processLLMResponse`). Processors are wrapped into a
* workflow before they reach the loop, so the wrapper is the only place that
* still knows this. Unknown workflows leave it undefined and are treated as
* post-stream, because callers use this to decide what is safe to start early.
*
* Only meaningful on output chains. The same wrapper builds input chains, which
* carry the flag without it meaning anything there.
*/
__processOutputStep?: boolean;
/**
* @internal Whether any wrapped processor implements `processToolResult`. That hook
* runs *inside* the model stream and can abort the turn before the post-stream pass,
* so it is a separate question from `__processOutputStep`. Recorded here for the same
* reason: the wrapper is the only place that still knows. Unknown workflows leave it
* undefined and are treated as implementing it.
*/
__processToolResult?: boolean;
/** @internal Direct adapter execution, only for framework-generated plain processor chains. */
__executeOutputStream?: ProcessorStepExecutor;
/**
* @internal End-of-stream counterpart of `__executeOutputStream`: releases the parts the
* chained processors still hold, each pushed through the processors after its holder.
*/
__flushOutputStream?: (args: Parameters<ProcessorStepExecutor>[0]) => Promise<ChunkType[]>;
/**
* @internal Failure counterpart of `__flushOutputStream`: drops what the chained processors
* hold without emitting their content or running any further checks, returning the held
* control parts (oldest first).
*/
__discardOutputStream?: (processorStates?: Map<string, ProcessorState>) => Promise<ChunkType[]>;
};
/**
* Input processor config: can be a Processor or a Workflow.
*/
export type InputProcessorOrWorkflow<TTripwireMetadata = unknown> = InputProcessor<TTripwireMetadata> | ProcessorWorkflow;
/**
* Output processor config: can be a Processor or a Workflow.
*/
export type OutputProcessorOrWorkflow<TTripwireMetadata = unknown> = OutputProcessor<TTripwireMetadata> | ProcessorWorkflow;
/**
* Error processor config: must be a processor with processAPIError.
* Workflows are not supported because LLM API rejection handling only invokes processor methods.
*/
export type ErrorProcessorOrWorkflow<TTripwireMetadata = unknown> = ErrorProcessor<TTripwireMetadata>;
/**
* Processor config accepted by the provider-boundary LLM request lane.
*
* The lane carries input processors plus error processors, so an error-lane processor that implements
* `processLLMRequest` still gets its hook. Entries without that method are inert there.
*/
export type LLMRequestProcessorOrWorkflow<TTripwireMetadata = unknown> = InputProcessorOrWorkflow<TTripwireMetadata> | ErrorProcessorOrWorkflow<TTripwireMetadata>;
export { isProcessorWorkflow } from './is-processor-workflow.js';
export { defaultStabilityErrorProcessors, isMalformedFunctionCallError, STABILITY_ERROR_PROCESSOR_IDS, } from './stability-defaults.js';
export * from './processors/index.js';
export { CyberRefusalHandler } from './cyber-refusal-handler.js';
export { PrefillErrorHandler } from './prefill-error-handler.js';
export { UnsupportedFileHandler } from './unsupported-file-handler.js';
export { ProviderHistoryCompat, anthropicToolIdFormat, cerebrasStripReasoningContent, openaiOrphanItemId, } from './provider-history-compat.js';
export { isBadRequestError, isRetryableOpenAIResponsesStreamError, StreamErrorRetryProcessor, type StreamErrorRetryDelayMs, type StreamErrorRetryMatcher, type StreamErrorRetryMatcherConfig, type StreamErrorRetryMatcherEntry, type StreamErrorRetryProcessorOptions, } from './stream-error-retry-processor.js';
export type { CompatRule } from './provider-history-compat.js';
export { ProcessorState, ProcessorRunner } from './runner.js';
export { REPROCESS_PART_KEY } from './stream-reprocess.js';
export { createProcessorSendSignal } from './send-signal.js';
export { createBackgroundWorkSignalProcessor } from './background-work-signals.js';
export type { BackgroundWorkDisposition, BackgroundWorkInvocationKind, BackgroundWorkLifecyclePayload, BackgroundWorkTerminalStatus, } from './background-work-signals.js';
export * from './memory/index.js';
export type { TripWireOptions } from '../agent/trip-wire.js';
export { ProcessorStepSchema, ProcessorStepInputSchema, ProcessorStepOutputSchema, ProcessorInputPhaseSchema, ProcessorInputStepPhaseSchema, ProcessorOutputStreamPhaseSchema, ProcessorOutputResultPhaseSchema, ProcessorOutputStepPhaseSchema, ProcessorMessageSchema, ProcessorMessageContentSchema, MessageContentSchema, MessagePartSchema, TextPartSchema, ImagePartSchema, FilePartSchema, ToolInvocationPartSchema, ReasoningPartSchema, SourcePartSchema, StepStartPartSchema, } from './step-schema.js';
export type { ProcessorStepData, ProcessorStepDataFlexible, ProcessorStepInput, ProcessorStepOutput, ProcessorMessage, MessageContent, MessagePart, } from './step-schema.js';
//# sourceMappingURL=index.d.ts.map