import type { AgentExecutionOptions, AgentExecutionOptionsBase, MultiPrimitiveExecutionOptions, AgentGenerateOptions, AgentStreamOptions, SerializableStructuredOutputOptions, ToolsInput, UIMessageWithMetadata, AgentInstructions, AgentEditorConfig } from '@mastra/core/agent'; import type { MessageListInput } from '@mastra/core/agent/message-list'; import type { BuilderModelPolicy, DefaultModelEntry, ProviderModelEntry } from '@mastra/core/agent-builder/ee'; import type { ScoreRowData } from '@mastra/core/evals'; import type { CoreMessage, Provider as ModelProviderId } from '@mastra/core/llm'; import type { AiMessageType, MastraMessageV1, MastraDBMessage, MemoryConfig, StorageThreadType } from '@mastra/core/memory'; import type { TracingOptions } from '@mastra/core/observability'; import type { RequestContext } from '@mastra/core/request-context'; import type { AgentInstructionBlock, PaginationInfo, WorkflowRuns, Rule, RuleGroup, StorageConditionalVariant, StorageConditionalField, StoredProcessorGraph } from '@mastra/core/storage'; import type { ChunkType, ThreadHistoryChunk, ThreadRunStatusChunk } from '@mastra/core/stream'; import type { QueryResult } from '@mastra/core/vector'; import type { SerializedStepFlowEntry, WorkflowResult, WorkflowRunStatus, WorkflowState } from '@mastra/core/workflows'; import type { PublicSchema } from '@mastra/schema-compat/schema'; import type { JSONSchema7 } from 'json-schema'; import type { ZodSchema as ZodSchemaV3 } from 'zod/v3'; import type { ZodType as ZodTypeV4 } from 'zod/v4'; import type { Body, PathParams, QueryParams, RouteKey, RouteResponse, Simplify } from './route-types.generated.js'; import type { JSONValue, ToolInvocationUIPart } from './utils/ai-sdk-v4/index.js'; export type ZodSchema = ZodSchemaV3 | ZodTypeV4; /** * Provider metadata as it travels on a message part: a two-level map of * provider namespace -> key -> value (e.g. `{ vertex: { thoughtSignature: '...' } }`). */ export type PartProviderMetadata = Record>; /** Stream chunk payloads may carry provider metadata; the AI SDK payload types don't declare it. */ export type MaybeProviderMetadata = { providerMetadata?: PartProviderMetadata; }; /** * `ToolInvocationUIPart` from the AI SDK v4 UI types has no `providerMetadata` field, but the * server reads provider metadata from the part itself (not from the nested `toolInvocation`), * so the SDK has to be able to set it there. */ export type ToolInvocationUIPartWithMeta = ToolInvocationUIPart & MaybeProviderMetadata; type OptionalizeUndefined = T extends Date ? Date : T extends (...args: any[]) => any ? T : T extends readonly (infer U)[] ? OptionalizeUndefined[] : T extends object ? Simplify<{ [K in keyof T as undefined extends T[K] ? never : K]: OptionalizeUndefined; } & { [K in keyof T as undefined extends T[K] ? K : never]?: OptionalizeUndefined>; }> : T; /** A server payload type as it arrives over JSON: `Date` fields become ISO strings. */ export type Serialized = T extends Date ? string : T extends readonly (infer U)[] ? Serialized[] : T extends object ? { [K in keyof T]: Serialized; } : T; type RequestContextOptions = { requestContext?: RequestContext | Record; }; type GeneratedRequest = OptionalizeUndefined; type GeneratedResponse = Serialized>; export type SerializedRouteResponse = GeneratedResponse; type WithoutIndexSignatures = { [K in keyof T as string extends K ? never : number extends K ? never : symbol extends K ? never : K]: T[K]; }; export type GetScoreResponse = GeneratedResponse<'GET /observability/scores/:scoreId'>; export type GetFeedbackResponse = GeneratedResponse<'GET /observability/feedback/:feedbackId'>; export type ListFeedbackResponse = GeneratedResponse<'GET /observability/feedback'>; export type FeedbackItem = ListFeedbackResponse['feedback'][number]; export type GetMetricTimeSeriesResponse = GeneratedResponse<'POST /observability/metrics/timeseries'>; export interface ClientOptions { /** Base URL for API requests */ baseUrl: string; /** API route prefix. Defaults to '/api'. Set this to match your server's apiPrefix configuration. */ apiPrefix?: string; /** * Number of retry attempts for failed requests. Defaults to 3 for read requests * (GET, HEAD, OPTIONS). Write requests (POST, PUT, PATCH, DELETE) are not retried * unless this or a per-request `retries` count is set, so a failed attempt cannot * repeat a state-changing request. */ retries?: number; /** Initial backoff time in milliseconds between retries */ backoffMs?: number; /** Maximum backoff time in milliseconds between retries */ maxBackoffMs?: number; /** Custom headers to include with requests */ headers?: Record; /** Abort signal for request */ abortSignal?: AbortSignal; /** Credentials mode for requests. See https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials for more info. */ credentials?: 'omit' | 'same-origin' | 'include'; /** Custom fetch function to use for HTTP requests. Useful for environments like Tauri that require custom fetch implementations. */ fetch?: typeof fetch; } export type AgentVersionIdentifier = { versionId: string; } | { status: 'draft' | 'published'; }; export type AgentSignalActiveBehavior = 'deliver' | 'persist' | 'discard'; export type AgentSignalIdleBehavior = 'wake' | 'persist' | 'discard'; export type SendAgentSignalParams = GeneratedRequest>; export type SendAgentMessageParams = GeneratedRequest>; export type QueueAgentMessageParams = GeneratedRequest>; export type QueueAgentSignalParams = GeneratedRequest>; export interface SubscribeAgentThreadParams { resourceId?: string; threadId: string; /** * Emit one `thread-history` chunk with the stored thread messages before any * run parts; parts already covered by that history are not replayed. */ withInitialHistory?: boolean | { perPage?: number; }; /** Emit thread-run-status chunks, including retained outcomes. Defaults to false. */ withRunStatus?: boolean; } export type AbortAgentThreadParams = GeneratedRequest>; /** Cancels pending signals on the server process handling the request. */ export type CancelQueuedAgentMessagesParams = GeneratedRequest>; export type CancelQueuedAgentMessagesResponse = GeneratedResponse<'POST /agents/:agentId/threads/signals/cancel'>; export type ListAgentSuspendedRunsParams = GeneratedRequest>; /** * Listed suspended runs as returned by `agent.listSuspendedRuns()`. * Date fields (e.g. `suspendedAt`) are ISO strings over the wire, matching * the rest of the client SDK. */ export type ListAgentSuspendedRunsResponse = GeneratedResponse<'GET /agents/:agentId/suspended-runs'>; export type GetAgentPlanResponse = GeneratedResponse<'GET /agents/:agentId/plans/file'>; export type AgentSuspendedRun = ListAgentSuspendedRunsResponse['runs'][number]; export type AgentSuspendedRunToolCall = AgentSuspendedRun['toolCalls'][number]; export interface ProcessAgentThreadStreamOptions { /** Receives history and run status chunks only when requested by the subscription. */ onChunk: (chunk: ChunkType | ThreadHistoryChunk | (WITH_RUN_STATUS extends true ? ThreadRunStatusChunk : never)) => void | Promise; reconnect?: boolean | { /** Maximum reconnect attempts after the initial stream ends or errors. Defaults to Infinity. */ maxRetries?: number; /** Delay between reconnect attempts in milliseconds. Defaults to 1000. */ delayMs?: number; }; } export interface RequestOptions { method?: string; headers?: Record; body?: any; stream?: boolean; /** * Overrides the client's configured retry count for this request. Also opts a write * request (POST, PUT, PATCH, DELETE) back into retrying, since writes are not retried * by default. */ retries?: number; /** Per-request abort signal. Merged with the client-wide `abortSignal` from `ClientOptions`. */ signal?: AbortSignal; /** Credentials mode for requests. See https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials for more info. */ credentials?: 'omit' | 'same-origin' | 'include'; } type ResponseInput = Body<'POST /v1/responses'>['input']; type ResponseInputMessageFromRoute = Exclude[number]; type ResponsePayload = GeneratedResponse<'POST /v1/responses'>; export type ResponseInputTextPart = Exclude[number]; export type ResponseInputMessage = ResponseInputMessageFromRoute; export type ResponseTextConfig = NonNullable['text']>; export type ResponseTextFormat = ResponseTextConfig['format']; export type ResponseOutputItem = ResponsePayload['output'][number]; export type ResponseOutputMessage = Extract; export type ResponseOutputText = ResponseOutputMessage['content'][number]; export type ResponseOutputFunctionCall = Extract; export type ResponseOutputFunctionCallOutput = Extract; export type ResponseUsage = NonNullable; export type ResponseTool = NonNullable[number]; export type ConversationItem = GeneratedResponse<'GET /v1/conversations/:conversationId/items'>['data'][number]; export type ConversationItemMessage = Extract; export type ConversationItemInputText = Extract; export type ConversationItemsPage = GeneratedResponse<'GET /v1/conversations/:conversationId/items'>; /** Response payload augmented by the SDK with concatenated message text. */ export type ResponsesResponse = ResponsePayload & { output_text: string; }; export type ResponsesDeleteResponse = GeneratedResponse<'DELETE /v1/responses/:responseId'>; export type CreateResponseParams = GeneratedRequest>> & RequestContextOptions; export type Conversation = GeneratedResponse<'POST /v1/conversations'>; export type ConversationDeleted = GeneratedResponse<'DELETE /v1/conversations/:conversationId'>; export type CreateConversationParams = GeneratedRequest> & RequestContextOptions; export type ResponsesCreatedEvent = { type: 'response.created'; response: ResponsesResponse; sequence_number?: number; }; export type ResponsesInProgressEvent = { type: 'response.in_progress'; response: ResponsesResponse; sequence_number?: number; }; export type ResponsesOutputItemAddedEvent = { type: 'response.output_item.added'; output_index: number; item: ResponseOutputItem; sequence_number?: number; }; export type ResponsesContentPartAddedEvent = { type: 'response.content_part.added'; output_index: number; content_index: number; item_id: string; part: ResponseOutputText; sequence_number?: number; }; export type ResponsesOutputTextDeltaEvent = { type: 'response.output_text.delta'; output_index: number; content_index: number; item_id: string; delta: string; sequence_number?: number; }; export type ResponsesOutputTextDoneEvent = { type: 'response.output_text.done'; output_index: number; content_index: number; item_id: string; text: string; sequence_number?: number; }; export type ResponsesContentPartDoneEvent = { type: 'response.content_part.done'; output_index: number; content_index: number; item_id: string; part: ResponseOutputText; sequence_number?: number; }; export type ResponsesOutputItemDoneEvent = { type: 'response.output_item.done'; output_index: number; item: ResponseOutputItem; sequence_number?: number; }; export type ResponsesFunctionCallArgumentsDeltaEvent = { type: 'response.function_call_arguments.delta'; output_index: number; item_id: string; delta: string; sequence_number?: number; }; export type ResponsesFunctionCallArgumentsDoneEvent = { type: 'response.function_call_arguments.done'; output_index: number; item_id: string; name: string; arguments: string; sequence_number?: number; }; export type ResponsesCompletedEvent = { type: 'response.completed'; response: ResponsesResponse; sequence_number?: number; }; export type ResponsesStreamEvent = ResponsesCreatedEvent | ResponsesInProgressEvent | ResponsesOutputItemAddedEvent | ResponsesContentPartAddedEvent | ResponsesOutputTextDeltaEvent | ResponsesOutputTextDoneEvent | ResponsesContentPartDoneEvent | ResponsesOutputItemDoneEvent | ResponsesFunctionCallArgumentsDeltaEvent | ResponsesFunctionCallArgumentsDoneEvent | ResponsesCompletedEvent; type WithoutMethods = { [K in keyof T as T[K] extends (...args: any[]) => any ? never : T[K] extends { (): any; } ? never : T[K] extends undefined | ((...args: any[]) => any) ? never : K]: T[K]; }; export type NetworkStreamParams = { messages: MessageListInput; model?: string; tracingOptions?: TracingOptions; } & Omit, 'model' | 'scopes'>; export type GetAgentResponse = GeneratedResponse<'GET /agents/:agentId'> & { /** Handler-provided identifier omitted from the serialized route schema's value shape. */ id: string; instructions: AgentInstructions; tools: Record; workflows: Record; agents: Record; skills?: SkillMetadata[]; workspaceTools?: string[]; browserTools?: string[]; hasBrowser?: boolean; workspaceId?: string; defaultOptions: WithoutMethods; defaultGenerateOptionsLegacy: WithoutMethods; defaultStreamOptionsLegacy: WithoutMethods; requestContextSchema?: string; editor?: AgentEditorConfig; }; /** * Response from the deployer-provided browser session probe endpoint. * * This route is registered dynamically by deployer adapters rather than the * server route registry, so it has no generated contract. Use it to decide * whether to open a screencast WebSocket for an agent/thread: * - `screencastAvailable`: server has the `ws` / `@hono/node-ws` packages installed. * When false, opening a WS will fail and trigger a reconnect loop — skip it. * - `hasSession`: the agent has an active browser session for this thread. When * false, the WS would just sit idle waiting for the agent to invoke a tool. */ export interface GetAgentBrowserSessionResponse { hasSession: boolean; screencastAvailable: boolean; } export type ClientToolsResolver = () => ToolsInput | undefined; export type GenerateLegacyParams = { messages: string | string[] | CoreMessage[] | AiMessageType[] | UIMessageWithMetadata[]; model?: string; output?: T; experimental_output?: T; requestContext?: RequestContext | Record; clientTools?: ToolsInput; clientToolsResolver?: ClientToolsResolver; } & WithoutMethods, 'model' | 'output' | 'experimental_output' | 'requestContext' | 'clientTools'>>; export type StreamLegacyParams = { messages: string | string[] | CoreMessage[] | AiMessageType[] | UIMessageWithMetadata[]; model?: string; output?: T; experimental_output?: T; requestContext?: RequestContext | Record; clientTools?: ToolsInput; clientToolsResolver?: ClientToolsResolver; } & WithoutMethods, 'model' | 'output' | 'experimental_output' | 'requestContext' | 'clientTools'>>; export type StructuredOutputOptions = Omit, 'schema'> & { schema: PublicSchema; }; export type StreamParamsBase = { model?: string; tracingOptions?: TracingOptions; requestContext?: RequestContext | Record; clientTools?: ToolsInput; clientToolsResolver?: ClientToolsResolver; /** * Per-call abort signal. Aborting it (or cancelling the returned stream) aborts the * underlying request and stops any client-tool continuations. */ abortSignal?: AbortSignal; } & WithoutMethods, 'model' | 'requestContext' | 'clientTools' | 'options' | 'scopes'>>; export type StreamParamsBaseWithoutMessages = StreamParamsBase; export type StreamParams = StreamParamsBase & { messages: MessageListInput; } & (OUTPUT extends undefined ? { structuredOutput?: never; } : { structuredOutput: StructuredOutputOptions; }); /** * Provider id widened to accept admin-configured custom gateway providers. * Closed unions over the five hard-coded providers are removed in favor of the * generated `ModelProviderId` union plus a `(string & {})` escape hatch — this * preserves IDE autocomplete on known providers while letting custom gateway * ids flow through (see Phase 1 of the admin model configuration plan). */ export type AdminProviderId = ModelProviderId | (string & {}); export type UpdateModelParams = GeneratedRequest>; export type UpdateModelInModelListParams = Omit, 'agentId'> & GeneratedRequest>; export type ReorderModelListParams = GeneratedRequest>; export type GetToolResponse = GeneratedResponse<'GET /tools/:toolId'>; /** Query contract with the SDK's legacy `false` sentinel for `limit`. */ export type ListWorkflowRunsParams = Omit>, 'limit'> & { limit?: number | false; }; type WorkflowRunsRouteResponse = SerializedRouteResponse<'GET /workflows/:workflowId/runs'>; type WorkflowRunSnapshot = WorkflowRuns['runs'][number]['snapshot']; export type ListWorkflowRunsResponse = Omit & { runs: Array & { snapshot: WorkflowRunSnapshot; }>; }; export type WorkflowRunCounts = GeneratedResponse<'GET /workflows/run-counts'>[string]; export type ListWorkflowRunCountsResponse = GeneratedResponse<'GET /workflows/run-counts'>; export type GetWorkflowRunByIdResponse = Omit, 'serializedStepGraph'> & Omit, 'serializedStepGraph'> & Pick; export type ListDynamicWorkflowsParams = GeneratedRequest>; export type ListDynamicWorkflowsResponse = GeneratedResponse<'GET /stored/workflows'>; export type UpsertDynamicWorkflowParams = GeneratedRequest>; export type UpsertDynamicWorkflowResponse = GeneratedResponse<'POST /stored/workflows'>; type DynamicWorkflowDefinitionField = 'description' | 'inputSchema' | 'outputSchema' | 'stateSchema' | 'requestContextSchema' | 'graph'; export type DynamicWorkflowDefinition = Omit, DynamicWorkflowDefinitionField> & Pick; export type DeleteDynamicWorkflowResponse = GeneratedResponse<'DELETE /stored/workflows/:dynamicWorkflowId'>; export type GetWorkflowResponse = Omit, 'name' | 'stepGraph'> & { name: string; stepGraph?: SerializedStepFlowEntry[]; requestContextSchema?: string; }; export type WorkflowRunResult = WorkflowResult; export type UpsertVectorParams = GeneratedRequest>; export type CreateIndexParams = GeneratedRequest>; export type QueryVectorParams = GeneratedRequest>; /** The server schema currently represents vector-store-specific result rows as `unknown`. */ export type QueryVectorResponse = GeneratedResponse<'POST /vector/:vectorName/query'> & QueryResult[]; export type GetVectorIndexResponse = GeneratedResponse<'GET /vector/:vectorName/indexes/:indexName'>; export type SaveMessageToMemoryParams = GeneratedRequest & QueryParams<'POST /memory/save-messages'>> & RequestContextOptions & { messages: (MastraMessageV1 | MastraDBMessage)[]; }; export type SaveNetworkMessageToMemoryParams = GeneratedRequest & QueryParams<'POST /memory/network/save-messages'>> & { messages: (MastraMessageV1 | MastraDBMessage)[]; }; /** The server schema currently represents persisted message payloads as `unknown`. */ export type SaveMessageToMemoryResponse = GeneratedResponse<'POST /memory/save-messages'> & { messages: (MastraMessageV1 | MastraDBMessage)[]; }; export type CreateMemoryThreadParams = GeneratedRequest & QueryParams<'POST /memory/threads'>> & RequestContextOptions; export type CreateMemoryThreadResponse = GeneratedResponse<'POST /memory/threads'>; export type ListMemoryThreadsParams = GeneratedRequest> & RequestContextOptions; export type ListMemoryThreadsResponse = GeneratedResponse<'GET /memory/threads'>; export type GetMemoryConfigParams = GeneratedRequest> & RequestContextOptions; export type GetMemoryConfigResponse = GeneratedResponse<'GET /memory/config'>; export type UpdateMemoryThreadParams = Omit & QueryParams<'PATCH /memory/threads/:threadId'>>, 'agentId'> & RequestContextOptions & { /** Resolved from the resource constructor when omitted. */ agentId?: string; }; export type ListMemoryThreadMessagesParams = GeneratedRequest> & RequestContextOptions & { /** Optional network ID. When provided, uses the network memory endpoint. */ networkId?: string; }; /** The route schema intentionally keeps persisted message payloads opaque. */ export type ListMemoryThreadMessagesResponse = GeneratedResponse<'GET /memory/threads/:threadId/messages'> & { messages: MastraDBMessage[]; }; export type CloneMemoryThreadParams = Omit & QueryParams<'POST /memory/threads/:threadId/clone'>>, 'agentId'> & RequestContextOptions & { /** Resolved from the resource constructor when omitted. */ agentId?: string; }; /** The route schema intentionally keeps cloned persisted message payloads opaque. */ export type CloneMemoryThreadResponse = GeneratedResponse<'POST /memory/threads/:threadId/clone'> & { thread: StorageThreadType; clonedMessages: MastraDBMessage[]; }; export type TransferMemoryThreadParams = GeneratedRequest & QueryParams<'POST /memory/threads/:threadId/transfer'>> & RequestContextOptions; export type GetLogsParams = GeneratedRequest>; export type GetLogParams = Omit & GeneratedRequest>, 'fromDate' | 'toDate'> & { /** SDK convenience inputs serialized to the route's ISO date query values. */ fromDate?: Date; toDate?: Date; }; export type GetLogsResponse = GeneratedResponse<'GET /logs'>; export type RequestFunction = (path: string, options?: RequestOptions) => Promise; export interface GetVNextNetworkResponse { id: string; name: string; instructions: string; agents: Array<{ name: string; provider: string; modelId: string; }>; routingModel: { provider: string; modelId: string; }; workflows: Array<{ name: string; description: string; inputSchema: string | undefined; outputSchema: string | undefined; }>; tools: Array<{ id: string; description: string; }>; } export interface GenerateVNextNetworkResponse { task: string; result: string; resourceId: string; resourceType: 'none' | 'tool' | 'agent' | 'workflow'; } export interface GenerateOrStreamVNextNetworkParams { message: string; threadId?: string; resourceId?: string; requestContext?: RequestContext | Record; } export interface LoopStreamVNextNetworkParams { message: string; threadId?: string; resourceId?: string; maxIterations?: number; requestContext?: RequestContext | Record; } export interface LoopVNextNetworkResponse { status: 'success'; result: { task: string; resourceId: string; resourceType: 'agent' | 'workflow' | 'none' | 'tool'; result: string; iteration: number; isOneOff: boolean; prompt: string; threadId?: string | undefined; threadResourceId?: string | undefined; isComplete?: boolean | undefined; completionReason?: string | undefined; }; steps: WorkflowResult['steps']; } export type McpServerListResponse = GeneratedResponse<'GET /mcp/v0/servers'>; /** The built-in Mastra MCP server (`server.mcp`) as described by `GET /mcp/builtin`. */ export type GetBuiltinMcpServerResponse = GeneratedResponse<'GET /mcp/builtin'>; /** MCP server registry entry plus the transports served under `/mcp/:serverId`. */ export type McpServerInfo = McpServerListResponse['servers'][number]; export type McpServerDetailInfo = GeneratedResponse<'GET /mcp/v0/servers/:id'>; /** Protocol transports the Mastra server exposes for a registered MCP server. */ export type McpServerTransport = NonNullable[number]; export type McpToolInfo = GeneratedResponse<'GET /mcp/:serverId/tools/:toolId'>; export type McpServerToolListResponse = GeneratedResponse<'GET /mcp/:serverId/tools'>; /** * `{ result }` for a completed tool, or the suspended shape a 2026-07-28 server reports * when the tool asked for input (answer with `resumeData` and the echoed `suspendPayload`). */ export type McpToolExecuteResponse = RouteResponse<'POST /mcp/:serverId/tools/:toolId/execute'>; /** Event types an MCP server declares, plus whether test emit is served (experimental). */ export type McpServerEventListResponse = GeneratedResponse<'GET /mcp/:serverId/events'>; /** One declared MCP server event type (experimental). */ export type McpServerEventInfo = McpServerEventListResponse['events'][number]; /** Result of polling an MCP server event type (experimental). */ export type McpServerEventPollResponse = GeneratedResponse<'POST /mcp/:serverId/events/:eventName/poll'>; /** One occurrence of an MCP server event (experimental). */ export type McpServerEventOccurrence = McpServerEventPollResponse['events'][number]; /** A frame yielded by `streamMcpServerEvent` (experimental). */ export type McpServerEventStreamFrame = GeneratedResponse<'POST /mcp/:serverId/events/:eventName/stream'>; /** Task surfaces of an MCP server and its recent tasks across principals (experimental). */ export type McpServerTaskListResponse = GeneratedResponse<'GET /mcp/:serverId/tasks'>; /** A tool, workflow or agent an MCP server runs as a task (experimental). */ export type McpServerTaskSurface = McpServerTaskListResponse['surfaces'][number]; /** * One MCP server task as Studio sees it: identified by `taskKey` (a hash of the task id) and a * hashed principal, never by the task id itself (experimental). */ export type McpServerTask = McpServerTaskListResponse['tasks'][number]; /** Answers to a task's open input requests, keyed by request (experimental). */ export type McpServerTaskInputResponses = Body<'POST /mcp/:serverId/tasks/:taskKey/input'>['inputResponses']; /** * Client version of ScoreRowData with dates serialized as strings (from JSON) */ export type ClientScoreRowData = Omit & { createdAt: string; updatedAt: string | null; }; /** * Response for listing scores (client version with serialized dates) */ export type ListScoresResponse = { pagination: PaginationInfo; scores: ClientScoreRowData[]; }; export type ListScoresByRunIdParams = GeneratedRequest & QueryParams<'GET /scores/run/:runId'>>; export type ListScoresByScorerIdParams = GeneratedRequest & QueryParams<'GET /scores/scorer/:scorerId'>>; export type ListScoresByEntityIdParams = GeneratedRequest & QueryParams<'GET /scores/entity/:entityType/:entityId'>>; /** Score records remain opaque in the route schema because their shape is scorer-specific. */ export type SaveScoreParams = GeneratedRequest> & { score: Omit; }; /** Score records remain opaque in the route schema because their shape is scorer-specific. */ export type SaveScoreResponse = GeneratedResponse<'POST /scores'> & { score: ClientScoreRowData; }; export type GetScorerResponse = GeneratedResponse<'GET /scores/scorers/:scorerId'>; export type GetScorersResponse = GeneratedResponse<'GET /scores/scorers'>; export interface TemplateInstallationRequest { /** Template repository URL or slug */ repo: string; /** Git ref (branch/tag/commit) to install from */ ref?: string; /** Template slug for identification */ slug?: string; /** Target project path */ targetPath?: string; /** Environment variables for template */ variables?: Record; } export interface StreamVNextChunkType { type: string; payload: any; runId: string; from: 'AGENT' | 'WORKFLOW'; } export interface MemorySearchResponse { results: MemorySearchResult[]; count: number; query: string; searchType?: string; searchScope?: 'thread' | 'resource'; } export interface MemorySearchResult { id: string; role: string; content: string; createdAt: string; threadId?: string; threadTitle?: string; context?: { before?: Array<{ id: string; role: string; content: string; createdAt: string; }>; after?: Array<{ id: string; role: string; content: string; createdAt: string; }>; }; } export type TimeTravelParams = Omit, 'requestContext'> & { requestContext?: RequestContext | Record; }; /** * Semantic recall configuration for vector-based memory retrieval */ export interface SemanticRecallConfig { topK: number; messageRange: number | { before: number; after: number; }; scope?: 'thread' | 'resource'; threshold?: number; indexName?: string; } /** * Title generation configuration */ export type TitleGenerationConfig = boolean | { model?: string; instructions?: string; /** Minimum number of thread messages required before a title is generated */ minMessages?: number; /** Emit the generated title as a transient `data-thread-title` chunk on the run stream, before `finish` */ emitEvent?: boolean; }; /** * Serialized memory configuration matching SerializedMemoryConfig from @mastra/core * * Note: When semanticRecall is enabled, both `vector` (string, not false) and `embedder` must be configured. */ /** Serializable observation step config for observational memory */ export interface SerializedObservationConfig { model?: string; messageTokens?: number; modelSettings?: Record; providerOptions?: Record | undefined>; maxTokensPerBatch?: number; bufferTokens?: number | false; bufferActivation?: number; blockAfter?: number; } /** Serializable reflection step config for observational memory */ export interface SerializedReflectionConfig { model?: string; observationTokens?: number; modelSettings?: Record; providerOptions?: Record | undefined>; blockAfter?: number; bufferActivation?: number; } /** Serializable observational memory configuration */ export interface SerializedObservationalMemoryConfig { model?: string; scope?: 'resource' | 'thread'; shareTokenBudget?: boolean; observation?: SerializedObservationConfig; reflection?: SerializedReflectionConfig; } export interface SerializedMemoryConfig { /** * Vector database identifier. Required when semanticRecall is enabled. * Set to false to explicitly disable vector search. */ vector?: string | false; options?: { readOnly?: boolean; lastMessages?: number | false; /** * Semantic recall configuration. When enabled (true or object), * requires both `vector` and `embedder` to be configured. */ semanticRecall?: boolean | SemanticRecallConfig; generateTitle?: TitleGenerationConfig; }; /** * Embedding model ID in the format "provider/model" * (e.g., "openai/text-embedding-3-small") * Required when semanticRecall is enabled. */ embedder?: string; /** * Options to pass to the embedder */ embedderOptions?: Record; /** * Serialized observational memory configuration. * `true` to enable with defaults, or a config object for customization. */ observationalMemory?: boolean | SerializedObservationalMemoryConfig; } /** * Stored-agent memory: a reference to a Memory instance registered on Mastra * (by registry key, falling back to the instance id), an explicitly tagged * inline config, or a legacy untagged inline config. */ export type StoredMemoryRef = { type: 'id'; memoryId: string; } | { type: 'inline'; config: SerializedMemoryConfig; } | SerializedMemoryConfig; /** * Default options for agent execution (serializable subset of AgentExecutionOptionsBase) */ export interface DefaultOptions { runId?: string; savePerStep?: boolean; maxSteps?: number; activeTools?: string[]; maxProcessorRetries?: number; toolChoice?: 'auto' | 'none' | 'required' | { type: 'tool'; toolName: string; }; modelSettings?: { temperature?: number; maxTokens?: number; topP?: number; topK?: number; frequencyPenalty?: number; presencePenalty?: number; stopSequences?: string[]; seed?: number; maxRetries?: number; }; returnScorerData?: boolean; tracingOptions?: { traceName?: string; attributes?: Record; spanId?: string; traceId?: string; }; requireToolApproval?: boolean; autoResumeSuspendedTools?: boolean; toolCallConcurrency?: number; includeRawChunks?: boolean; [key: string]: unknown; } /** * Per-tool config for stored agents (e.g., description overrides) */ export interface StoredAgentToolConfig { description?: string; rules?: RuleGroup; } /** * Per-MCP-client/integration tool configuration stored in agent snapshots. * Specifies which tools from an MCP client or integration provider are enabled and their overrides. * An empty `tools` map (`{}`) includes all tools from the source. * When `tools` is omitted, no tools are included. */ export interface StoredMCPClientToolsConfig { /** `{}` includes all tools from the source; when omitted, no tools are included. */ tools?: Record; } /** * One pinned connection on a `toolProviders[providerId].connections[toolkit]` bucket. * Part of the Agent Builder / CMS tool-providers shape * (`StoredAgentSnapshot.toolProviders`). */ export interface StoredToolProviderConnection { /** * Identity binding kind. * * - `'author'` — uses the agent author's connection (v1 default). * - `'invoker'` — uses the end-user's connection (v1.5, reserved). * - `'platform'` — uses a shared platform account (v2, reserved). */ kind: 'author' | 'invoker' | 'platform'; /** Parent toolkit slug. Denormalized for callsite clarity. */ toolkit: string; /** * Provider-opaque identifier for the OAuth bucket. * * Required for `'author'` and `'platform'`; reserved (empty) for `'invoker'`. */ connectionId: string; /** * Display label and LLM disambiguator. Optional when this is the only * connection on a `toolkit`; required (non-empty, ≤ 32 chars, * `[A-Za-z0-9 _-]+`, case-insensitively unique) once ≥ 2 connections share * the same `toolkit`. */ label?: string; /** * Ownership scope of the underlying OAuth bucket. * * - `'per-author'` (default) — bucketed under the agent author's id. * - `'shared'` — bucketed under a constant shared id; visible to and * usable by anyone with edit access. * - `'caller-supplied'` — bucketed under the request-context * `MASTRA_RESOURCE_ID_KEY` value at runtime. Used for multi-tenant * deployments where the host app sets the user id per request. */ scope?: 'per-author' | 'shared' | 'caller-supplied'; } /** Per-tool override stored alongside the selected tool slug. */ export interface StoredToolProviderToolMeta { /** * Toolkit this slug belongs to. The runtime groups selected slugs * by this field when fanning out across connections. */ toolkit?: string; description?: string; } /** Stored shape for one tool provider's configuration on one agent. */ export interface StoredToolProviderConfig { tools: Record; connections: Record; } /** * Scorer config for stored agents */ export interface StoredAgentScorerConfig { description?: string; sampling?: { type: 'none'; } | { type: 'ratio'; rate: number; }; rules?: RuleGroup; } /** * Per-skill config stored in agent snapshots. * Allows overriding skill description and instructions for a specific agent context. */ export interface StoredAgentSkillConfig { description?: string; instructions?: string; /** Pin to a specific version ID. Takes precedence over strategy. */ pin?: string; /** Resolution strategy: 'latest' = latest published version, 'live' = read from filesystem */ strategy?: 'latest' | 'live'; } export type StoredWorkspaceRef = Extract>['workspace']>, { type: 'id' | 'inline' | 'provider'; }>; export interface StoredBrowserConfig { provider: string; headless?: boolean; viewport?: { width: number; height: number; }; timeout?: number; screencast?: { format?: 'jpeg' | 'png'; quality?: number; maxWidth?: number; maxHeight?: number; everyNthFrame?: number; }; } export type StoredBrowserRef = { type: 'inline'; config: StoredBrowserConfig; }; export type StoredAgentRule = Rule; export type StoredAgentRuleGroup = RuleGroup; export type ConditionalVariant = StorageConditionalVariant; export type ConditionalField = StorageConditionalField; /** * Resolved author identity. Returned by the server when an auth provider is * configured and the agent's `authorId` could be looked up. All fields except * `id` are optional — providers may not expose every field. */ export interface ResolvedAuthor { id: string; name?: string; email?: string; avatarUrl?: string; } /** * Serializable durable-execution opt-in for a stored agent. * * `cache` and `pubsub` are live runtime objects and cannot be sent over the API — * the server inherits them from its Mastra instance. */ export type StoredAgentDurableConfig = boolean | { /** Maximum steps for the durable agentic loop. */ maxSteps?: number; /** Auto-cleanup timer for durable stream state (ms). `0` disables cleanup. */ cleanupTimeoutMs?: number; }; /** * Stored agent data returned from API */ export type StoredAgentResponse = GeneratedResponse<'GET /stored/agents/:storedAgentId'>; /** * Parameters for listing stored agents */ export type ListStoredAgentsParams = GeneratedRequest>; /** * Response from favorite / unfavorite mutations. */ export interface FavoriteToggleResponse { favorited: boolean; favoriteCount: number; } /** * Response for listing stored agents */ export type ListStoredAgentsResponse = GeneratedResponse<'GET /stored/agents'>; /** * Parameters for cloning an agent to a stored agent */ export interface CloneAgentParams { /** ID for the cloned agent. If not provided, derived from agent ID. */ newId?: string; /** Name for the cloned agent. Defaults to "{name} (Clone)". */ newName?: string; /** Additional metadata for the cloned agent. */ metadata?: Record; /** Author identifier for the cloned agent. */ authorId?: string; /** Visibility of the cloned agent. Defaults to 'private'. */ visibility?: 'private' | 'public'; /** Request context for resolving dynamic agent configuration (instructions, model, tools, etc.) */ requestContext?: RequestContext | Record; } /** * Parameters for creating a stored agent. * Flat union of agent-record fields and config fields. */ export type CreateStoredAgentParams = GeneratedRequest>; /** * Parameters for updating a stored agent */ export type ExportStoredAgentParams = Partial>; export type OpenStoredAgentChangeRequestParams = ExportStoredAgentParams & { changeMessage?: string; userName?: string; inspectOnly?: boolean; }; export type ExportStoredAgentResponse = GeneratedResponse<'POST /stored/agents/:storedAgentId/export'>; export type OpenStoredAgentChangeRequestResponse = GeneratedResponse<'POST /stored/agents/:storedAgentId/change-request'>; export type UpdateStoredAgentParams = GeneratedRequest>; /** * Response for deleting a stored agent */ export type DeleteStoredAgentResponse = GeneratedResponse<'DELETE /stored/agents/:storedAgentId'>; /** * A single agent that references another agent as a sub-agent. Includes both * public and the caller's own private agents — anything the caller can read. */ export interface StoredAgentDependent { id: string; name: string; } /** * Response for listing dependents of a stored agent. * `dependents` lists caller-readable references (with names). * `hiddenCount` aggregates dependents the caller cannot read; it is only * non-zero when the target agent is public. */ export type StoredAgentDependentsResponse = GeneratedResponse<'GET /stored/agents/:storedAgentId/dependents'>; /** * Sampling configuration for scorers */ export type ScorerSamplingConfig = { type: 'none'; } | { type: 'ratio'; rate: number; }; /** * Scorer type discriminator */ export type StoredScorerType = 'llm-judge' | 'answer-relevancy' | 'answer-similarity' | 'bias' | 'context-precision' | 'context-relevance' | 'faithfulness' | 'hallucination' | 'noise-sensitivity' | 'prompt-alignment' | 'tool-call-accuracy' | 'toxicity'; /** * Stored scorer definition data returned from API */ export type StoredScorerResponse = GeneratedResponse<'GET /stored/scorers/:storedScorerId'>; /** * Parameters for listing stored scorer definitions */ export type ListStoredScorersParams = GeneratedRequest>; /** * Response for listing stored scorer definitions */ export type ListStoredScorersResponse = GeneratedResponse<'GET /stored/scorers'>; /** * Parameters for creating a stored scorer definition */ export type CreateStoredScorerParams = GeneratedRequest>; /** * Parameters for updating a stored scorer definition */ export type UpdateStoredScorerParams = GeneratedRequest>; /** * Response for deleting a stored scorer definition */ export type DeleteStoredScorerResponse = GeneratedResponse<'DELETE /stored/scorers/:storedScorerId'>; /** * MCP server transport configuration */ export interface StoredMCPServerConfig { type: 'stdio' | 'http'; command?: string; args?: string[]; env?: Record; url?: string; timeout?: number; } /** * Stored MCP client data returned from API */ export type StoredMCPClientResponse = GeneratedResponse<'GET /stored/mcp-clients/:storedMCPClientId'>; /** * Parameters for listing stored MCP clients */ export type ListStoredMCPClientsParams = GeneratedRequest>; /** * Response for listing stored MCP clients */ export type ListStoredMCPClientsResponse = GeneratedResponse<'GET /stored/mcp-clients'>; /** * Parameters for creating a stored MCP client */ export type CreateStoredMCPClientParams = GeneratedRequest>; /** * Parameters for updating a stored MCP client */ export type UpdateStoredMCPClientParams = GeneratedRequest>; /** * Response for deleting a stored MCP client */ export type DeleteStoredMCPClientResponse = GeneratedResponse<'DELETE /stored/mcp-clients/:storedMCPClientId'>; export interface AgentVersionResponse { id: string; agentId: string; versionNumber: number; name: string; description?: string; instructions: string | AgentInstructionBlock[]; model: ConditionalField<{ provider: string; name: string; [key: string]: unknown; }>; tools?: ConditionalField>; defaultOptions?: ConditionalField; workflows?: ConditionalField>; agents?: ConditionalField>; integrationTools?: ConditionalField>; toolProviders?: ConditionalField>; mcpClients?: ConditionalField>; inputProcessors?: ConditionalField; outputProcessors?: ConditionalField; memory?: ConditionalField; scorers?: ConditionalField>; requestContextSchema?: Record; changedFields?: string[]; changeMessage?: string; createdAt: string; } export interface ListAgentVersionsParams { page?: number; perPage?: number; orderBy?: { field?: 'versionNumber' | 'createdAt'; direction?: 'ASC' | 'DESC'; }; } export interface ListAgentVersionsResponse { versions: AgentVersionResponse[]; total: number; page: number; perPage: number | false; hasMore: boolean; } export interface CreateAgentVersionParams { changeMessage?: string; } export interface CreateCodeAgentVersionParams { instructions?: AgentVersionResponse['instructions']; tools?: AgentVersionResponse['tools']; changeMessage?: string; } export interface CreateAgentVersionResponse { version: AgentVersionResponse; } export interface ActivateAgentVersionResponse { success: boolean; message: string; activeVersionId: string; } export interface RestoreAgentVersionResponse { success: boolean; message: string; version: AgentVersionResponse; } export interface DeleteAgentVersionResponse { success: boolean; message: string; } export interface VersionDiff { field: string; previousValue: any; currentValue: any; changeType?: 'added' | 'removed' | 'modified'; } export type AgentVersionDiff = VersionDiff; export interface CompareVersionsResponse { fromVersion: AgentVersionResponse; toVersion: AgentVersionResponse; diffs: VersionDiff[]; } export interface ScorerVersionResponse { id: string; scorerDefinitionId: string; versionNumber: number; name: string; description?: string; type: StoredScorerType; model?: { provider: string; name: string; [key: string]: unknown; }; instructions?: string; scoreRange?: { min?: number; max?: number; }; presetConfig?: Record; defaultSampling?: ScorerSamplingConfig; changedFields?: string[]; changeMessage?: string; createdAt: string; } export interface ListScorerVersionsParams { page?: number; perPage?: number; orderBy?: { field?: 'versionNumber' | 'createdAt'; direction?: 'ASC' | 'DESC'; }; } export interface ListScorerVersionsResponse { versions: ScorerVersionResponse[]; total: number; page: number; perPage: number | false; hasMore: boolean; } export interface CreateScorerVersionParams { changeMessage?: string; } export interface ActivateScorerVersionResponse { success: boolean; message: string; activeVersionId: string; } export interface DeleteScorerVersionResponse { success: boolean; message: string; } export interface CompareScorerVersionsResponse { fromVersion: ScorerVersionResponse; toVersion: ScorerVersionResponse; diffs: VersionDiff[]; } export type ListAgentsModelProvidersResponse = GeneratedResponse<'GET /agents/providers'>; export type GetAgentBuilderActionsResponse = GeneratedResponse<'GET /agent-builder'>; export type Provider = ListAgentsModelProvidersResponse['providers'][number]; export interface MastraPackage { name: string; version: string; } export type GetSystemPackagesResponse = GeneratedResponse<'GET /system/packages'>; type BaseObservabilityCapabilitiesResponse = GeneratedResponse<'GET /observability/capabilities'>; export type GetObservabilityCapabilitiesResponse = Omit & { capabilities: BaseObservabilityCapabilitiesResponse['capabilities'] & { /** Optional capabilities advertised by Platform's trace page endpoint. */ tracePage?: boolean; tracePageSearch?: boolean; }; }; /** * Workspace capabilities */ export type WorkspaceCapabilities = ListWorkspacesResponse['workspaces'][number]['capabilities']; /** * Workspace safety configuration */ export type WorkspaceSafety = ListWorkspacesResponse['workspaces'][number]['safety']; /** * Response for getting workspace info */ export type WorkspaceInfoResponse = GeneratedResponse<'GET /workspaces/:workspaceId'>; /** * Workspace item in list response */ export type WorkspaceItem = ListWorkspacesResponse['workspaces'][number]; /** * Response for listing all workspaces */ export type ListWorkspacesResponse = GeneratedResponse<'GET /workspaces'>; /** * File entry in directory listing */ export interface WorkspaceFileEntry { name: string; type: 'file' | 'directory'; size?: number; } /** * Response for reading a file */ export type WorkspaceFsReadResponse = GeneratedResponse<'GET /workspaces/:workspaceId/fs/read'>; /** * Response for writing a file */ export type WorkspaceFsWriteResponse = GeneratedResponse<'POST /workspaces/:workspaceId/fs/write'>; /** * Response for listing files */ export type WorkspaceFsListResponse = GeneratedResponse<'GET /workspaces/:workspaceId/fs/list'>; /** * Response for deleting a file */ export type WorkspaceFsDeleteResponse = GeneratedResponse<'DELETE /workspaces/:workspaceId/fs/delete'>; /** * Response for creating a directory */ export type WorkspaceFsMkdirResponse = GeneratedResponse<'POST /workspaces/:workspaceId/fs/mkdir'>; /** * Response for getting file stats */ export type WorkspaceFsStatResponse = GeneratedResponse<'GET /workspaces/:workspaceId/fs/stat'>; /** * skills.sh registry operations (proxied by the workspace API) */ export type SkillsShSearchParams = QueryParams<'GET /workspaces/:workspaceId/skills-sh/search'>; export type SkillsShSearchResponse = GeneratedResponse<'GET /workspaces/:workspaceId/skills-sh/search'>; export type SkillsShPopularParams = QueryParams<'GET /workspaces/:workspaceId/skills-sh/popular'>; export type SkillsShPopularResponse = GeneratedResponse<'GET /workspaces/:workspaceId/skills-sh/popular'>; export type SkillsShSkill = SkillsShPopularResponse['skills'][number]; export type SkillsShPreviewParams = QueryParams<'GET /workspaces/:workspaceId/skills-sh/preview'>; export type SkillsShPreviewResponse = GeneratedResponse<'GET /workspaces/:workspaceId/skills-sh/preview'>; export type SkillsShInstallParams = Body<'POST /workspaces/:workspaceId/skills-sh/install'>; export type SkillsShInstallResponse = GeneratedResponse<'POST /workspaces/:workspaceId/skills-sh/install'>; export type SkillsShRemoveParams = Body<'POST /workspaces/:workspaceId/skills-sh/remove'>; export type SkillsShRemoveResponse = GeneratedResponse<'POST /workspaces/:workspaceId/skills-sh/remove'>; export type SkillsShUpdateParams = Body<'POST /workspaces/:workspaceId/skills-sh/update'>; export type SkillsShUpdateResponse = GeneratedResponse<'POST /workspaces/:workspaceId/skills-sh/update'>; /** * Workspace search result */ export interface WorkspaceSearchResult { /** Document identifier (typically the indexed file path) */ id: string; content: string; score: number; lineRange?: { start: number; end: number; }; scoreDetails?: { vector?: number; bm25?: number; }; } /** * Parameters for searching workspace content */ export type WorkspaceSearchParams = GeneratedRequest>; /** * Response for searching workspace */ export type WorkspaceSearchResponse = GeneratedResponse<'GET /workspaces/:workspaceId/search'>; /** * Parameters for indexing content */ export type WorkspaceIndexParams = GeneratedRequest>; /** * Response for indexing content */ export type WorkspaceIndexResponse = GeneratedResponse<'POST /workspaces/:workspaceId/index'>; /** * Skill source type indicating where the skill comes from */ export type SkillSource = { type: 'external'; packagePath: string; } | { type: 'local'; projectPath: string; } | { type: 'managed'; mastraPath: string; }; /** * Skill metadata (without instructions content) */ export interface SkillMetadata { name: string; description: string; license?: string; compatibility?: string; metadata?: Record; path: string; } /** * Full skill data including instructions and file paths */ export interface Skill extends SkillMetadata { instructions: string; source: SkillSource; references: string[]; scripts: string[]; assets: string[]; } /** * Response for listing skills */ export interface ListSkillsResponse { skills: SkillMetadata[]; isSkillsConfigured: boolean; } /** * Skill search result */ export interface SkillSearchResult { skillName: string; source: string; content: string; score: number; lineRange?: { start: number; end: number; }; scoreDetails?: { vector?: number; bm25?: number; }; } /** * Parameters for searching skills */ export interface SearchSkillsParams { query: string; topK?: number; minScore?: number; skillNames?: string[]; includeReferences?: boolean; } /** * Response for searching skills */ export interface SearchSkillsResponse { results: SkillSearchResult[]; query: string; } /** * Response for listing skill references */ export interface ListSkillReferencesResponse { skillName: string; references: string[]; } /** * Response for getting skill reference content */ export interface GetSkillReferenceResponse { skillName: string; referencePath: string; content: string; } /** * File node for skill workspace */ export interface StoredSkillFileNode { id: string; name: string; type: 'file' | 'folder'; content?: string; children?: StoredSkillFileNode[]; } /** * Stored skill data returned from API */ export type StoredSkillResponse = GeneratedResponse<'GET /stored/skills/:storedSkillId'>; /** * Parameters for listing stored skills */ export type ListStoredSkillsParams = GeneratedRequest>; /** * Response for listing stored skills */ export type ListStoredSkillsResponse = GeneratedResponse<'GET /stored/skills'>; /** * Parameters for creating a stored skill */ export type CreateStoredSkillParams = GeneratedRequest>; /** * Parameters for updating a stored skill */ export type UpdateStoredSkillParams = GeneratedRequest>; /** * Response for deleting a stored skill */ export type DeleteStoredSkillResponse = GeneratedResponse<'DELETE /stored/skills/:storedSkillId'>; /** * Filesystem configuration in a stored workspace */ export interface StoredFilesystemConfig { provider: string; config: Record; readOnly?: boolean; } /** * Sandbox configuration in a stored workspace */ export interface StoredSandboxConfig { provider: string; config: Record; } /** * Stored workspace data returned from API */ export type StoredWorkspaceResponse = GeneratedResponse<'GET /stored/workspaces/:storedWorkspaceId'>; /** * Parameters for listing stored workspaces */ export type ListStoredWorkspacesParams = GeneratedRequest>; /** * Response for listing stored workspaces */ export type ListStoredWorkspacesResponse = GeneratedResponse<'GET /stored/workspaces'>; /** Processor phases are defined by the processor detail route. */ export type ProcessorPhase = GeneratedResponse<'GET /processors/:processorId'>['phases'][number]; /** Processor attachment configuration returned by the detail route. */ export type ProcessorConfiguration = GeneratedResponse<'GET /processors/:processorId'>['configurations'][number]; /** Processor summary returned from the processor collection route. */ export type GetProcessorResponse = GeneratedResponse<'GET /processors'>[string]; /** Detailed processor response. */ export type GetProcessorDetailResponse = GeneratedResponse<'GET /processors/:processorId'>; /** Parameters for executing a processor. */ export type ExecuteProcessorParams = GeneratedRequest> & RequestContextOptions; /** Tripwire result returned from processor execution. */ export type ProcessorTripwireResult = NonNullable['tripwire']>; /** Response from processor execution. */ export type ExecuteProcessorResponse = GeneratedResponse<'POST /processors/:processorId/execute'>; /** * Parameters for getting observational memory */ export type GetObservationalMemoryParams = Omit>, 'from' | 'to'> & { from?: Date | string; to?: Date | string; } & RequestContextOptions; /** * Response for observational memory endpoint */ export type GetObservationalMemoryResponse = GeneratedResponse<'GET /memory/observational-memory'>; /** * Parameters for awaiting buffer status */ export type AwaitBufferStatusParams = GeneratedRequest> & RequestContextOptions; /** * Response for buffer status endpoint */ export type AwaitBufferStatusResponse = GeneratedResponse<'POST /memory/observational-memory/buffer-status'>; /** * Extended memory status response with OM info */ export type GetMemoryStatusResponse = GeneratedResponse<'GET /memory/status'>; /** * Extended memory config response with OM config */ export interface GetMemoryConfigResponseExtended { memoryType?: 'local' | 'gateway'; config: MemoryConfig & { observationalMemory?: { enabled: boolean; scope?: 'thread' | 'resource'; messageTokens?: number | { min: number; max: number; }; observationTokens?: number | { min: number; max: number; }; observationModel?: string; reflectionModel?: string; }; }; } /** * Response for listing available vector stores */ export type ListVectorsResponse = GeneratedResponse<'GET /vectors'>; /** * Response for listing available embedding models */ export type ListEmbeddersResponse = GeneratedResponse<'GET /embedders'>; export type ToolProviderInfo = GeneratedResponse<'GET /tool-providers'>['providers'][number]; export type ToolProviderToolkit = GeneratedResponse<'GET /tool-providers/:providerId/toolkits'>['data'][number]; export type ToolProviderToolInfo = GeneratedResponse<'GET /tool-providers/:providerId/tools'>['data'][number]; export type ToolProviderPagination = NonNullable['pagination']>; export type ListToolProvidersResponse = GeneratedResponse<'GET /tool-providers'>; export type ListToolProviderToolkitsResponse = GeneratedResponse<'GET /tool-providers/:providerId/toolkits'>; export type ListToolProviderToolsParams = GeneratedRequest>; export type ListToolProviderToolsResponse = GeneratedResponse<'GET /tool-providers/:providerId/tools'>; export type GetToolProviderToolSchemaResponse = GeneratedResponse<'GET /tool-providers/:providerId/tools/:toolSlug/schema'>; export type AuthorizeToolProviderParams = GeneratedRequest>; export type AuthorizeToolProviderResponse = GeneratedResponse<'POST /tool-providers/:providerId/authorize'>; export type ToolProviderAuthStatusResponse = GeneratedResponse<'GET /tool-providers/:providerId/auth-status/:authId'>; export type ToolProviderConnectionStatusParams = GeneratedRequest>; export type ToolProviderConnectionStatusResponse = GeneratedResponse<'POST /tool-providers/:providerId/connection-status'>; export type ListToolProviderConnectionsParams = GeneratedRequest>; export type ListToolProviderConnectionsResponse = GeneratedResponse<'GET /tool-providers/:providerId/connections'>; export type ListToolProviderConnectionFieldsParams = GeneratedRequest>; export type ListToolProviderConnectionFieldsResponse = GeneratedResponse<'GET /tool-providers/:providerId/connection-fields'>; export type DisconnectToolProviderConnectionParams = GeneratedRequest>; export type DisconnectToolProviderConnectionResponse = GeneratedResponse<'DELETE /tool-providers/:providerId/connections/:connectionId'>; export type UpdateToolProviderConnectionParams = GeneratedRequest>; export type UpdateToolProviderConnectionResponse = GeneratedResponse<'PATCH /tool-providers/:providerId/connections/:connectionId'>; export type GetToolProviderConnectionUsageParams = GeneratedRequest>; export type GetToolProviderConnectionUsageResponse = GeneratedResponse<'GET /tool-providers/:providerId/connections/:connectionId/usage'>; export type ToolProviderHealthResponse = GeneratedResponse<'GET /tool-providers/:providerId/health'>; /** * Provider phase names as returned by the server (prefixed form). * Distinct from ProcessorPhase which uses the short/unprefixed form for processor endpoints. */ export type ProcessorProviderPhase = 'processInput' | 'processInputStep' | 'processOutputStream' | 'processOutputResult' | 'processOutputStep'; export interface ProcessorProviderInfo { id: string; name: string; description?: string; availablePhases: ProcessorProviderPhase[]; } export interface GetProcessorProvidersResponse { providers: ProcessorProviderInfo[]; } export interface GetProcessorProviderResponse { id: string; name: string; description?: string; availablePhases: ProcessorProviderPhase[]; configSchema: Record; } /** * HTTP error thrown by the Mastra client. * Extends Error with additional properties for better error handling. * * @example * ```typescript * try { * await client.getWorkspace('my-workspace').listFiles('/invalid-path'); * } catch (error) { * if (error instanceof MastraClientError) { * if (error.status === 404) { * console.log('Not found:', error.body); * } * } * } * ``` */ export declare class MastraClientError extends Error { /** HTTP status code */ readonly status: number; /** HTTP status text (e.g., "Not Found", "Internal Server Error") */ readonly statusText: string; /** Parsed response body if available */ readonly body?: unknown; constructor(status: number, statusText: string, message: string, body?: unknown); } export interface DatasetItemSource { type: 'csv' | 'json' | 'trace' | 'llm' | 'experiment-result' | 'candidate-screener'; referenceId?: string; } /** A single item-level static tool mock (agent targets only). */ export interface DatasetItemToolMock { /** Name of the tool this mock applies to. */ toolName: string; /** Arguments to match against the tool call (deep equality when matchArgs is 'strict'). */ args: Record; /** Output served to the agent when this mock is matched and consumed. */ output: unknown; /** Argument matching mode. 'strict' (default) deep-equals args; 'ignore' matches on toolName only. */ matchArgs?: 'strict' | 'ignore'; } /** Diagnostic receipt for item-level tool mocks, returned on experiment results. */ export type ToolMockReport = NonNullable['results'][number]['toolMockReport']>; export type DatasetItem = NonNullable>; export type DatasetRecord = NonNullable>; export type ExperimentTargetType = NonNullable['targetType']>; export interface ExperimentProvenance { source?: string; sourceId?: string; sourceVersion?: string; metadata?: Record; } export interface ExperimentRunnerAttestation { runnerId: string; invocationId: string; runnerVersion?: string; } export interface ExperimentGrouping { experimentSetId?: string; comparisonId?: string; variantId?: string; trialIndex?: number; } export type ListExperimentsParams = GeneratedRequest>; export type ListDatasetsParams = GeneratedRequest>; export type DatasetExperiment = GeneratedResponse<'GET /experiments'>['experiments'][number]; export type DatasetExperimentResult = GeneratedResponse<'GET /datasets/:datasetId/experiments/:experimentId/results'>['results'][number] & { /** * Aggregated scorer runs are a client convenience: score records are fetched * from the scores store rather than embedded in the route response. */ scores?: Array<{ scorerId: string; scorerName: string; score: number | null; reason: string | null; error: string | null; }>; }; export type UpdateExperimentResultParams = PathParams<'PATCH /datasets/:datasetId/experiments/:experimentId/results/:resultId'> & WithoutIndexSignatures>>; export type CreateDatasetParams = WithoutIndexSignatures>>; export type UpdateDatasetParams = PathParams<'PATCH /datasets/:datasetId'> & WithoutIndexSignatures>> & GeneratedRequest>; export type AddDatasetItemParams = PathParams<'POST /datasets/:datasetId/items'> & WithoutIndexSignatures>>; export type UpdateDatasetItemParams = PathParams<'PATCH /datasets/:datasetId/items/:itemId'> & WithoutIndexSignatures>>; export type BatchInsertDatasetItemsParams = PathParams<'POST /datasets/:datasetId/items/batch'> & WithoutIndexSignatures>>; export type BatchDeleteDatasetItemsParams = PathParams<'DELETE /datasets/:datasetId/items/batch'> & WithoutIndexSignatures>>; export type GenerateDatasetItemsParams = PathParams<'POST /datasets/:datasetId/generate-items'> & WithoutIndexSignatures>>; export type GeneratedItem = GeneratedResponse<'POST /datasets/:datasetId/generate-items'>['items'][number]; export type UpdateDatasetExperimentParams = PathParams<'PATCH /datasets/:datasetId/experiments/:experimentId'> & WithoutIndexSignatures>>; export type TriggerDatasetExperimentParams = PathParams<'POST /datasets/:datasetId/experiments'> & WithoutIndexSignatures>>; export type CreateDatasetExperimentParams = PathParams<'POST /datasets/:datasetId/experiments'> & WithoutIndexSignatures>>; export type CreateDatasetExperimentResponse = GeneratedResponse<'POST /datasets/:datasetId/experiments'>; export type RunExperimentItemParams = PathParams<'POST /datasets/:datasetId/experiments/:experimentId/items/:itemId/run'> & WithoutIndexSignatures>>; /** * A single experiment result row as the server returns it: structured * `error` object and no aggregated `scores` (scores live in the scores * store, keyed by `runId = experimentId`). */ export type ListDatasetExperimentResultsResponse = Omit, 'results'> & { results: DatasetExperimentResult[]; }; export type DatasetExperimentResultRow = DatasetExperimentResult extends infer R ? R extends unknown ? Omit : never : never; export type RunExperimentItemResponse = GeneratedResponse<'POST /datasets/:datasetId/experiments/:experimentId/items/:itemId/run'>; export type SubmitExperimentResultParams = PathParams<'POST /datasets/:datasetId/experiments/:experimentId/results'> & WithoutIndexSignatures>>; export type FinalizeExperimentParams = PathParams<'POST /datasets/:datasetId/experiments/:experimentId/finalize'>; export type CompareExperimentsParams = PathParams<'POST /datasets/:datasetId/compare'> & WithoutIndexSignatures>>; export type DatasetItemVersionResponse = NonNullable>; export type DatasetVersionResponse = SerializedRouteResponse<'GET /datasets/:datasetId/versions'>['versions'][number]; export type CompareExperimentsResponse = GeneratedResponse<'POST /datasets/:datasetId/compare'>; /** * Stored prompt block data returned from API */ export type StoredPromptBlockResponse = GeneratedResponse<'GET /stored/prompt-blocks/:storedPromptBlockId'>; /** * Parameters for listing stored prompt blocks */ export type ListStoredPromptBlocksParams = GeneratedRequest>; /** * Response for listing stored prompt blocks */ export type ListStoredPromptBlocksResponse = GeneratedResponse<'GET /stored/prompt-blocks'>; /** * Parameters for creating a stored prompt block */ export type CreateStoredPromptBlockParams = GeneratedRequest>; /** * Parameters for updating a stored prompt block */ export type UpdateStoredPromptBlockParams = GeneratedRequest>; /** * Response for deleting a stored prompt block */ export type DeleteStoredPromptBlockResponse = GeneratedResponse<'DELETE /stored/prompt-blocks/:storedPromptBlockId'>; export interface PromptBlockVersionResponse { id: string; blockId: string; versionNumber: number; name: string; description?: string; content: string; rules?: RuleGroup; requestContextSchema?: Record; changedFields?: string[]; changeMessage?: string; createdAt: string; } export interface ListPromptBlockVersionsParams { page?: number; perPage?: number; orderBy?: { field?: 'versionNumber' | 'createdAt'; direction?: 'ASC' | 'DESC'; }; } export interface ListPromptBlockVersionsResponse { versions: PromptBlockVersionResponse[]; total: number; page: number; perPage: number | false; hasMore: boolean; } export interface CreatePromptBlockVersionParams { changeMessage?: string; } export interface ActivatePromptBlockVersionResponse { success: boolean; message: string; activeVersionId: string; } export interface DeletePromptBlockVersionResponse { success: boolean; message: string; } export type BackgroundTaskStatus = 'pending' | 'running' | 'suspended' | 'completed' | 'failed' | 'cancelled' | 'timed_out'; export type BackgroundTaskDateColumn = 'createdAt' | 'startedAt' | 'completedAt'; export type BackgroundTaskResponse = GeneratedResponse<'GET /background-tasks'>['tasks'][number]; export type ListBackgroundTasksParams = GeneratedRequest>; export type ListBackgroundTasksResponse = GeneratedResponse<'GET /background-tasks'>; export type StreamBackgroundTasksParams = GeneratedRequest>; export type ScheduleStatus = 'active' | 'paused' | 'completed'; export interface ScheduleRunSummary { status: WorkflowRunStatus; startedAt?: number; completedAt?: number; durationMs?: number; error?: string; } /** Attributes rendered onto the signal's XML tag. */ export type ScheduleSignalAttributes = Record; /** Mirrors the core `AgentSignalType` union. */ export type ScheduleSignalType = 'user' | 'state' | 'reactive' | 'notification' | 'user-message' | 'system-reminder'; /** Behavior applied when the thread is already streaming. */ export interface ScheduleIfActive { behavior?: 'deliver' | 'persist' | 'discard'; attributes?: ScheduleSignalAttributes; } /** * Behavior applied when the thread is idle, plus a serializable subset of * stream options forwarded to the woken run. */ export interface ScheduleIfIdle { behavior?: 'wake' | 'persist' | 'discard'; attributes?: ScheduleSignalAttributes; streamOptions?: { requestContext?: Record; }; } /** * Flat agent-schedule view returned by the unified `/schedules` surface. * Discriminate from workflow schedules by the presence of `agentId`. */ export type AgentSchedule = Extract['schedules'][number], { agentId: string; }>; /** * Flat workflow-schedule view returned by the unified `/schedules` surface. * Discriminate from agent schedules by the presence of `workflowId`. */ export type WorkflowSchedule = Extract['schedules'][number], { workflowId: string; }>; /** Union of the flat views returned by the unified `/schedules` surface. */ export type ScheduleResponse = AgentSchedule | WorkflowSchedule; export type ScheduleTriggerOutcome = 'published' | 'succeeded' | 'delivered' | 'persisted' | 'discarded' | 'skipped' | 'aborted' | 'failed'; export type ScheduleTriggerKind = 'schedule-fire' | 'queue-drain' | 'manual'; export type ScheduleTriggerResponse = GeneratedResponse<'GET /schedules/:scheduleId/triggers'>['triggers'][number]; export type ListSchedulesParams = GeneratedRequest>; export type ListSchedulesResponse = GeneratedResponse<'GET /schedules'>; export type ListScheduleTriggersParams = GeneratedRequest>; export type ListScheduleTriggersResponse = GeneratedResponse<'GET /schedules/:scheduleId/triggers'>; /** * Agent variant of the `client.createSchedule(...)` body — targets an agent * by `agentId`. Mirrors `CreateAgentScheduleInput` on the core Schedules * service. */ export type CreateAgentScheduleInput = Extract>>, { agentId: string; }>; /** * Workflow variant of the `client.createSchedule(...)` body — targets a * workflow by `workflowId`. Mirrors `CreateWorkflowScheduleInput` on the * core Schedules service. */ export type CreateWorkflowScheduleInput = Extract>>, { workflowId: string; }>; /** * Body for `client.createSchedule(...)`. Discriminated by which target id is * present: `agentId` creates an agent schedule, `workflowId` a workflow * schedule. */ export type CreateScheduleInput = CreateAgentScheduleInput | CreateWorkflowScheduleInput; /** * Patch body for `client.updateSchedule(...)`. Fields apply to the matching * target type; agent-only fields on a workflow schedule are rejected by the * server. `threadId` / `resourceId` are part of an agent schedule's identity * and cannot be changed — to retarget, delete and recreate. */ export type UpdateScheduleInput = WithoutIndexSignatures>>; /** * Response for POST /schedules/:scheduleId/run. * * The fire runs asynchronously through the same worker pipeline as scheduled * fires. `claimId` is the trigger row's `runId` (used to look up the * resulting trigger row via `listScheduleTriggers`). */ export type RunScheduleResponse = GeneratedResponse<'POST /schedules/:scheduleId/run'>; export interface ExperimentReviewCounts { experimentId: string; total: number; needsReview: number; reviewed: number; complete: number; } /** * Agent feature flags for the builder. * * The `GET /editor/builder/settings` response always carries a fully-resolved * object. On admin input, omitted keys default to `true` (default-on / allowlist * model — admins opt out by setting a key to `false`). Special case: `browser` * is only `true` when `configuration.agent.browser` is provided. * * Clients should still use strict `=== true` checks. */ export interface BuilderAgentFeatures { tools?: boolean; agents?: boolean; workflows?: boolean; scorers?: boolean; skills?: boolean; memory?: boolean; variables?: boolean; favorites?: boolean; avatarUpload?: boolean; browser?: boolean; /** * Whether the model picker is visible in the Agent Builder. * Omitted/`false` ⇒ picker hidden (locked mode); admin's `models.default` is applied. */ model?: boolean; } /** * Re-exported from `@mastra/core/agent-builder/ee` so SDK consumers don't need * a second import for admin model configuration types. Owned by core. */ export type { BuilderModelPolicy, DefaultModelEntry, ProviderModelEntry, ModelProviderId }; /** * Response from GET /editor/builder/settings */ export type BuilderSettingsResponse = GeneratedResponse<'GET /editor/builder/settings'>; /** * Response from GET /editor/builder/models/available. * * Same provider shape as {@link ListAgentsModelProvidersResponse}, but each * provider's `models` list is already filtered by the active builder model * policy (the server applies the EE allowlist). Providers with no allowed * models are omitted, so the picker can render this verbatim. */ export type BuilderAvailableModelsResponse = GeneratedResponse<'GET /editor/builder/models/available'>; /** * A valid permission-pattern string (e.g. `agents:read`, `*`). * * Kept as a string alias so the Playground can name the type while the * authoritative set is fetched from the server at runtime. */ export type PermissionPattern = string; /** * Response from GET /auth/permission-patterns. */ export type WorkflowBuilderSettingsResponse = GeneratedResponse<'GET /editor/workflow-builder/settings'>; export type PermissionPatternsResponse = GeneratedResponse<'GET /auth/permission-patterns'>; /** * Resolved picker visibility section returned in {@link BuilderSettingsResponse}. * * Per kind: * - `null` ⇒ unrestricted (show all registered entries). * - `string[]` ⇒ explicit allowlist (may be empty to show none). */ export interface BuilderPickerResponse { visibleTools: string[] | null; visibleAgents: string[] | null; visibleWorkflows: string[] | null; } /** * Response from GET /editor/builder/infrastructure * * Agent Builder infrastructure configuration plus lightweight runtime resolution state. */ export type InfrastructureStatusResponse = GeneratedResponse<'GET /editor/builder/infrastructure'>; /** * One known skill registry surfaced from the Agent Builder config. */ export type BuilderRegistryDescriptor = GeneratedResponse<'GET /editor/builder/registries'>['registries'][number]; export type ListBuilderRegistriesResponse = GeneratedResponse<'GET /editor/builder/registries'>; export type BuilderRegistrySkillSummary = GeneratedResponse<'GET /editor/builder/registries/:registryId/search'>['skills'][number]; export type BuilderRegistrySearchResponse = GeneratedResponse<'GET /editor/builder/registries/:registryId/search'>; export type BuilderRegistryPopularResponse = GeneratedResponse<'GET /editor/builder/registries/:registryId/popular'>; export type BuilderRegistryPreviewResponse = GeneratedResponse<'GET /editor/builder/registries/:registryId/preview'>; export type BuilderRegistryInstallBody = GeneratedRequest>; export type BuilderRegistryInstallResponse = GeneratedResponse<'POST /editor/builder/registries/:registryId/install'>; export type { AgentControllerThinkingLevel, PermissionPolicy, ToolCategory } from '@mastra/core/agent-controller'; export type { TaskItemSnapshot as AgentControllerTaskSnapshot } from '@mastra/core/tools'; export type AgentControllerInfo = GeneratedResponse<'GET /agent-controller'>['agentControllers'][number]; export type CreateAgentControllerSessionResponse = GeneratedResponse<'POST /agent-controller/:controllerId/sessions'>; export type AgentControllerSessionState = GeneratedResponse<'GET /agent-controller/:controllerId/sessions/:sessionId'>; /** * Agent behavior settings, mirroring the TUI's `/settings` toggles. An absent * `thinkingLevel` means the session inherits the configured default rather than * overriding it. */ export type AgentControllerSessionSettings = NonNullable; /** * Status-line relevant slice of observational-memory progress, mirroring the * TUI status line. `msg` reads `pendingTokens/threshold ↓projectedMessageRemoval` * (the active message window before an observation fires); `mem` reads * `observationTokens/reflectionThreshold ↓projectedReflectionSavings` * (accumulated observations before a reflection fires). */ export type AgentControllerOMProgress = NonNullable; export type AgentControllerModeInfo = GeneratedResponse<'GET /agent-controller/:controllerId/modes'>['modes'][number]; export type AgentControllerAvailableModel = GeneratedResponse<'GET /agent-controller/:controllerId/models'>['models'][number]; export type AgentControllerActiveRun = GeneratedResponse<'GET /agent-controller/:controllerId/active-runs'>['runs'][number]; /** * A thread as it appears in `listThreads()`. Carries the session scoping tags * it was stamped with (e.g. `{ projectPath }`) and whether a run is currently * executing on it, so one listing can report activity across every scope * sharing the resourceId. */ export type AgentControllerThreadInfo = GeneratedResponse<'GET /agent-controller/:controllerId/sessions/:sessionId/threads'>['threads'][number]; /** A thread as returned by `createThread()` and `cloneThread()`. */ export type CreateAgentControllerThreadResponse = GeneratedResponse<'POST /agent-controller/:controllerId/sessions/:sessionId/threads'>; export type AgentControllerWorkspaceStatus = GeneratedResponse<'GET /agent-controller/:controllerId/workspace'>; export type AgentControllerGoalRecord = NonNullable['goal']>; /** Per-category and per-tool approval policies. */ export type PermissionRules = GeneratedResponse<'GET /agent-controller/:controllerId/sessions/:sessionId/permissions'>; export type SendNotificationInput = GeneratedRequest>; export type SendNotificationResult = GeneratedResponse<'POST /agent-controller/:controllerId/sessions/:sessionId/notifications'>; export type { FilterGroup, FilterNode, FilterToken, SavedViewColumn, SavedViewDateRange, SavedViewPage, SavedViewSort, SavedViewState, } from '@mastra/core/storage'; export type { GetTracePageArgs, TracePageRequest, TracePageResponse, TracePageNode, } from './resources/observability-route-types.js'; //# sourceMappingURL=types.d.ts.map