@mastra/core
Version:
539 lines • 27.7 kB
TypeScript
import { z } from 'zod/v4';
import { Agent } from '../agent/index.js';
import type { AgentExecutionOptions } from '../agent/index.js';
import type { AgentInstructions, AgentMemoryOption, ToolsInput } from '../agent/types.js';
import { MastraError } from '../error/index.js';
import type { MastraModelConfig } from '../llm/model/shared.types.js';
import type { Mastra } from '../mastra/index.js';
import type { MastraMemory } from '../memory/memory.js';
import { EntityType } from '../observability/index.js';
import type { CorrelationContext, DefinitionSource, ObservabilityContext, ScorerScoreSource, ScorerStepType, ScorerTargetScope } from '../observability/index.js';
import type { ErrorProcessorOrWorkflow, InputProcessorOrWorkflow, OutputProcessorOrWorkflow } from '../processors/index.js';
import { RequestContext } from '../request-context/index.js';
import type { PublicSchema } from '../schema/index.js';
import type { JSONValue, MastraOnFinishCallback } from '../stream/index.js';
import type { MastraOnStepFinishCallback } from '../stream/types.js';
import type { DynamicArgument } from '../types/index.js';
import type { NotScorable, NotScorableOutcome } from './not-scorable.js';
import type { ScoringFilter } from './predicate.js';
import type { ScoringSamplingConfig, ScorerRunInputForAgent, ScorerRunOutputForAgent, Trajectory, TrajectoryExpectation } from './types.js';
interface ScorerStepDefinition {
name: string;
definition: any;
isPromptObject: boolean;
}
type ScorerTypeShortcuts = {
agent: {
input: ScorerRunInputForAgent;
output: ScorerRunOutputForAgent;
};
trajectory: {
input: ScorerRunInputForAgent;
output: Trajectory;
};
};
/**
* LLM-as-judge configuration for a scorer (or an individual scorer step).
*
* When `tools` is provided, the internal judge agent can call them before
* producing its score/output — e.g. a goal judge that inspects the workspace
* with readonly tools to independently verify the agent's claims, rather than
* grading text alone. Tools run in the judge agent's own tool-call loop and the
* judge still returns the step's structured output at the end.
*/
export interface ScorerJudgeConfig {
model: MastraModelConfig;
/**
* System instructions for the judge. Accepts the same forms as `Agent` instructions:
* text, system messages (which can carry `providerOptions` such as a cache setting),
* or a function of `requestContext` that returns either.
*/
instructions: DynamicArgument<AgentInstructions, any>;
/**
* Controls how the judge's structured output schema reaches the model.
* Defaults to automatic capability-based routing.
*/
jsonPromptInjection?: boolean | 'system' | 'inline' | 'auto';
/** @internal Injection placement for the format-error retry; leaves the initial request unchanged. */
fallbackJsonPromptInjection?: 'system' | 'inline';
/** Optional tools the judge agent may call while evaluating (e.g. readonly verification tools). */
tools?: ToolsInput;
/** Optional memory instance for the internal judge agent. */
memory?: MastraMemory;
/** Default memory options passed to the internal judge agent run. */
defaultMemoryOptions?: AgentMemoryOption;
/** Optional callback for observing the internal judge agent stream as soon as it starts. */
onStream?: (stream: Awaited<ReturnType<Agent['stream']>>) => void | Promise<void>;
/** Optional callback fired after each model step in the internal judge agent. */
onStepFinish?: MastraOnStepFinishCallback<unknown>;
/** Optional callback fired when an internal judge agent invocation finishes. */
onFinish?: MastraOnFinishCallback<unknown>;
/** Optional maximum number of agentic loop iterations for the internal judge agent. */
maxSteps?: number;
/**
* Optional input processors for the internal judge agent. Run before the judge's
* messages reach the model (e.g. redaction, validation).
*/
inputProcessors?: InputProcessorOrWorkflow[];
/**
* Optional output processors for the internal judge agent. Run on the judge's
* output before it is returned (e.g. moderation, transformation).
*/
outputProcessors?: OutputProcessorOrWorkflow[];
/**
* Optional error processors for the internal V2+ judge agent. These implement
* `processAPIError` and can inspect LLM API rejections and signal a retry,
* e.g. `StreamErrorRetryProcessor`. V1 judges use `generateLegacy()` and do
* not run error processors.
*/
errorProcessors?: ErrorProcessorOrWorkflow[];
/**
* Set to `false` to run only the judge's configured `errorProcessors`, with none
* of the agent's shared stability defaults added. See `AgentConfig.errorProcessorDefaults`.
*/
errorProcessorDefaults?: boolean;
/**
* Maximum number of times error processors can retry one V2+ judge generation.
* When errorProcessors are configured and this is omitted, the runtime cap is
* 3. Set this explicitly to bound the coordinated retry budget.
*/
maxProcessorRetries?: number;
/**
* Optional model call settings (e.g. temperature, topP, topK, maxOutputTokens,
* maxRetries, frequencyPenalty, presencePenalty, timeout) forwarded to the
* internal judge agent run. Step-level `judge.modelSettings` replaces this
* scorer-level value.
*/
modelSettings?: AgentExecutionOptions['modelSettings'];
/**
* Optional request context forwarded to the judge agent execution. When the judge
* agent has memory with OM observers that read dynamic model config from controller
* state (e.g. mastracode's `getObserverModel`), this lets the OM system resolve the
* correct observer model and provider credentials. Values from the run's `requestContext`
* override these values, except for reserved Mastra keys and `MastraMemory`.
*/
requestContext?: RequestContext<any>;
}
/**
* Step-level fields override scorer-level judge fields. Processor arrays replace
* the scorer-level arrays; omit maxProcessorRetries to inherit its numeric cap.
*/
export type ScorerStepJudgeConfig = Omit<ScorerJudgeConfig, 'memory' | 'defaultMemoryOptions' | 'requestContext'> & {
/** Per-step memory options merged onto scorer-level `judge.defaultMemoryOptions`. */
memory?: AgentMemoryOption;
};
interface ScorerConfig<TID extends string, TInput = any, TRunOutput = any> {
id: TID;
name?: string;
description: string;
judge?: ScorerJudgeConfig;
type?: keyof ScorerTypeShortcuts | {
input: z.ZodSchema<TInput>;
output: z.ZodSchema<TRunOutput>;
};
/**
* Transform the scorer run data before the SCORER_RUN span is created.
* Use this to strip unnecessary data from `input` and `output`, reducing
* what flows into both the scorer pipeline and the observability span.
*
* Runs synchronously before any span creation or pipeline execution.
*/
prepareRun?: (run: ScorerRun<TInput, TRunOutput>) => ScorerRun<TInput, TRunOutput> | Promise<ScorerRun<TInput, TRunOutput>>;
}
interface ScorerRun<TInput = any, TOutput = any> {
/** Unique ID for this scorer execution. Generated by scorer.run() when omitted. */
runId?: string;
/** Primary scorer input. This is often model input/messages, but can be any structured value. */
input?: TInput;
/** Primary scorer target output. This is the required value the scorer evaluates. */
output: TOutput;
/** Optional expected label/reference value for judged or supervised evaluations. */
groundTruth?: any;
/** Expected trajectory config for trajectory scorers. Flows from dataset items or scorer constructor. */
expectedTrajectory?: TrajectoryExpectation;
/**
* Optional request context forwarded to scorer steps and the judge. The judge doesn't
* receive the run's reserved Mastra keys or its `MastraMemory` binding.
*/
requestContext?: Record<string, any> | RequestContext;
/**
* RequestContext keys to persist onto the scorer-run span input, so the run
* can be reproduced later (datasets, experiments). Supports dot notation for
* nested values (e.g. `'user.id'`).
*
* This is independent of the observability config's `requestContextKeys`,
* which controls live span metadata — recording a run for repeatability and
* surfacing keys on every span are different concerns.
*
* - Omitted or `[]`: nothing from the request context is persisted (default).
* - `['*']`: the entire request context is persisted (the framework-managed
* auth token is still redacted).
* - Specific keys: only those keys are persisted.
*/
requestContextKeys?: string[];
/** What kind of scoring flow produced this score, such as live runs, trace scoring, or experiments. */
scoreSource?: ScorerScoreSource;
/**
* How the scorer interpreted the target data.
* `span` means a single span's input/output was scored.
* `trajectory` means a trajectory/path was scored.
*/
targetScope?: ScorerTargetScope;
/** Entity type of the scored target when known. */
targetEntityType?: EntityType;
/** Trace anchor for the target being scored when available. */
targetTraceId?: string;
/** Optional span anchor for the target being scored. */
targetSpanId?: string;
/** Live correlation snapshot for the target span/trace when available. */
targetCorrelationContext?: CorrelationContext;
/** Live target metadata to merge into emitted score metadata when available. */
targetMetadata?: Record<string, unknown>;
/** @internal Framework controls that must not affect scorer execution or returned results. */
_internal?: {
emitObservabilityScore?: boolean;
/**
* Inherited from the scored target's trace (`tracingOptions.hideInput`). Hides the
* scorer's own trace input and keeps the judge's reason out of the emitted score.
*/
hideInput?: boolean;
/** Inherited from the scored target's trace (`tracingOptions.hideOutput`). */
hideOutput?: boolean;
};
}
interface PromptObject<TOutput, TAccumulated extends Record<string, any>, TStepName extends string = string, TInput = any, TRunOutput = any> {
description: string;
/**
* Schema defining the expected output structure.
* Accepts any schema type supported by Mastra (Zod v4, JSON Schema, AI SDK Schema, or StandardSchema).
* Will be converted to StandardSchemaWithJSON at runtime via toStandardSchema().
*
* The TOutput generic is inferred from this schema's output type.
*/
outputSchema: PublicSchema<TOutput>;
judge?: ScorerStepJudgeConfig;
createPrompt: (context: PromptObjectContext<TAccumulated, TStepName, TInput, TRunOutput>) => string | Promise<string>;
}
type StepResultKey<T extends string> = `${T}StepResult`;
type Awaited<T> = T extends Promise<infer U> ? U : T;
type StepContext<TAccumulated extends Record<string, any>, TInput, TRunOutput> = Partial<ObservabilityContext> & {
run: ScorerRun<TInput, TRunOutput>;
results: TAccumulated;
mastra?: Mastra;
};
type AccumulatedResults<T extends Record<string, any>, K extends string, V> = T & Record<StepResultKey<K>, Exclude<V, NotScorable>>;
type GenerateReasonContext<TAccumulated extends Record<string, any>, TInput, TRunOutput> = StepContext<TAccumulated, TInput, TRunOutput> & {
score: TAccumulated extends Record<'generateScoreStepResult', infer TScore> ? TScore : never;
};
export type ScorerStepName = 'preprocess' | 'analyze' | 'generateScore' | 'generateReason';
export type ScorerJudgeStepName = ScorerStepName;
export interface ScorerJudgeUsage {
inputTokens?: number;
outputTokens?: number;
totalTokens?: number;
reasoningTokens?: number;
cachedInputTokens?: number;
cacheCreationInputTokens?: number;
}
export interface ScorerJudgeCost {
amount: number;
unit: string;
source: string;
}
interface ScorerJudgeExecutionBase {
prompt: string;
judgeModelId: string;
judgeProvider?: string;
attemptCount: number;
modelCallCount: number;
durationMs: number;
}
export interface ScorerJudgeExecutionSuccess extends ScorerJudgeExecutionBase {
status: 'success';
output: JSONValue;
usage: ScorerJudgeUsage;
cost?: ScorerJudgeCost;
}
export interface ScorerJudgeErrorSummary {
name: string;
message: string;
code?: string;
}
export interface ScorerJudgeExecutionFailure extends ScorerJudgeExecutionBase {
status: 'failed';
output?: JSONValue;
rawOutput?: string;
usage?: ScorerJudgeUsage;
finishReason?: string;
error: ScorerJudgeErrorSummary;
}
export type ScorerJudgeExecution = ScorerJudgeExecutionSuccess | ScorerJudgeExecutionFailure;
export interface ScorerJudgeStepResult {
executions: ScorerJudgeExecution[];
}
export type ScorerJudgeResults = Partial<Record<ScorerJudgeStepName, ScorerJudgeStepResult>>;
type ScorerRunResultFields<TAccumulatedResults extends Record<string, any> = Record<string, any>, TInput = any, TRunOutput = any> = ScorerRun<TInput, TRunOutput> & {
scoreTraceId?: string;
reason?: TAccumulatedResults extends Record<'generateReasonStepResult', infer TReason> ? TReason : undefined;
preprocessPrompt?: string;
analyzePrompt?: string;
generateScorePrompt?: string;
generateReasonPrompt?: string;
preprocessStepResult?: TAccumulatedResults extends Record<'preprocessStepResult', infer TPreprocess> ? TPreprocess : undefined;
analyzeStepResult?: TAccumulatedResults extends Record<'analyzeStepResult', infer TAnalyze> ? TAnalyze : undefined;
judge?: ScorerJudgeResults;
} & {
runId: string;
};
/**
* Result of `scorer.run()`.
*
* Either the run was scored (`score` is set) or a step returned `notScorable()`
* (`notScorable` is set and `score` is absent). Check `notScorable` before
* reading `score`:
*
* ```ts
* const result = await scorer.run(input)
* if (result.notScorable) {
* // skipped — no score
* } else {
* result.score // number
* }
* ```
*/
export type ScorerRunResult<TAccumulatedResults extends Record<string, any> = Record<string, any>, TInput = any, TRunOutput = any> = ScorerRunResultFields<TAccumulatedResults, TInput, TRunOutput> & ({
score: TAccumulatedResults extends Record<'generateScoreStepResult', infer TScore> ? TScore : never;
notScorable?: undefined;
} | {
score?: undefined;
/** Set when a step returned `notScorable()`. The remaining steps did not run. */
notScorable: NotScorableOutcome;
});
export type ScorerRunResultSnapshot<TResult extends ScorerRunResult = ScorerRunResult> = Omit<TResult, 'score'> & Partial<Pick<TResult, 'score'>>;
export interface ScorerRunErrorOptions<TResult extends ScorerRunResult = ScorerRunResult> {
scorerId: string;
steps: ScorerStepName[];
failedStep: ScorerStepName;
completedSteps: ScorerStepName[];
result?: ScorerRunResultSnapshot<TResult>;
cause: unknown;
}
export declare class ScorerRunError<TResult extends ScorerRunResult = ScorerRunResult> extends MastraError {
readonly failedStep: ScorerStepName;
readonly completedSteps: ScorerStepName[];
readonly result?: ScorerRunResultSnapshot<TResult>;
constructor(options: ScorerRunErrorOptions<TResult>);
}
type PromptObjectContext<TAccumulated extends Record<string, any>, TStepName extends string, TInput, TRunOutput> = TStepName extends 'generateReason' ? GenerateReasonContext<TAccumulated, TInput, TRunOutput> : StepContext<TAccumulated, TInput, TRunOutput>;
type FunctionStep<TAccumulated extends Record<string, any>, TInput, TRunOutput, TOutput> = ((context: StepContext<TAccumulated, TInput, TRunOutput>) => TOutput) | ((context: StepContext<TAccumulated, TInput, TRunOutput>) => Promise<TOutput>);
type GenerateReasonFunctionStep<TAccumulated extends Record<string, any>, TInput, TRunOutput> = ((context: GenerateReasonContext<TAccumulated, TInput, TRunOutput>) => any) | ((context: GenerateReasonContext<TAccumulated, TInput, TRunOutput>) => Promise<any>);
type GenerateScoreFunctionStep<TAccumulated extends Record<string, any>, TInput, TRunOutput> = ((context: StepContext<TAccumulated, TInput, TRunOutput>) => number | NotScorable) | ((context: StepContext<TAccumulated, TInput, TRunOutput>) => Promise<number | NotScorable>);
interface GenerateScorePromptObject<TAccumulated extends Record<string, any>, TInput, TRunOutput> {
description: string;
judge?: ScorerStepJudgeConfig;
createPrompt: (context: StepContext<TAccumulated, TInput, TRunOutput>) => string | Promise<string>;
}
interface GenerateReasonPromptObject<TAccumulated extends Record<string, any>, TInput, TRunOutput> {
description: string;
judge?: ScorerStepJudgeConfig;
createPrompt: (context: GenerateReasonContext<TAccumulated, TInput, TRunOutput>) => string | Promise<string>;
}
type PreprocessStepDef<TAccumulated extends Record<string, any>, TStepOutput, TInput, TRunOutput> = FunctionStep<TAccumulated, TInput, TRunOutput, TStepOutput> | (PromptObject<TStepOutput, TAccumulated, 'preprocess', TInput, TRunOutput> & {
outputSchema: PublicSchema<TStepOutput>;
});
type AnalyzeStepDef<TAccumulated extends Record<string, any>, TStepOutput, TInput, TRunOutput> = FunctionStep<TAccumulated, TInput, TRunOutput, TStepOutput> | (PromptObject<TStepOutput, TAccumulated, 'analyze', TInput, TRunOutput> & {
outputSchema: PublicSchema<TStepOutput>;
});
type GenerateScoreStepDef<TAccumulated extends Record<string, any>, TInput, TRunOutput> = GenerateScoreFunctionStep<TAccumulated, TInput, TRunOutput> | GenerateScorePromptObject<TAccumulated, TInput, TRunOutput>;
type GenerateReasonStepDef<TAccumulated extends Record<string, any>, TInput, TRunOutput> = GenerateReasonFunctionStep<TAccumulated, TInput, TRunOutput> | GenerateReasonPromptObject<TAccumulated, TInput, TRunOutput>;
declare class MastraScorer<TID extends string = string, TInput = any, TRunOutput = any, TAccumulatedResults extends Record<string, any> = {}> {
#private;
config: ScorerConfig<TID, TInput, TRunOutput>;
private steps;
private originalPromptObjects;
/**
* Tracks whether this scorer was defined in code or loaded from storage.
* Set by `Mastra.addScorer()` when the `source` option is provided.
*/
source?: DefinitionSource;
constructor(config: ScorerConfig<TID, TInput, TRunOutput>, steps?: Array<ScorerStepDefinition>, originalPromptObjects?: Map<string, PromptObject<any, any, any, TInput, TRunOutput> | GenerateReasonPromptObject<any, TInput, TRunOutput> | GenerateScorePromptObject<any, TInput, TRunOutput>>, mastra?: Mastra);
/**
* Registers the Mastra instance with the scorer.
* This enables access to custom gateways for model resolution.
* @internal
*/
__registerMastra(mastra: Mastra): void;
/**
* Returns the raw storage configuration this scorer was created from,
* or undefined if it was created from code.
*/
toRawConfig(): Record<string, unknown> | undefined;
/**
* Sets the raw storage configuration for this scorer.
* @internal
*/
__setRawConfig(rawConfig: Record<string, unknown>): void;
get type(): {
input: z.ZodSchema<TInput, unknown, z.core.$ZodTypeInternals<TInput, unknown>>;
output: z.ZodSchema<TRunOutput, unknown, z.core.$ZodTypeInternals<TRunOutput, unknown>>;
} | keyof ScorerTypeShortcuts | undefined;
get id(): TID;
get name(): string;
get description(): string;
get judge(): ScorerJudgeConfig | undefined;
preprocess<TPreprocessOutput>(stepDef: PreprocessStepDef<TAccumulatedResults, TPreprocessOutput, TInput, TRunOutput>): MastraScorer<TID, TInput, TRunOutput, AccumulatedResults<TAccumulatedResults, 'preprocess', Awaited<TPreprocessOutput>>>;
analyze<TAnalyzeOutput>(stepDef: AnalyzeStepDef<TAccumulatedResults, TAnalyzeOutput, TInput, TRunOutput>): MastraScorer<TID, TInput, TRunOutput, AccumulatedResults<TAccumulatedResults, 'analyze', Awaited<TAnalyzeOutput>>>;
generateScore<TScoreOutput extends number = number>(stepDef: GenerateScoreStepDef<TAccumulatedResults, TInput, TRunOutput>): MastraScorer<TID, TInput, TRunOutput, AccumulatedResults<TAccumulatedResults, 'generateScore', Awaited<TScoreOutput>>>;
generateReason<TReasonOutput = string>(stepDef: GenerateReasonStepDef<TAccumulatedResults, TInput, TRunOutput>): MastraScorer<TID, TInput, TRunOutput, AccumulatedResults<TAccumulatedResults, 'generateReason', Awaited<TReasonOutput>>>;
private get hasGenerateScore();
private normalizeRunRequestContext;
private mergeJudgeRequestContext;
/**
* Projects the run's RequestContext down to the keys that should be persisted
* on the scorer-run span input for repeatability.
*
* `serializeForSpan()` provides the safe base projection — reserved Mastra keys
* (auth token, internal plumbing) are omitted and values are shaped for the
* trace serializer to bound.
* `requestContextKeys` then selects from it:
* - omitted / empty → nothing is persisted (secure default)
* - `['*']` → the full (safe) context
* - specific keys → only those keys (dot notation for nested values)
*/
private selectRecordedRequestContext;
run(input: ScorerRun<TInput, TRunOutput>): Promise<ScorerRunResult<TAccumulatedResults, TInput, TRunOutput>>;
private isPromptObject;
getSteps(): Array<{
name: string;
type: ScorerStepType;
description?: string;
}>;
private toMastraWorkflow;
private createScorerContext;
private executeFunctionStep;
private executePromptStep;
private appendFailedJudgeExecution;
private getWorkflowFailureState;
private hasScorerResultFields;
private transformToScorerResult;
}
/**
* Creates a scorer builder for evaluating input/output pairs.
* Add a `generateScore` stage before running the scorer.
*
* @example
* ```typescript
* import { createScorer } from '@mastra/core/evals';
*
* const scorer = createScorer({
* id: 'response-presence',
* description: 'Check whether the agent produced any output messages.',
* type: 'agent',
* }).generateScore(({ run }) => (run.output.length > 0 ? 1 : 0));
* ```
*
* @see For documentation bundled with your installed package, locate
* `@mastra/core/package.json` with your project's resolver or package-manager
* tooling, then read `dist/docs/SKILL.md` from that package root and follow its
* reference links. Use package-manager tools for virtual or archived packages.
*
* @see [Scorer documentation](https://mastra.ai/reference/evals/create-scorer)
* if packaged docs are unavailable.
*/
export declare function createScorer<TID extends string, TType extends keyof ScorerTypeShortcuts>(config: Omit<ScorerConfig<TID, any, any>, 'type'> & {
type: TType;
}): MastraScorer<TID, ScorerTypeShortcuts[TType]['input'], ScorerTypeShortcuts[TType]['output'], {}>;
export declare function createScorer<TID extends string, TInputSchema extends z.ZodTypeAny, TOutputSchema extends z.ZodTypeAny>(config: Omit<ScorerConfig<TID, z.infer<TInputSchema>, z.infer<TOutputSchema>>, 'type'> & {
type: {
input: TInputSchema;
output: TOutputSchema;
};
}): MastraScorer<TID, z.infer<TInputSchema>, z.infer<TOutputSchema>, {}>;
export declare function createScorer<TInput = any, TRunOutput = any, TID extends string = string>(config: ScorerConfig<TID, TInput, TRunOutput>): MastraScorer<TID, TInput, TRunOutput, {}>;
export type MastraScorerEntry = {
scorer: MastraScorer<any, any, any, any>;
sampling?: ScoringSamplingConfig;
/**
* Declarative eligibility filter, evaluated before sampling (filter →
* sample): the sampling rate applies to qualifying traffic only. JSON-safe,
* so it survives durable-agent serialization. See `evals/predicate.ts`.
*/
filter?: ScoringFilter;
};
export type MastraScorers = Record<string, MastraScorerEntry>;
/**
* Known MastraMessagePart type values. Provides autocomplete for common types
* while still allowing arbitrary `data-*` strings via the `string & {}` escape hatch.
*/
export type MastraPartType = 'text' | 'tool-invocation' | 'step-start' | 'reasoning' | 'image' | 'file' | 'source' | 'source-document' | 'data-' | 'data-om-' | 'data-om-status' | 'data-om-observation-start' | 'data-om-observation-end' | 'data-om-observation-failed' | 'data-om-buffering-start' | 'data-om-buffering-end' | 'data-om-buffering-failed' | 'data-om-activation' | 'data-om-thread-update' | 'data-workspace-' | 'data-workspace-metadata' | 'data-sandbox-' | 'data-sandbox-stdout' | 'data-sandbox-stderr' | 'data-sandbox-exit' | 'data-sandbox-command' | 'data-tool-' | 'data-tool-call-approval' | 'data-tool-call-suspended' | 'data-system-reminder' | 'data-signal' | 'data-user-message' | 'data-tripwire' | 'data-structured-output' | (string & {});
export interface FilterRunOptions {
/**
* Keep only messages whose parts match these MastraMessagePart type patterns.
* Applied to both `input.rememberedMessages` and `output` when they contain
* MastraDBMessage arrays (the `type: 'agent'` scorer shape).
*
* Each entry is prefix-matched against `MastraMessagePart.type`:
* - `'text'` — text parts
* - `'tool-invocation'` — tool invocation parts
* - `'step-start'` — step markers
* - `'data-'` — all data parts (OM, workspace, sandbox, etc.)
* - `'data-om-'` — only observational memory data parts
*
* Messages where no part matches are dropped. Plain text messages (user text,
* assistant text without tool parts) are always kept regardless of this filter.
*
* To filter by specific tool names, use `toolNames` instead.
*/
partTypes?: MastraPartType[];
/**
* Keep only tool-invocation messages for these specific tools.
* Each entry is prefix-matched against `toolInvocation.toolName`.
* Non-tool messages (text, data) are unaffected by this filter.
*
* @example `['execute_command', 'write_file', 'string_replace']`
*/
toolNames?: string[];
/**
* Maximum number of messages to keep in `input.rememberedMessages`.
* Taken from the end (most recent messages). Useful for limiting context window.
*/
maxRememberedMessages?: number;
/**
* Maximum number of messages to keep in `output` (response messages).
* Taken from the end.
*/
maxOutputMessages?: number;
/**
* Drop `requestContext` entirely from the run.
*/
dropRequestContext?: boolean;
/**
* Drop `expectedTrajectory` from the run.
*/
dropExpectedTrajectory?: boolean;
/**
* Drop `groundTruth` from the run.
*/
dropGroundTruth?: boolean;
}
/**
* Creates a `prepareRun` function from declarative options.
* Use this with `createScorer({ prepareRun: filterRun({ ... }) })`.
*
* @example
* ```ts
* createScorer({
* id: 'my-scorer',
* description: '...',
* type: 'agent',
* prepareRun: filterRun({
* toolNames: ['execute_command', 'write_file', 'string_replace_lsp'],
* maxRememberedMessages: 20,
* }),
* })
* ```
*/
export declare function filterRun<TInput = unknown, TOutput = unknown>(options: FilterRunOptions): (run: ScorerRun<TInput, TOutput>) => ScorerRun<TInput, TOutput>;
export type { ScorerConfig, ScorerRun, ScorerTypeShortcuts, StepContext, PromptObject };
export { MastraScorer };
//# sourceMappingURL=base.d.ts.map