{"version":3,"sources":["../src/tools/stream.ts","../src/tools/types.ts","../src/tools/tool-builder/builder.ts","../src/utils.ts"],"names":["WritableStream","RequestContext","toStandardSchema","MastraBase","isVercelTool","isProviderDefinedTool","z","isZodObject","safeExtendZodObject","backgroundOverrideZodSchema","isStandardSchemaWithJSON","jsonSchema","standardSchemaToJSONSchema","backgroundOverrideJsonSchema","schema","convertZodSchemaToAISDKSchema","executeWithContext","wrapMastra","createObservabilityContext","args","resumeData","validateToolInput","validateToolSuspendData","validateToolOutput","logger","getOrCreateSpan","EntityType","MastraFGAPermissions","MastraError","ErrorDomain","ErrorCategory","OpenAIReasoningSchemaCompatLayer","OpenAISchemaCompatLayer","GoogleSchemaCompatLayer","AnthropicSchemaCompatLayer","DeepSeekSchemaCompatLayer","MetaSchemaCompatLayer","applyCompatLayer","getNeedsApprovalFn","createHash","Tool","jsonSchemaToZod"],"mappings":";;;;;;;;;;;;;;;;;;AAIO,IAAM,UAAA,GAAN,cAAyBA,kBAAA,CAAwB;AAAA,EAC9C,MAAA;AAAA,EACA,MAAA;AAAA,EACA,IAAA;AAAA,EACA,KAAA;AAAA,EACA,OAAA;AAAA,EAER,WAAA,CACE;AAAA,IACE,MAAA;AAAA,IACA,MAAA;AAAA,IACA,IAAA;AAAA,IACA;AAAA,KAOF,OAAA,EACA;AACA,IAAA,KAAA,CAAM;AAAA,MACJ,MAAM,MAAM,KAAA,EAAY;AACtB,QAAA,MAAM,WAAA,EAAY,CAAE,MAAA,CAAO,KAAK,CAAA;AAAA,MAClC;AAAA,KACD,CAAA;AAED,IAAA,MAAM,IAAA,GAAO,IAAA;AACb,IAAA,SAAS,WAAA,GAAc;AACrB,MAAA,OAAO,IAAA;AAAA,IACT;AAEA,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AACb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nF,IAAA;AAAA,EACF;AAEA,EAAA,IAAI,OAAA,GAAU,GAAA;AACd,EAAA,KAAA,MAAW,OAAO,IAAA,EAAM;AACtB,IAAA,MAAM,QAAA,GAAW,MAAA,CAAO,SAAA,CAAU,cAAA,CAAe,IAAA,CAAK,SAAS,GAAG,CAAA,GAAI,OAAA,CAAQ,GAAG,CAAA,GAAI,MAAA;AACrF,IAAA,IAAI,QAAA,KAAa,IAAA,IAAQ,OAAO,QAAA,KAAa,QAAA,EAAU;AAIrD,MAAA,MAAM,SAAA,mBAAY,MAAA,CAAO,MAAA,CAAO,IAAI,CAAA;AACpC,MAAA,MAAA,CAAO,cAAA,CAAe,OAAA,EAAS,GAAA,EAAK,EAAE,KAAA,EAAO,SAAA,EAAW,QAAA,EAAU,IAAA,EAAM,UAAA,EAAY,IAAA,EAAM,YAAA,EAAc,IAAA,EAAM,CAAA;AAAA,IAChH;AACA,IAAA,OAAA,GAAU,QAAQ,GAAG,CAAA;AAAA,EACvB;AAEA,EAAA,MAAA,CAAO,cAAA,CAAe,OAAA,EAAS,OAAA,EAAS,EAAE,KAAA,EAAO,QAAA,EAAU,IAAA,EAAM,UAAA,EAAY,IAAA,EAAM,YAAA,EAAc,IAAA,EAAM,CAAA;AACzG;AAEO,IAAM,qBAAA,GAAwB,CAAC,GAAA,KAA6B;AACjE,EAAA,OAAO,MAAA,CAAO,WAAA,CAAY,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,CAAE,MAAA,CAAO,CAAC,CAAC,CAAA,EAAG,KAAK,CAAA,KAAM,KAAA,KAAU,MAAS,CAAC,CAAA;AAC3F","file":"chunk-ER5YO3AZ.cjs","sourcesContent":["import { WritableStream } from 'node:stream/web';\nimport type { DataChunkType } from '../stream/types';\nimport type { OutputWriter } from '../workflows';\n\nexport class ToolStream extends WritableStream {\n private prefix: string;\n private callId: string;\n private name: string;\n private runId: string;\n private writeFn?: OutputWriter;\n\n constructor(\n {\n prefix,\n callId,\n name,\n runId,\n }: {\n prefix: string;\n callId: string;\n name: string;\n runId: string;\n },\n writeFn?: OutputWriter,\n ) {\n super({\n async write(chunk: any) {\n await getInstance()._write(chunk);\n },\n });\n\n const self = this;\n function getInstance() {\n return self;\n }\n\n this.prefix = prefix;\n this.callId = callId;\n this.name = name;\n this.runId = runId;\n this.writeFn = writeFn;\n }\n\n private async _write(data: any) {\n if (this.writeFn) {\n await this.writeFn({\n type: `${this.prefix}-output`,\n runId: this.runId,\n from: 'USER',\n payload: {\n output: data,\n ...(this.prefix === 'workflow-step'\n ? {\n runId: this.runId,\n stepName: this.name,\n }\n : {\n [`${this.prefix}CallId`]: this.callId,\n [`${this.prefix}Name`]: this.name,\n }),\n },\n });\n }\n }\n\n async write(data: any) {\n await this._write(data);\n }\n\n async custom(data: T extends { type: `data-${string}` } ? DataChunkType : T) {\n if (this.writeFn) {\n await this.writeFn(data);\n }\n }\n}\n","import type { WritableStream } from 'node:stream/web';\nimport type {\n Tool,\n ToolV5,\n FlexibleSchema,\n ToolCallOptions,\n ToolExecutionOptions,\n Schema,\n} from '@internal/external-types';\nimport type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { ElicitRequest, ElicitResult } from '@modelcontextprotocol/sdk/types.js';\n\nimport type { MastraPrimitives, MastraUnion } from '../action';\nexport type { MastraPrimitives, MastraUnion };\nimport type { ActorSignal } from '../auth/ee';\nimport type { ToolBackgroundConfig } from '../background-tasks';\nimport type { MastraBrowser } from '../browser/browser';\nimport type { Mastra } from '../mastra';\nimport type { ObservabilityContext } from '../observability';\nimport type { RequestContext } from '../request-context';\nimport type { PublicSchema } from '../schema';\nimport type { SuspendOptions, OutputWriter } from '../workflows';\nimport type { Workspace } from '../workspace/workspace';\nimport type { ToolStream } from './stream';\nimport type { ValidationError } from './validation';\n\nexport type VercelTool = Tool;\nexport type VercelToolV5 = ToolV5;\n\nexport type ToolInvocationOptions = ToolExecutionOptions | ToolCallOptions;\n\n/**\n * Context passed to a global `requireToolApproval` function, evaluated per tool call.\n */\nexport type ToolApprovalContext = {\n /** Name of the tool being called. */\n toolName: string;\n /** Arguments the model is passing to the tool. */\n args: Record;\n /** Plain object view of the request context, when available. */\n requestContext?: Record;\n /** Active workspace, when the run is bound to one. */\n workspace?: Workspace;\n};\n\n/**\n * Function form of the global `requireToolApproval` option. Evaluated per tool call;\n * return `true` to require approval for that call, `false` to allow it. Enables\n * conditional, per-call approval policies (e.g. regex matching on `toolName`).\n */\nexport type RequireToolApprovalFn = (ctx: ToolApprovalContext) => boolean | Promise;\n\n/**\n * Global tool approval setting. `true` requires approval for every tool call,\n * `false`/omitted requires none, and a function decides per call.\n */\nexport type RequireToolApproval = boolean | RequireToolApprovalFn;\n\n/**\n * Context passed to a per-tool `needsApprovalFn` alongside the parsed tool input.\n * This is the same context surfaced to a tool-level `requireApproval` function.\n */\nexport type NeedsApprovalContext = {\n /** Plain object view of the request context, when available. */\n requestContext?: Record;\n /** Active workspace, when the run is bound to one. */\n workspace?: Workspace;\n};\n\n/**\n * Per-tool approval predicate attached to a tool instance.\n *\n * This is the runtime-resolved form of a tool's `requireApproval` function (or of an\n * MCP server-level `requireToolApproval` function wrapped by the MCP client). It is\n * evaluated per tool call with the parsed input and the available context; return\n * `true` to require approval for that call, `false` to allow it.\n *\n * It is attached to the tool instance by {@link CoreToolBuilder} / the MCP client and\n * read by the agent runtime. Prefer the public `requireApproval` option on\n * `createTool` over setting this directly.\n */\nexport type NeedsApprovalFn = (input: any, ctx?: NeedsApprovalContext) => boolean | Promise;\n\nexport interface ToolHookContext<\n TInput = unknown,\n TContext = unknown,\n TMetadata extends Record = Record,\n> {\n /** The name exposed to the model for this tool call. */\n toolName: string;\n /** Input passed to the tool. */\n input: TInput;\n /** Execution context passed to the tool. */\n context: TContext;\n /** Optional adapter-specific metadata. */\n metadata?: TMetadata;\n}\n\nexport interface ToolBeforeHookResult {\n /** Set to false to skip the tool execution and return `output` instead. */\n proceed: false;\n output: TOutput;\n}\n\nexport interface ToolAfterHookContext<\n TInput = unknown,\n TOutput = unknown,\n TContext = unknown,\n TMetadata extends Record = Record,\n> extends ToolHookContext {\n /** Tool output when execution completed. Undefined when execution failed before producing output. */\n output?: TOutput;\n /** Error thrown by the tool, if execution failed. */\n error?: unknown;\n}\n\nexport interface ToolHooks<\n TInput = unknown,\n TOutput = unknown,\n TContext = unknown,\n TMetadata extends Record = Record,\n> {\n beforeToolCall?: (\n context: ToolHookContext,\n ) => void | ToolBeforeHookResult | Promise>;\n afterToolCall?: (context: ToolAfterHookContext) => void | Promise;\n}\n\nexport type ToolPayloadTransformTarget = 'display' | 'transcript';\n\nexport type ToolPayloadTransformPhase =\n | 'input-delta'\n | 'input-available'\n | 'output-available'\n | 'error'\n | 'approval'\n | 'suspend'\n | 'resume';\n\nexport type ToolPayloadTransformContext = {\n target: ToolPayloadTransformTarget;\n phase: ToolPayloadTransformPhase;\n toolName: string;\n toolCallId: string;\n input?: TInput;\n inputTextDelta?: string;\n output?: TOutput;\n error?: TError;\n suspendPayload?: unknown;\n resumeData?: unknown;\n providerMetadata?: Record;\n context?: Record;\n};\n\nexport type ToolPayloadTransformResult = unknown;\n\nexport type ToolPayloadTransformFunction = (\n context: ToolPayloadTransformContext,\n) => ToolPayloadTransformResult | Promise;\n\nexport type ToolPayloadTransformTargetConfig = {\n input?: ToolPayloadTransformFunction;\n inputDelta?: ToolPayloadTransformFunction;\n output?: ToolPayloadTransformFunction;\n error?: ToolPayloadTransformFunction;\n approval?: ToolPayloadTransformFunction;\n suspend?: ToolPayloadTransformFunction;\n resume?: ToolPayloadTransformFunction;\n};\n\nexport type ToolPayloadTransform = Partial<\n Record>\n>;\n\nexport type ToolPayloadTransformPolicy = {\n transformToolPayload?: ToolPayloadTransformFunction;\n targets?: ToolPayloadTransformTarget[];\n};\n\n/**\n * Observability helpers available on the tool execution context.\n * Wraps child span creation and structured log emission in a\n * null-safe API that callers never need to check — when no tracing\n * context is active, `span` runs the function directly and `log` is\n * a no-op.\n */\nexport interface ToolObserve {\n span(name: string, fn: () => Promise | T, attributes?: Record): Promise;\n log(level: 'debug' | 'info' | 'warn' | 'error' | 'fatal', message: string, data?: Record): void;\n}\n\n/**\n * A no-op ToolObserve implementation. `span` runs the function\n * directly; `log` does nothing. Used as the default when no\n * collector/tracing context is active, so user code never needs to\n * null-check `observe`.\n */\nexport const noopObserve: ToolObserve = {\n async span(_name: string, fn: () => Promise | T): Promise {\n return fn();\n },\n log(): void {},\n};\n\n/**\n * MCP-specific context properties available during tool execution in MCP environments.\n */\n// Agent tool execution context - properties specific when tools are executed by agents\nexport interface AgentToolExecutionContext {\n // Always present when called from agent context\n agentId: string;\n toolCallId: string;\n messages: any[];\n suspend: (suspendPayload: TSuspend, suspendOptions?: SuspendOptions) => Promise;\n\n // Optional - memory identifiers\n threadId?: string;\n resourceId?: string;\n\n // Optional - only present if tool was previously suspended\n resumeData?: TResume;\n\n // Optional - original WritableStream passed from AI SDK (without Mastra metadata wrapping)\n writableStream?: WritableStream;\n\n /**\n * Flushes the parent stream's pending messages to persistent storage.\n * See `MastraToolInvocationOptions.flushMessages` for details.\n */\n flushMessages?: () => Promise;\n}\n\n// Workflow tool execution context - properties specific when tools are executed in workflows\nexport interface WorkflowToolExecutionContext {\n // Always present when called from workflow context\n runId: string;\n workflowId: string;\n state: any;\n setState: (state: any) => void;\n suspend: (suspendPayload: TSuspend, suspendOptions?: SuspendOptions) => Promise;\n // Optional - only present if workflow step was previously suspended\n resumeData?: TResume;\n}\n\n// MCP tool execution context - properties specific when tools are executed via Model Context Protocol\nexport interface MCPToolExecutionContext {\n /** MCP protocol context passed by the server */\n extra: RequestHandlerExtra;\n /** Elicitation handler for interactive user input during tool execution */\n elicitation: {\n sendRequest: (request: ElicitRequest['params']) => Promise;\n };\n}\n\n/**\n * Extended version of ToolInvocationOptions that includes Mastra-specific properties\n * for suspend/resume functionality, stream writing, and tracing context.\n *\n * This is used by CoreTool/InternalCoreTool for AI SDK compatibility (AI SDK expects this signature).\n * Mastra v1.0 tools (ToolAction) use ToolExecutionContext instead.\n *\n * CoreToolBuilder acts as the adapter layer:\n * - Receives: AI SDK calls with MastraToolInvocationOptions\n * - Converts to: ToolExecutionContext for Mastra tool execution\n * - Returns: Results back to AI SDK\n */\nexport type MastraToolInvocationOptions = ToolInvocationOptions &\n Partial & {\n suspend?: (suspendPayload: any, suspendOptions?: SuspendOptions) => Promise;\n resumeData?: any;\n outputWriter?: OutputWriter;\n /**\n * Optional MCP-specific context passed when tool is executed in MCP server.\n * This is populated by the MCP server and passed through to the tool's execution context.\n */\n mcp?: MCPToolExecutionContext;\n /**\n * Workspace for tool execution. When provided at execution time, this overrides\n * any workspace configured at tool build time. Allows dynamic workspace selection\n * per-step via prepareStep.\n */\n workspace?: Workspace;\n /**\n * Request context for tool execution. When provided at execution time, this overrides\n * any requestContext configured at tool build time. Allows workflow steps to forward\n * their requestContext (e.g., authenticated API clients, feature flags) to tools.\n */\n requestContext?: RequestContext;\n /** Trusted server-side signal for this tool FGA check. */\n actor?: ActorSignal;\n /**\n * Flushes the parent stream's pending messages to persistent storage.\n *\n * The agent stream batches message saves through a `SaveQueueManager`\n * (100ms debounce). Tools that read the thread's persisted history\n * mid-stream (e.g. cloning the thread, exporting it, handing off to a\n * sibling agent) must call this first, otherwise the store will be\n * missing the latest user / assistant messages.\n *\n * Populated automatically by the agent tool-call step. No-op when the\n * stream is not memory-backed.\n */\n flushMessages?: () => Promise;\n /** Observability helper to expose on the final tool execution context. */\n observe?: ToolObserve;\n };\n\n/**\n * The type of tool registered with the MCP server.\n * This is used to categorize tools in the MCP Server playground.\n * If not specified, it defaults to a regular tool.\n */\nexport type MCPToolType = 'agent' | 'workflow';\n\n/**\n * Metadata identifying a tool as originating from an MCP server.\n * Set automatically by the MCP client when creating tools.\n * Used by CoreToolBuilder to create MCP_TOOL_CALL spans instead of TOOL_CALL spans.\n */\nexport interface McpMetadata {\n serverName: string;\n serverVersion?: string;\n /** Instructions advertised by the MCP server during initialize. */\n serverInstructions?: string;\n /** Whether the agent should append these instructions to its system prompt. Defaults to false (opt-in). */\n forwardInstructions?: boolean;\n /** Maximum number of characters to forward into the agent system prompt. */\n instructionsMaxLength?: number;\n}\n\n/**\n * MCP Tool Annotations for describing tool behavior and UI presentation.\n * These annotations are part of the MCP protocol and are used by clients\n * like OpenAI Apps SDK to control tool card display and permission hints.\n *\n * @see https://spec.modelcontextprotocol.io/specification/2025-03-26/server/tools/#tool-annotations\n */\nexport interface ToolAnnotations {\n /**\n * A human-readable title for the tool.\n * Used for display purposes in UI components.\n */\n title?: string;\n /**\n * If true, the tool does not modify its environment.\n * This hint indicates the tool only reads data and has no side effects.\n * @default false\n */\n readOnlyHint?: boolean;\n /**\n * If true, the tool may perform destructive updates to its environment.\n * If false, the tool performs only additive updates.\n * This hint helps clients determine if confirmation should be required.\n * @default true\n */\n destructiveHint?: boolean;\n /**\n * If true, calling the tool repeatedly with the same arguments\n * will have no additional effect on its environment.\n * This hint indicates idempotent behavior.\n * @default false\n */\n idempotentHint?: boolean;\n /**\n * If true, this tool may interact with an \"open world\" of external\n * entities (e.g., web search, external APIs).\n * If false, the tool's domain is closed and fully defined.\n * @default true\n */\n openWorldHint?: boolean;\n}\n\n// MCP-specific properties for tools\nexport interface MCPToolProperties {\n /**\n * The type of tool registered with the MCP server.\n * This is used to categorize tools in the MCP Server playground.\n * If not specified, it defaults to a regular tool.\n */\n toolType?: MCPToolType;\n /**\n * MCP tool annotations for describing tool behavior and UI presentation.\n * These are exposed via MCP protocol and used by clients like OpenAI Apps SDK.\n * @see https://spec.modelcontextprotocol.io/specification/2025-03-26/server/tools/#tool-annotations\n */\n annotations?: ToolAnnotations;\n /**\n * Arbitrary metadata that will be passed through to MCP clients.\n * This field allows custom metadata to be attached to tools for\n * client-specific functionality.\n */\n _meta?: Record;\n}\n\n/**\n * CoreTool is the AI SDK-compatible tool format used when passing tools to the AI SDK.\n * This matches the AI SDK's Tool interface.\n *\n * CoreToolBuilder converts Mastra tools (ToolAction) to this format and handles the\n * signature transformation from Mastra's (inputData, context) to AI SDK format (params, options).\n *\n * Key differences from ToolAction:\n * - Uses 'parameters' instead of 'inputSchema' (AI SDK naming)\n * - Execute signature: (params, options: MastraToolInvocationOptions) (AI SDK format)\n * - Supports FlexibleSchema | Schema for broader AI SDK compatibility\n */\nexport type CoreTool = {\n description?: string;\n parameters: FlexibleSchema | Schema;\n outputSchema?: FlexibleSchema | Schema;\n execute?: (params: any, options: MastraToolInvocationOptions) => Promise;\n /**\n * Enables strict tool input generation for providers that support it.\n */\n strict?: boolean;\n /**\n * Provider-specific options passed to the model when this tool is used.\n */\n providerOptions?: Record>;\n /**\n * Optional MCP-specific properties.\n * Only populated when the tool is being used in an MCP context.\n */\n mcp?: MCPToolProperties;\n /**\n * Optional function to transform tool output before returning to the model.\n * Receives the raw tool output and returns a transformed representation.\n * Passed through from the original tool definition.\n */\n toModelOutput?: (output: unknown) => unknown;\n transform?: ToolPayloadTransform;\n /**\n * Examples of valid tool inputs. Each example contains an `input` object\n * showing what valid arguments look like.\n * Passed through to the AI SDK which forwards them to model providers\n * that support input examples (e.g., Anthropic's `input_examples` beta feature).\n */\n inputExamples?: Array<{ input: Record }>;\n onInputStart?: (options: ToolCallOptions) => void | PromiseLike;\n onInputDelta?: (options: { inputTextDelta: string } & ToolCallOptions) => void | PromiseLike;\n onInputAvailable?: (options: { input: any } & ToolCallOptions) => void | PromiseLike;\n onOutput?: (\n options: { output: any; toolName: string } & Omit,\n ) => void | PromiseLike;\n /** Background task configuration for this tool. */\n background?: ToolBackgroundConfig;\n} & (\n | {\n type?: 'function' | undefined;\n id?: string;\n }\n | {\n type: 'provider-defined';\n id: `${string}.${string}`;\n args: Record;\n }\n);\n\n/**\n * InternalCoreTool is identical to CoreTool but with stricter typing.\n * Used internally where we know the schema has already been converted to AI SDK Schema format.\n *\n * The only difference: parameters must be Schema (not FlexibleSchema | Schema)\n */\nexport type InternalCoreTool = {\n description?: string;\n parameters: Schema;\n outputSchema?: Schema;\n execute?: (params: any, options: MastraToolInvocationOptions) => Promise;\n /**\n * Enables strict tool input generation for providers that support it.\n */\n strict?: boolean;\n /**\n * Provider-specific options passed to the model when this tool is used.\n */\n providerOptions?: Record>;\n /**\n * Optional MCP-specific properties.\n * Only populated when the tool is being used in an MCP context.\n */\n mcp?: MCPToolProperties;\n /**\n * Optional function to transform tool output before returning to the model.\n * Receives the raw tool output and returns a transformed representation.\n * Passed through from the original tool definition.\n */\n toModelOutput?: (output: unknown) => unknown;\n transform?: ToolPayloadTransform;\n /**\n * Examples of valid tool inputs. Each example contains an `input` object\n * showing what valid arguments look like.\n * Passed through to the AI SDK which forwards them to model providers\n * that support input examples (e.g., Anthropic's `input_examples` beta feature).\n */\n inputExamples?: Array<{ input: Record }>;\n onInputStart?: (options: ToolCallOptions) => void | PromiseLike;\n onInputDelta?: (options: { inputTextDelta: string } & ToolCallOptions) => void | PromiseLike;\n onInputAvailable?: (options: { input: any } & ToolCallOptions) => void | PromiseLike;\n onOutput?: (\n options: { output: any; toolName: string } & Omit,\n ) => void | PromiseLike;\n /** Background task configuration for this tool. */\n background?: ToolBackgroundConfig;\n} & (\n | {\n type?: 'function' | undefined;\n id?: string;\n }\n | {\n type: 'provider-defined';\n id: `${string}.${string}`;\n args: Record;\n }\n);\n\n// Unified tool execution context that works for all scenarios\nexport interface ToolExecutionContext<\n TSuspend = unknown,\n TResume = unknown,\n TRequestContext extends Record | unknown = unknown,\n> extends Partial {\n // ============ Common properties (available in all contexts) ============\n mastra?: MastraUnion;\n requestContext?: RequestContext;\n abortSignal?: AbortSignal;\n /** Trusted server-side signal forwarded for nested FGA checks. */\n actor?: ActorSignal;\n\n /**\n * Workspace available for tool execution. When provided, tools can access:\n * - workspace.filesystem - for file operations (read, write, list, etc.)\n * - workspace.sandbox - for command execution\n *\n * This allows tools to work with the agent's configured workspace.\n */\n workspace?: Workspace;\n\n /**\n * Browser available for tool execution. When provided, tools can access\n * browser capabilities for web automation, screenshots, and data extraction.\n *\n * The browser is lazily initialized - it will be launched on first use.\n */\n browser?: MastraBrowser;\n\n // Writer is created by Mastra for ALL contexts (agent, workflow, direct execution)\n // Wraps chunks with metadata (toolCallId, toolName, runId) before passing to underlying stream\n writer?: ToolStream;\n\n // ============ Context-specific nested properties ============\n\n // Agent-specific properties\n agent?: AgentToolExecutionContext;\n\n // Workflow-specific properties\n workflow?: WorkflowToolExecutionContext;\n\n // MCP (Model Context Protocol) specific context\n mcp?: MCPToolExecutionContext;\n\n /**\n * Observability helpers for recording child spans and structured logs\n * from inside a tool's execute function. Always provided — when no\n * tracing context is active, `span` runs the function directly and\n * `log` is a no-op. No null-checking needed.\n *\n * ```ts\n * execute: async ({ userId }, { observe }) => {\n * observe.log('info', 'fetching user', { userId })\n * return observe.span('fetch user', () => fetch(`/api/users/${userId}`))\n * }\n * ```\n */\n observe: ToolObserve;\n}\n\nexport interface ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspend = unknown,\n TResume = unknown,\n TContext extends ToolExecutionContext = ToolExecutionContext,\n TId extends string = string,\n TRequestContext extends Record | unknown = unknown,\n> {\n id: TId;\n description: string;\n inputSchema?: PublicSchema;\n outputSchema?: PublicSchema;\n suspendSchema?: PublicSchema;\n resumeSchema?: PublicSchema;\n /**\n * Optional schema for validating request context values.\n * When provided, the request context will be validated against this schema before tool execution.\n * If validation fails, a validation error is returned instead of executing the tool.\n */\n requestContextSchema?: PublicSchema;\n /**\n * Optional MCP-specific properties.\n * Only populated when the tool is being used in an MCP context.\n */\n mcp?: MCPToolProperties;\n /**\n * Optional function to transform tool output before returning to the model.\n * Receives the raw tool output and returns a transformed representation.\n * Passed through from the original tool definition.\n */\n toModelOutput?: (output: TSchemaOut) => unknown;\n /**\n * Optional target-aware transform for tool payloads that leave runtime.\n *\n * Runtime execution still receives raw inputs and outputs. These transforms\n * are used by display and transcript serializers to avoid exposing internal\n * payload fields.\n */\n transform?: ToolPayloadTransform;\n // Execute signature with unified context type\n // First parameter: raw input data (validated against inputSchema)\n // Second parameter: unified execution context with all metadata\n // Returns: The expected output, a validation error, or void when the tool\n // suspends via `context.agent?.suspend?.(...)` / `context.workflow?.suspend?.(...)`.\n // When `suspend` has been called, the tool runtime skips output validation\n // (see `Tool.execute` in tool.ts), so returning `undefined` after `suspend`\n // is the supported idiom (e.g. `return await suspend(...)`).\n // Note: When no outputSchema is provided, returns any to allow property access\n // Note: For outputSchema, we use the input type because Zod transforms are applied during validation\n // Note: { error?: never } enables inline type narrowing with 'error' in result checks\n execute?: (inputData: TSchemaIn, context: TContext) => Promise;\n mastra?: Mastra;\n /**\n * Whether the tool requires explicit user approval before execution.\n * Pass `true` to always require approval, or a function evaluated per-call\n * with the tool input (and optional request context/workspace) to require\n * approval conditionally.\n */\n requireApproval?:\n | boolean\n | ((\n input: TSchemaIn,\n ctx?: { requestContext?: Record; workspace?: Workspace },\n ) => boolean | Promise);\n /**\n * Enables strict tool input generation for providers that support it.\n * When enabled, supported providers will attempt to generate arguments\n * that exactly match the tool schema.\n */\n strict?: boolean;\n /**\n * Provider-specific options passed to the model when this tool is used.\n * Keys are provider names (e.g., 'anthropic', 'openai'), values are provider-specific configs.\n * @example\n * ```typescript\n * providerOptions: {\n * anthropic: {\n * cacheControl: { type: 'ephemeral' }\n * }\n * }\n * ```\n */\n providerOptions?: Record>;\n /**\n * Metadata identifying this tool as originating from an MCP server.\n * Set automatically by the MCP client when creating tools.\n * Used by CoreToolBuilder to create MCP_TOOL_CALL spans instead of TOOL_CALL spans.\n */\n mcpMetadata?: McpMetadata;\n /**\n * Examples of valid tool inputs. Each example contains an `input` object\n * showing what valid arguments look like.\n * Passed through to the AI SDK which forwards them to model providers\n * that support input examples (e.g., Anthropic's `input_examples` beta feature).\n */\n inputExamples?: Array<{ input: Record }>;\n onInputStart?: (options: ToolCallOptions) => void | PromiseLike;\n onInputDelta?: (\n options: {\n inputTextDelta: string;\n } & ToolCallOptions,\n ) => void | PromiseLike;\n onInputAvailable?: (\n options: {\n input: TSchemaIn;\n } & ToolCallOptions,\n ) => void | PromiseLike;\n onOutput?: (\n options: {\n output: TSchemaOut;\n toolName: string;\n } & Omit,\n ) => void | PromiseLike;\n /**\n * Background task configuration for this tool.\n * When enabled, the tool can be executed in the background while the agent conversation continues.\n */\n background?: ToolBackgroundConfig;\n}\n","import type { Schema } from '@internal/ai-v6';\nimport type { ProviderDefinedTool, ToolExecutionOptions } from '@internal/external-types';\nimport {\n OpenAIReasoningSchemaCompatLayer,\n OpenAISchemaCompatLayer,\n GoogleSchemaCompatLayer,\n AnthropicSchemaCompatLayer,\n DeepSeekSchemaCompatLayer,\n MetaSchemaCompatLayer,\n applyCompatLayer,\n convertZodSchemaToAISDKSchema,\n jsonSchema,\n} from '@mastra/schema-compat';\nimport type { JSONSchema7Definition } from 'json-schema';\nimport { z } from 'zod/v4';\nimport { MastraFGAPermissions } from '../../auth/ee';\nimport { backgroundOverrideJsonSchema, backgroundOverrideZodSchema } from '../../background-tasks';\nimport { MastraBase } from '../../base';\nimport { ErrorCategory, MastraError, ErrorDomain } from '../../error';\nimport type { Mastra } from '../../mastra';\nimport { SpanType, wrapMastra, EntityType, getOrCreateSpan, createObservabilityContext } from '../../observability';\nimport type { AnySpan } from '../../observability';\nimport { executeWithContext } from '../../observability/utils';\nimport { RequestContext } from '../../request-context';\nimport { isStandardSchemaWithJSON, toStandardSchema, standardSchemaToJSONSchema } from '../../schema';\nimport type { StandardSchemaWithJSON } from '../../schema';\nimport { getNeedsApprovalFn, isVercelTool, isProviderDefinedTool } from '../../tools/toolchecks';\nimport type { ToolOptions } from '../../utils';\nimport { safeStringify } from '../../utils';\nimport { isZodObject, safeExtendZodObject } from '../../utils/zod-utils';\n\nimport type { SuspendOptions } from '../../workflows';\nimport { ToolStream } from '../stream';\nimport type {\n CoreTool,\n McpMetadata,\n MastraToolInvocationOptions,\n NeedsApprovalFn,\n ToolAction,\n VercelTool,\n VercelToolV5,\n} from '../types';\nimport { noopObserve } from '../types';\nimport { validateToolInput, validateToolOutput, validateToolSuspendData } from '../validation';\n\n/**\n * Merge two RequestContexts so non-serializable values survive the evented\n * workflow engine's toJSON/reconstruct cycle.\n *\n * The evented engine serialises the RequestContext via `toJSON()` when\n * publishing workflow events. Values that fail `JSON.stringify` (functions,\n * objects with circular references — e.g. the `harness` context) are silently\n * dropped. The reconstructed RC handed to steps is therefore *degraded*.\n *\n * Tools, however, also hold a reference to the *original* RC captured during\n * tool conversion (the \"closure\" RC). By merging both — exec first, then\n * closure on top — keys that survived serialisation are preserved while\n * non-serializable keys from the closure (like `harness`) are restored.\n */\nfunction mergeRequestContexts(\n closureRC: RequestContext | undefined,\n execRC: RequestContext | undefined,\n): RequestContext {\n if (!closureRC && !execRC) return new RequestContext();\n if (!closureRC) return execRC instanceof RequestContext ? execRC : new RequestContext();\n if (!execRC || !(execRC instanceof RequestContext) || execRC.size() === 0) return closureRC;\n\n const merged = new RequestContext();\n // Start with the evented engine's serialised snapshot\n for (const [key, value] of execRC.entries()) {\n merged.set(key, value);\n }\n // Overlay closure values — restores non-serializable keys and ensures the\n // authoritative (non-degraded) copy wins for keys present in both.\n for (const [key, value] of closureRC.entries()) {\n merged.set(key, value);\n }\n return merged;\n}\n\n/**\n * Types that can be converted to Mastra tools.\n * Includes provider-defined tools from external packages via ProviderDefinedTool.\n */\nexport type ToolToConvert = VercelTool | ToolAction | VercelToolV5 | ProviderDefinedTool;\nexport type LogType = 'tool' | 'toolset' | 'client-tool';\n\ninterface LogOptions {\n agentName?: string;\n toolName: string;\n type?: 'tool' | 'toolset' | 'client-tool';\n}\n\ninterface LogMessageOptions {\n start: string;\n error: string;\n logData: Record;\n}\n\n/**\n * Detect Zod v4 schemas. Zod v3 stores the type name as `_def.typeName`\n * (e.g. \"ZodObject\"); Zod v4 stores it as `_def.type` (e.g. \"object\"). We\n * cannot use `instanceof` here because both Zod versions may be loaded in the\n * same process and the prototype identity is not guaranteed.\n */\nfunction isZodV4Schema(schema: unknown): boolean {\n const def = (schema as any)?._def;\n return !!def && typeof def.type === 'string' && !def.typeName;\n}\n\n/**\n * Build a Standard Schema that:\n * - exposes the spliced JSON Schema (with `_background`/`suspendedToolRunId`/\n * `resumeData` properties added) so provider compat layers see the override\n * fields when serializing the tool to an LLM, and\n * - delegates runtime `validate` to the *original* schema so Zod v3\n * `.transform()` / `.default()` / `.refine()` and other Standard Schema\n * parsing behavior still run before `execute()` sees the args.\n *\n * Injected override keys (`_background`, `suspendedToolRunId`, `resumeData`)\n * are stripped from the input before delegating, then merged back into the\n * validated value so the inner `execute()` still receives them — matching the\n * Zod v4 `.extend()` path's behavior.\n *\n * If the original schema has no `~standard.validate` (e.g. a raw JSON Schema\n * with no Standard Schema wrapper), fall back to validating against the\n * spliced JSON Schema directly.\n */\nfunction buildJsonOverrideSchema(\n originalSchema: unknown,\n splicedJsonSchema: JSONSchema7Definition,\n injectedKeys: readonly string[],\n): StandardSchemaWithJSON {\n const fallback = toStandardSchema(splicedJsonSchema as any);\n const original = originalSchema as { '~standard'?: { validate?: (v: unknown) => any } } | undefined;\n const originalValidate = original?.['~standard']?.validate?.bind(original['~standard']);\n\n // Standard Schema for *just* the injected override fields, so we can validate\n // malformed override payloads (e.g. `_background: { enabled: \"yes\" }`) before\n // merging them into the result. Matches the Zod v4 `.extend()` path's\n // behavior, which validates these fields as part of the object.\n // See https://github.com/mastra-ai/mastra/pull/16915#discussion_r3282600679\n const splicedProperties =\n splicedJsonSchema && typeof splicedJsonSchema === 'object' && 'properties' in splicedJsonSchema\n ? ((splicedJsonSchema.properties ?? {}) as Record)\n : {};\n const injectedProperties: Record = {};\n for (const key of injectedKeys) {\n if (splicedProperties[key] !== undefined) injectedProperties[key] = splicedProperties[key];\n }\n const injectedValidator = toStandardSchema({\n type: 'object',\n properties: injectedProperties,\n additionalProperties: false,\n } as any);\n\n const stripInjected = (input: unknown) => {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return { stripped: input, injected: {} };\n const injected: Record = {};\n const stripped: Record = {};\n for (const [k, v] of Object.entries(input as Record)) {\n if (injectedKeys.includes(k)) injected[k] = v;\n else stripped[k] = v;\n }\n return { stripped, injected };\n };\n\n const validate = (input: unknown) => {\n const { stripped, injected } = stripInjected(input);\n\n const baseResult = originalValidate\n ? (originalValidate(stripped) as\n | { value: unknown }\n | { issues: readonly unknown[] }\n | Promise<{ value: unknown } | { issues: readonly unknown[] }>)\n : fallback['~standard'].validate(stripped);\n\n const injectedResult = injectedValidator['~standard'].validate(injected);\n\n const combine = (\n base: { value: unknown } | { issues: readonly unknown[] },\n inj: { value: unknown } | { issues: readonly unknown[] },\n ) => {\n const baseIssues = 'issues' in base ? (base.issues ?? []) : [];\n const injIssues = 'issues' in inj ? (inj.issues ?? []) : [];\n if (baseIssues.length || injIssues.length) {\n return { issues: [...baseIssues, ...injIssues] };\n }\n const baseValue = (base as { value: unknown }).value;\n const injValue = (inj as { value: unknown }).value;\n if (baseValue && typeof baseValue === 'object' && !Array.isArray(baseValue)) {\n const injMerged =\n injValue && typeof injValue === 'object' && !Array.isArray(injValue)\n ? (injValue as Record)\n : injected;\n return { value: { ...(baseValue as Record), ...injMerged } };\n }\n return base;\n };\n\n const baseIsPromise = baseResult && typeof (baseResult as Promise).then === 'function';\n const injIsPromise = injectedResult && typeof (injectedResult as Promise).then === 'function';\n if (baseIsPromise || injIsPromise) {\n return Promise.all([baseResult, injectedResult]).then(([b, i]) =>\n combine(\n b as { value: unknown } | { issues: readonly unknown[] },\n i as { value: unknown } | { issues: readonly unknown[] },\n ),\n );\n }\n return combine(\n baseResult as { value: unknown } | { issues: readonly unknown[] },\n injectedResult as { value: unknown } | { issues: readonly unknown[] },\n );\n };\n\n return {\n '~standard': {\n version: 1,\n vendor: 'mastra-json-override',\n validate,\n jsonSchema: fallback['~standard'].jsonSchema,\n },\n } as StandardSchemaWithJSON;\n}\n\nexport class CoreToolBuilder extends MastraBase {\n private originalTool: ToolToConvert;\n private options: ToolOptions;\n private logType?: LogType;\n\n constructor(input: {\n originalTool: ToolToConvert;\n options: ToolOptions;\n logType?: LogType;\n autoResumeSuspendedTools?: boolean;\n backgroundTaskEnabled?: boolean;\n }) {\n super({ name: 'CoreToolBuilder' });\n this.originalTool = input.originalTool;\n this.options = input.options;\n this.logType = input.logType;\n\n // Only inject the `_background` override schema for tools that are actually\n // eligible for background execution — otherwise every user tool's input\n // schema would be mutated with a v4 Zod field, which breaks v3-authored\n // tools (keyValidator._parse crashes in schema-compat validation).\n const isBackgroundEligible = !!input.backgroundTaskEnabled;\n const isResumableTool =\n input.autoResumeSuspendedTools ||\n (this.originalTool as unknown as ToolAction).id?.startsWith('agent-') ||\n (this.originalTool as unknown as ToolAction).id?.startsWith('workflow-');\n\n if (!isVercelTool(this.originalTool) && !isProviderDefinedTool(this.originalTool)) {\n if (isBackgroundEligible || isResumableTool) {\n let schema = this.originalTool.inputSchema;\n if (typeof schema === 'function') {\n schema = schema();\n }\n if (!schema) {\n schema = z.object({});\n }\n\n // Preferred path: when the user's input schema is a Zod v4 ZodObject\n // (the common case for tools authored with `zod` / `zod/v4`), keep using\n // `.extend()`. This preserves the exact JSON Schema shape that existing\n // provider compat layers + LLM recordings expect.\n //\n // Fallback path: for everything else (Zod v3 ZodObject, raw JSON Schema,\n // `JsonSchemaWrapper`, etc.) splice the override fields directly into a\n // JSON Schema. Mixing a Zod v4 wrapper (`backgroundOverrideZodSchema`,\n // `.nullable()`, `.optional()`) into a Zod v3 ZodObject's `.shape` is\n // what triggered the original crash:\n // `TypeError: keyValidator._parse is not a function`.\n if (isZodObject(schema) && isZodV4Schema(schema)) {\n let nextSchema: z.ZodObject = schema as z.ZodObject;\n if (isBackgroundEligible) {\n nextSchema = safeExtendZodObject(nextSchema, {\n _background: backgroundOverrideZodSchema,\n });\n }\n if (isResumableTool) {\n nextSchema = safeExtendZodObject(nextSchema, {\n suspendedToolRunId: z.string().describe('The runId of the suspended tool').nullable().optional(),\n resumeData: z\n .any()\n .describe('The resumeData object created from the resumeSchema of suspended tool')\n .optional(),\n });\n }\n this.originalTool.inputSchema = nextSchema;\n } else {\n // Normalize to Standard Schema, extract JSON Schema, splice overrides.\n const standardSchema = isStandardSchemaWithJSON(schema) ? schema : toStandardSchema(schema);\n const jsonSchema = standardSchemaToJSONSchema(standardSchema, { io: 'input' });\n\n if (jsonSchema && typeof jsonSchema === 'object' && jsonSchema.type === 'object') {\n const properties: Record = { ...(jsonSchema.properties ?? {}) };\n const injectedKeys: string[] = [];\n\n if (isBackgroundEligible) {\n properties._background = backgroundOverrideJsonSchema;\n injectedKeys.push('_background');\n }\n if (isResumableTool) {\n // Match the pre-PR JSON Schema shape so existing provider compat\n // layers + LLM recordings collapse it identically.\n properties.suspendedToolRunId = {\n type: ['string', 'null'],\n description: 'The runId of the suspended tool',\n };\n properties.resumeData = {\n description: 'The resumeData object created from the resumeSchema of suspended tool',\n };\n injectedKeys.push('suspendedToolRunId', 'resumeData');\n }\n\n // Preserve the original schema's runtime validator (Zod v3\n // `.transform()` / `.default()` / `.refine()` etc.) while exposing\n // the spliced JSON Schema for provider serialization. See\n // https://github.com/mastra-ai/mastra/pull/16915#discussion_r3282520408\n this.originalTool.inputSchema = buildJsonOverrideSchema(\n schema,\n { ...jsonSchema, properties },\n injectedKeys,\n );\n }\n }\n }\n }\n }\n\n // Helper to get parameters based on tool type\n private getParameters = () => {\n if (isVercelTool(this.originalTool)) {\n // Handle both 'parameters' (v4) and 'inputSchema' (v5) properties\n // Also handle case where the schema is a function that returns a schema\n let schema =\n this.originalTool.parameters ??\n ('inputSchema' in this.originalTool ? (this.originalTool as any).inputSchema : undefined) ??\n z.object({});\n\n // If schema is a function, call it to get the actual schema\n if (typeof schema === 'function') {\n schema = schema();\n }\n\n return schema;\n }\n\n // For Mastra tools, inputSchema might also be a function\n let schema = this.originalTool.inputSchema;\n\n if (isStandardSchemaWithJSON(schema)) {\n return schema;\n }\n\n // If schema is a function, call it to get the actual schema\n if (typeof schema === 'function') {\n schema = schema();\n }\n\n return schema;\n };\n\n private getOutputSchema = () => {\n if ('outputSchema' in this.originalTool) {\n let schema = this.originalTool.outputSchema;\n\n if (isStandardSchemaWithJSON(schema)) {\n return schema;\n }\n\n // If schema is a function, call it to get the actual schema\n if (typeof schema === 'function') {\n schema = schema();\n }\n\n return schema;\n }\n\n return null;\n };\n\n private getResumeSchema = () => {\n if ('resumeSchema' in this.originalTool) {\n let schema = this.originalTool.resumeSchema;\n\n // If schema is a function, call it to get the actual schema\n if (typeof schema === 'function') {\n schema = schema();\n }\n\n return schema;\n }\n return null;\n };\n\n private getSuspendSchema = () => {\n if ('suspendSchema' in this.originalTool) {\n let schema = this.originalTool.suspendSchema;\n\n // If schema is a function, call it to get the actual schema\n if (typeof schema === 'function') {\n schema = schema();\n }\n\n return schema;\n }\n return null;\n };\n\n // For provider-defined tools, we need to include all required properties\n // AI SDK v5 uses type: 'provider-defined', AI SDK v6 uses type: 'provider'\n private buildProviderTool(tool: ToolToConvert): (CoreTool & { id: `${string}.${string}` }) | undefined {\n if (\n 'type' in tool &&\n (tool.type === 'provider-defined' || tool.type === 'provider') &&\n 'id' in tool &&\n typeof tool.id === 'string' &&\n tool.id.includes('.')\n ) {\n // Get schema directly from provider-defined tool (v4 uses parameters, v5 uses inputSchema)\n let parameters: unknown =\n 'parameters' in tool ? tool.parameters : 'inputSchema' in tool ? (tool as any).inputSchema : undefined;\n\n // If schema is a function, call it to get the actual schema\n if (typeof parameters === 'function') {\n parameters = parameters();\n }\n\n // Get output schema directly from provider-defined tool\n let outputSchema: unknown = 'outputSchema' in tool ? (tool as any).outputSchema : undefined;\n\n // If schema is a function, call it to get the actual schema\n if (typeof outputSchema === 'function') {\n outputSchema = outputSchema();\n }\n\n // Convert parameters to AI SDK Schema format\n let processedParameters;\n if (parameters !== undefined && parameters !== null) {\n if (typeof parameters === 'object' && 'jsonSchema' in parameters) {\n // Already in AI SDK Schema format\n processedParameters = parameters;\n } else if (isStandardSchemaWithJSON(parameters)) {\n // StandardSchemaWithJSON - extract the JSON schema and wrap it\n // Use input since parameters represent tool input\n const jsonSchema = standardSchemaToJSONSchema(parameters, { io: 'input' });\n processedParameters = { jsonSchema };\n } else {\n // Assume Zod schema - convert to AI SDK Schema\n processedParameters = convertZodSchemaToAISDKSchema(parameters as any);\n }\n } else {\n // No schema provided - create default empty object schema for AI SDK v1 compatibility\n // OpenAI requires at minimum type: \"object\" even for tools without parameters\n processedParameters = {\n jsonSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n };\n }\n\n // Convert output schema to AI SDK Schema format if present\n let processedOutputSchema;\n if (outputSchema !== undefined && outputSchema !== null) {\n if (typeof outputSchema === 'object' && 'jsonSchema' in outputSchema) {\n // Already in AI SDK Schema format\n processedOutputSchema = outputSchema;\n } else if (isStandardSchemaWithJSON(outputSchema)) {\n // StandardSchemaWithJSON - extract the JSON schema and wrap it\n const jsonSchema = standardSchemaToJSONSchema(outputSchema);\n processedOutputSchema = { jsonSchema };\n } else {\n // Assume Zod schema - convert to AI SDK Schema\n processedOutputSchema = convertZodSchemaToAISDKSchema(outputSchema as any);\n }\n }\n\n return {\n ...(processedOutputSchema ? { outputSchema: processedOutputSchema } : {}),\n type: 'provider-defined' as const,\n id: tool.id as `${string}.${string}`,\n // V5 SDK factories set a hardcoded `name` (e.g. \"web_search\" for\n // anthropic.web_search_20250305). Preserve it so that when this tool\n // is later used with a V6 provider, the bidirectional toolNameMapping\n // resolves the correct model-facing name instead of the versioned ID.\n ...('name' in tool && typeof tool.name === 'string' ? { name: tool.name } : {}),\n args: ('args' in this.originalTool ? this.originalTool.args : {}) as Record,\n description: tool.description,\n parameters: processedParameters,\n execute: this.originalTool.execute\n ? this.createExecute(\n this.originalTool,\n { ...this.options, description: this.originalTool.description },\n this.logType,\n )\n : undefined,\n toModelOutput: 'toModelOutput' in this.originalTool ? this.originalTool.toModelOutput : undefined,\n transform: 'transform' in this.originalTool ? this.originalTool.transform : undefined,\n inputExamples: 'inputExamples' in this.originalTool ? this.originalTool.inputExamples : undefined,\n } as unknown as (CoreTool & { id: `${string}.${string}` }) | undefined;\n }\n\n return undefined;\n }\n\n private createLogMessageOptions({ agentName, toolName, type }: LogOptions): LogMessageOptions {\n const toolType = type === 'toolset' ? 'toolset' : 'tool';\n return {\n start: `Executing ${toolType}`,\n error: `Failed ${toolType} execution`,\n logData: { agent: agentName, tool: toolName },\n };\n }\n\n private createExecute(tool: ToolToConvert, options: ToolOptions, logType?: 'tool' | 'toolset' | 'client-tool') {\n // don't add memory, mastra, or tracing context to logging (tracingContext may contain sensitive observability credentials)\n const {\n logger,\n mastra: _mastra,\n memory: _memory,\n requestContext,\n model,\n tracingContext: _tracingContext,\n tracingPolicy: _tracingPolicy,\n ...rest\n } = options;\n const logModelObject = {\n modelId: model?.modelId,\n provider: model?.provider,\n specificationVersion: model?.specificationVersion,\n };\n\n const { start, logData } = this.createLogMessageOptions({\n agentName: options.agentName,\n toolName: options.name,\n type: logType,\n });\n\n // Extract MCP metadata once with proper typing to avoid repeated unsafe casts\n const mcpMeta =\n !isVercelTool(tool) && 'mcpMetadata' in tool ? (tool as { mcpMetadata?: McpMetadata }).mcpMetadata : undefined;\n\n const execFunction = async (args: unknown, execOptions: MastraToolInvocationOptions, toolSpan?: AnySpan) => {\n try {\n let result;\n let suspendData = null;\n\n if (isVercelTool(tool)) {\n // Handle Vercel tools (AI SDK tools)\n result = await executeWithContext({\n span: toolSpan,\n fn: async () => tool?.execute?.(args, execOptions as ToolExecutionOptions),\n });\n } else {\n // Handle Mastra tools - wrap mastra instance with tracing context for context propagation\n\n /**\n * MASTRA INSTANCE TYPES IN TOOL EXECUTION:\n *\n * Full Mastra & MastraPrimitives (has getAgent, getWorkflow, etc.):\n * - Auto-generated workflow tools from agent.listWorkflows()\n * - These get this.#mastra directly and can be wrapped\n *\n * MastraPrimitives only (limited interface):\n * - Memory tools (from memory.listTools())\n * - Assigned tools (agent.tools)\n * - Toolset tools (from toolsets)\n * - Client tools (passed as tools in generate/stream options)\n * - These get mastraProxy and have limited functionality\n *\n * TODO: Consider providing full Mastra instance to more tool types for enhanced functionality\n */\n // Wrap mastra with tracing context - wrapMastra will handle whether it's a full instance or primitives\n const wrappedMastra = options.mastra ? wrapMastra(options.mastra, { currentSpan: toolSpan }) : options.mastra;\n\n const resumeSchema = this.getResumeSchema();\n // Pass raw args as first parameter, context as second\n // Properly structure context based on execution source\n const baseContext = {\n threadId: options.threadId,\n resourceId: options.resourceId,\n mastra: wrappedMastra,\n memory: options.memory,\n runId: options.runId,\n requestContext: mergeRequestContexts(options.requestContext, execOptions.requestContext),\n actor: execOptions.actor,\n // Workspace for file operations and command execution\n // Execution-time workspace (from prepareStep/processInputStep) takes precedence over build-time workspace\n workspace: execOptions.workspace ?? options.workspace,\n // Browser for web automation (lazily initialized on first use)\n browser: options.browser,\n observe: execOptions.observe ?? noopObserve,\n writer: new ToolStream(\n {\n prefix: 'tool',\n callId: execOptions.toolCallId,\n name: options.name,\n runId: options.runId!,\n },\n options.outputWriter || execOptions.outputWriter,\n ),\n ...createObservabilityContext({ currentSpan: toolSpan }),\n abortSignal: execOptions.abortSignal,\n suspend: (args: any, suspendOptions?: SuspendOptions) => {\n suspendData = args;\n const newSuspendOptions = {\n ...(suspendOptions ?? {}),\n resumeSchema:\n suspendOptions?.resumeSchema ??\n (resumeSchema\n ? JSON.stringify(standardSchemaToJSONSchema(toStandardSchema(resumeSchema), { io: 'input' }))\n : undefined),\n };\n return execOptions.suspend?.(args, newSuspendOptions);\n },\n resumeData: execOptions.resumeData,\n };\n\n // Check if this is agent execution\n // Agent execution takes precedence over workflow execution because agents may\n // use workflows internally for their agentic loop\n // Note: AI SDK v4 doesn't pass toolCallId/messages, so we also check for agentName and threadId\n const isAgentExecution =\n (execOptions.toolCallId && execOptions.messages) ||\n (options.agentName && options.threadId && !options.workflowId);\n\n // Check if this is workflow execution (has workflow properties in options)\n // Only consider it workflow execution if it's NOT agent execution\n const isWorkflowExecution = !isAgentExecution && (options.workflow || options.workflowId);\n\n let toolContext;\n if (isAgentExecution) {\n // Nest agent-specific properties under 'agent' key\n // Do NOT include workflow context even if workflow properties exist\n // (agents use workflows internally but tools should see agent context)\n const { suspend, resumeData, threadId, resourceId, ...restBaseContext } = baseContext;\n toolContext = {\n ...restBaseContext,\n agent: {\n agentId: options.agentId || '',\n toolCallId: execOptions.toolCallId || '',\n messages: execOptions.messages || [],\n suspend,\n resumeData,\n threadId,\n resourceId,\n outputWriter: execOptions.outputWriter,\n flushMessages: execOptions.flushMessages,\n },\n };\n } else if (isWorkflowExecution) {\n // Nest workflow-specific properties under 'workflow' key\n const { suspend, resumeData, ...restBaseContext } = baseContext;\n toolContext = {\n ...restBaseContext,\n workflow: options.workflow || {\n runId: options.runId,\n workflowId: options.workflowId,\n state: options.state,\n setState: options.setState,\n suspend,\n resumeData,\n },\n };\n } else if (execOptions.mcp) {\n // MCP execution context\n toolContext = {\n ...baseContext,\n mcp: execOptions.mcp,\n };\n } else {\n // Direct execution or unknown context\n toolContext = baseContext;\n }\n\n const resumeData = execOptions.resumeData;\n\n if (resumeData) {\n const resumeValidation = validateToolInput(resumeSchema, resumeData, options.name);\n if (resumeValidation.error) {\n logger?.warn(resumeValidation.error.message);\n toolSpan?.end({ output: resumeValidation.error, attributes: { success: false } });\n return resumeValidation.error as any;\n }\n }\n\n result = await executeWithContext({ span: toolSpan, fn: async () => tool?.execute?.(args, toolContext) });\n }\n\n if (suspendData) {\n const suspendSchema = this.getSuspendSchema();\n const suspendValidation = validateToolSuspendData(suspendSchema, suspendData, options.name);\n if (suspendValidation.error) {\n logger?.warn(suspendValidation.error.message);\n toolSpan?.end({ output: suspendValidation.error, attributes: { success: false } });\n return suspendValidation.error as any;\n }\n }\n\n // Skip validation if suspend was called without a result\n const shouldSkipValidation = typeof result === 'undefined' && !!suspendData;\n if (shouldSkipValidation) {\n toolSpan?.end({ output: result, attributes: { success: true } });\n return result;\n }\n\n // Validate output for Vercel/AI SDK tools which don't have built-in validation\n // Mastra tools handle their own validation in Tool.execute() which properly\n // applies Zod transforms (e.g., .transform(), .pipe()) to the output\n if (isVercelTool(tool)) {\n const outputSchema = this.getOutputSchema();\n const outputValidation = validateToolOutput(outputSchema, result, options.name, false);\n if (outputValidation.error) {\n logger?.warn(outputValidation.error.message);\n toolSpan?.end({ output: outputValidation.error, attributes: { success: false } });\n return outputValidation.error;\n }\n result = outputValidation.data;\n }\n\n // Return result (validated for Vercel tools, already validated for Mastra tools)\n toolSpan?.end({ output: result, attributes: { success: true } });\n return result;\n } catch (error) {\n toolSpan?.error({ error: error as Error, attributes: { success: false } });\n throw error;\n }\n };\n\n return async (args: unknown, execOptions?: MastraToolInvocationOptions) => {\n let logger = options.logger || this.logger;\n\n // Create tool span early so validation failures are always observable.\n // Prefer execution-time tracingContext (passed at runtime for VNext methods)\n // Fall back to build-time context for Legacy methods (AI SDK v4 doesn't support passing custom options)\n const tracingContext = execOptions?.tracingContext || options.tracingContext;\n const toolRequestContext = execOptions?.requestContext ?? options.requestContext;\n const toolSpan = getOrCreateSpan({\n type: mcpMeta ? SpanType.MCP_TOOL_CALL : SpanType.TOOL_CALL,\n name: mcpMeta ? `mcp_tool: '${options.name}' on '${mcpMeta.serverName}'` : `tool: '${options.name}'`,\n input: args,\n entityType: EntityType.TOOL,\n entityId: options.name,\n entityName: options.name,\n attributes: mcpMeta\n ? {\n mcpServer: mcpMeta.serverName,\n serverVersion: mcpMeta.serverVersion,\n toolDescription: options.description,\n }\n : {\n toolDescription: options.description,\n toolType: logType || 'tool',\n },\n tracingPolicy: options.tracingPolicy,\n tracingContext: tracingContext,\n requestContext: toolRequestContext,\n mastra: options.mastra && 'observability' in options.mastra ? (options.mastra as Mastra) : undefined,\n });\n\n const fgaProvider = (options.mastra as any)?.getServer?.()?.fga;\n const user = toolRequestContext?.get('user');\n if (fgaProvider) {\n const { getAgentToolFGAResourceId, getMCPToolFGAResourceId, getStandaloneToolFGAResourceId, requireFGA } =\n await import('../../auth/ee/fga-check');\n const toolResourceId = mcpMeta?.serverName\n ? getMCPToolFGAResourceId(mcpMeta.serverName, options.name)\n : options.agentId\n ? getAgentToolFGAResourceId(options.agentId, options.name)\n : getStandaloneToolFGAResourceId(options.name);\n await requireFGA({\n fgaProvider,\n user,\n resource: { type: 'tool', id: toolResourceId },\n permission: MastraFGAPermissions.TOOLS_EXECUTE,\n requestContext: toolRequestContext,\n actor: execOptions?.actor,\n context: {\n resourceId: options.resourceId,\n },\n metadata: {\n toolName: options.name,\n agentId: options.agentId,\n agentName: options.agentName,\n runId: options.runId,\n threadId: options.threadId,\n executionResourceId: options.resourceId,\n mcpMetadata: mcpMeta,\n },\n });\n }\n\n try {\n logger.debug(start, { ...logData, ...rest, model: logModelObject, args });\n\n // Validate input parameters if schema exists\n // Use the processed schema for validation if available, otherwise fall back to original\n const parameters = this.getParameters();\n const { data, error } = validateToolInput(parameters, args, options.name);\n //suspendedToolRunId is only required when resumeData is provided\n const suspendedToolRunIdErrToIgnore =\n error?.message?.includes('suspendedToolRunId: Required') && !(args as Record)?.resumeData;\n if (error && !suspendedToolRunIdErrToIgnore) {\n logger.warn('Tool input validation failed', { ...logData, validationError: error.message });\n toolSpan?.end({ output: error, attributes: { success: false } });\n return error;\n }\n // Use validated/transformed data\n args = data;\n\n // there is a small delay in stream output so we add an immediate to ensure the stream is ready\n return await new Promise((resolve, reject) => {\n setImmediate(async () => {\n try {\n const result = await execFunction(args, execOptions!, toolSpan);\n resolve(result);\n } catch (err) {\n reject(err);\n }\n });\n });\n } catch (err) {\n const mastraError = new MastraError(\n {\n id: 'TOOL_EXECUTION_FAILED',\n domain: ErrorDomain.TOOL,\n category: ErrorCategory.USER,\n details: {\n errorMessage: String(err),\n argsJson: safeStringify(args),\n model: model?.modelId ?? '',\n },\n },\n err,\n );\n toolSpan?.error({ error: mastraError, attributes: { success: false } });\n logger.trackException(mastraError, { ...logData, ...rest, model: logModelObject, args });\n throw mastraError;\n }\n };\n }\n\n buildV5() {\n const builtTool = this.build();\n\n if (!builtTool.parameters) {\n throw new Error('Tool parameters are required');\n }\n\n const base = {\n ...builtTool,\n inputSchema: builtTool.parameters,\n onInputStart: 'onInputStart' in this.originalTool ? this.originalTool.onInputStart : undefined,\n onInputDelta: 'onInputDelta' in this.originalTool ? this.originalTool.onInputDelta : undefined,\n onInputAvailable: 'onInputAvailable' in this.originalTool ? this.originalTool.onInputAvailable : undefined,\n onOutput: 'onOutput' in this.originalTool ? this.originalTool.onOutput : undefined,\n };\n\n // For provider-defined tools, exclude execute and add name as per v5 spec\n if (builtTool.type === 'provider-defined') {\n const { execute, parameters, ...rest } = base;\n // Prefer the preserved provider name (e.g. \"web_search\" from V5 SDK\n // factories) over the ID-derived name (e.g. \"web_search_20250305\").\n const name =\n ('name' in builtTool && typeof builtTool.name === 'string' ? builtTool.name : null) ||\n builtTool.id.split('.')[1] ||\n builtTool.id;\n return {\n ...rest,\n type: builtTool.type,\n id: builtTool.id,\n name,\n args: builtTool.args,\n } as VercelToolV5;\n }\n\n return base as VercelToolV5;\n }\n\n build(): CoreTool {\n const providerTool = this.buildProviderTool(this.originalTool);\n if (providerTool) {\n return providerTool;\n }\n const model = this.options.model;\n\n const schemaCompatLayers = [];\n\n if (model) {\n // Respect the model's own capability flag; do not disable it based solely on specificationVersion.\n const supportsStructuredOutputs =\n 'supportsStructuredOutputs' in model ? (model.supportsStructuredOutputs ?? false) : false;\n\n const modelInfo = {\n modelId: model.modelId,\n supportsStructuredOutputs,\n provider: model.provider,\n };\n\n schemaCompatLayers.push(\n new OpenAIReasoningSchemaCompatLayer(modelInfo),\n new OpenAISchemaCompatLayer(modelInfo),\n new GoogleSchemaCompatLayer(modelInfo),\n new AnthropicSchemaCompatLayer(modelInfo),\n new DeepSeekSchemaCompatLayer(modelInfo),\n new MetaSchemaCompatLayer(modelInfo),\n );\n }\n\n const originalSchema = this.getParameters();\n let processedInputSchema: Schema | undefined;\n\n if (originalSchema) {\n if (isStandardSchemaWithJSON(originalSchema)) {\n // Find the first applicable compatibility layer\n const applicableLayer = schemaCompatLayers.find(layer => layer.shouldApply());\n\n let schemaToUse: StandardSchemaWithJSON;\n if (applicableLayer) {\n schemaToUse = applicableLayer.processToCompatSchema(originalSchema as any);\n } else {\n schemaToUse = toStandardSchema(originalSchema);\n }\n\n processedInputSchema = jsonSchema(\n standardSchemaToJSONSchema(schemaToUse, {\n io: 'input',\n }),\n {\n validate: (value: unknown) => {\n const result = schemaToUse['~standard'].validate(value);\n // standard-schema validate may return a Promise\n if (result instanceof Promise) {\n return result.then(r => {\n if ('issues' in r && r.issues) {\n return {\n success: false as const,\n error: new Error(r.issues.map((i: any) => i.message).join(', ')),\n };\n }\n return { success: true as const, value: (r as { value: unknown }).value };\n });\n }\n // standard-schema returns { value } on success or { issues } on failure,\n // but AI SDK expects { success: boolean, value/error }\n if ('issues' in result && result.issues) {\n return {\n success: false as const,\n error: new Error(result.issues.map((i: any) => i.message).join(', ')),\n };\n }\n return { success: true as const, value: (result as { value: unknown }).value };\n },\n },\n );\n } else {\n processedInputSchema = applyCompatLayer({\n schema: originalSchema,\n compatLayers: schemaCompatLayers,\n mode: 'aiSdkSchema',\n });\n }\n }\n\n const outputSchema = this.getOutputSchema();\n let processedOutputSchema;\n\n if (outputSchema) {\n if (isStandardSchemaWithJSON(outputSchema)) {\n processedOutputSchema = standardSchemaToJSONSchema(outputSchema, { io: 'output' });\n } else {\n processedOutputSchema = applyCompatLayer({\n schema: outputSchema,\n compatLayers: [],\n mode: 'aiSdkSchema',\n });\n }\n }\n\n // Map AI SDK's needsApproval to our requireApproval\n // needsApproval can be boolean or a function that takes input and returns boolean\n let requireApproval = false;\n let needsApprovalFn: NeedsApprovalFn | undefined;\n\n if (typeof this.options.requireApproval === 'function') {\n requireApproval = true;\n needsApprovalFn = this.options.requireApproval;\n } else if (typeof this.options.requireApproval === 'boolean') {\n requireApproval = this.options.requireApproval;\n needsApprovalFn = undefined;\n }\n\n if (isVercelTool(this.originalTool) && 'needsApproval' in this.originalTool) {\n const needsApproval = (this.originalTool as any).needsApproval;\n if (typeof needsApproval === 'boolean') {\n requireApproval = needsApproval;\n needsApprovalFn = undefined;\n } else if (typeof needsApproval === 'function') {\n // Store the function to evaluate it per-call\n needsApprovalFn = needsApproval;\n // Set requireApproval to true so the tool-call-step knows to check the function\n requireApproval = true;\n }\n }\n\n // Preserve a needsApprovalFn that was attached directly to the tool instance\n // (e.g. MCP tools wrap a server-level `requireToolApproval` function and set\n // `needsApprovalFn` on the tool while keeping `requireApproval` as a boolean).\n // The branches above only derive needsApprovalFn from options/AI SDK shapes, so\n // without this it would be dropped during conversion and conditional approval\n // would silently fall back to the boolean flag.\n const instanceNeedsApprovalFn = getNeedsApprovalFn(this.originalTool);\n if (!needsApprovalFn && instanceNeedsApprovalFn) {\n needsApprovalFn = instanceNeedsApprovalFn;\n // Ensure the tool-call-step knows to evaluate the function per call.\n requireApproval = true;\n }\n\n const definition = {\n type: 'function' as const,\n description: this.originalTool.description,\n requireApproval,\n needsApprovalFn,\n hasSuspendSchema: !!this.getSuspendSchema(),\n execute: this.originalTool.execute\n ? this.createExecute(\n this.originalTool,\n { ...this.options, description: this.originalTool.description },\n this.logType,\n )\n : undefined,\n };\n\n return {\n ...definition,\n id: 'id' in this.originalTool ? this.originalTool.id : undefined,\n parameters: processedInputSchema ?? z.object({}),\n outputSchema: processedOutputSchema,\n strict: 'strict' in this.originalTool ? this.originalTool.strict : undefined,\n providerOptions: 'providerOptions' in this.originalTool ? this.originalTool.providerOptions : undefined,\n mcp: 'mcp' in this.originalTool ? this.originalTool.mcp : undefined,\n toModelOutput: 'toModelOutput' in this.originalTool ? this.originalTool.toModelOutput : undefined,\n transform: 'transform' in this.originalTool ? this.originalTool.transform : undefined,\n inputExamples: 'inputExamples' in this.originalTool ? this.originalTool.inputExamples : undefined,\n onInputStart: 'onInputStart' in this.originalTool ? this.originalTool.onInputStart : undefined,\n onInputDelta: 'onInputDelta' in this.originalTool ? this.originalTool.onInputDelta : undefined,\n onInputAvailable: 'onInputAvailable' in this.originalTool ? this.originalTool.onInputAvailable : undefined,\n onOutput: 'onOutput' in this.originalTool ? this.originalTool.onOutput : undefined,\n // Preserve tool-level background config so the agentic loop can pick it up\n // from the converted CoreTool at dispatch time.\n backgroundConfig: this.options.backgroundConfig,\n } as unknown as CoreTool;\n }\n}\n","import { createHash } from 'node:crypto';\nimport type { CoreMessage } from '@internal/ai-sdk-v4';\nimport { jsonSchemaToZod } from '@mastra/schema-compat/json-to-zod';\nimport { z } from 'zod/v4';\nimport type { MastraPrimitives } from './action';\nimport type { ToolsInput } from './agent';\nimport type { ToolBackgroundConfig } from './background-tasks';\nimport type { MastraBrowser } from './browser/browser';\nimport { ErrorCategory, ErrorDomain, MastraError } from './error';\nimport type { MastraLanguageModel, MastraLegacyLanguageModel } from './llm/model/shared.types';\nimport type { IMastraLogger } from './logger';\nimport type { Mastra } from './mastra';\nimport type { AiMessageType, MastraMemory } from './memory';\nimport type { ObservabilityContext, TracingPolicy } from './observability';\nimport type { RequestContext } from './request-context';\nimport type { CoreTool, VercelTool, VercelToolV5 } from './tools';\nimport { Tool } from './tools/tool';\nimport { CoreToolBuilder } from './tools/tool-builder/builder';\nimport type { ToolToConvert } from './tools/tool-builder/builder';\nimport { isVercelTool } from './tools/toolchecks';\nimport type { OutputWriter } from './workflows/types';\nimport type { Workspace } from './workspace/workspace';\n\n// Re-export Zod utilities for external use (isZodType is defined locally below)\nexport { getZodTypeName, getZodDef, isZodArray, isZodObject } from './utils/zod-utils';\nexport { fetchWithRetry } from './utils/fetchWithRetry';\nexport type { FetchWithRetryOptions } from './utils/fetchWithRetry';\n\nexport const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\n/**\n * Safely JSON-stringifies a value, replacing circular references with \"[Circular]\".\n * Uses a stack-based approach so shared (non-circular) references are preserved.\n */\nexport function safeStringify(value: unknown, space?: string | number): string {\n const stack: unknown[] = [];\n return JSON.stringify(\n value,\n function (this: unknown, _key: string, val: unknown) {\n if (typeof val === 'bigint') return val.toString();\n if (val !== null && typeof val === 'object') {\n // Trim the stack: pop entries that are no longer ancestors of the current path.\n // `this` is the parent object containing the current key.\n while (stack.length > 0 && stack[stack.length - 1] !== this) {\n stack.pop();\n }\n if (stack.includes(val)) return '[Circular]';\n stack.push(val);\n }\n return val;\n },\n space,\n );\n}\n\n/**\n * Returns a JSON-serializable copy of a value by stripping circular references.\n * If the value is already serializable, returns it unchanged (no cloning overhead).\n */\nexport function ensureSerializable(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n\n try {\n JSON.stringify(value);\n return value;\n } catch {\n return JSON.parse(safeStringify(value));\n }\n}\n\n/**\n * Checks if a value is a plain object (not an array, function, Date, RegExp, etc.)\n */\nfunction isPlainObject(value: unknown): value is Record {\n if (value === null || typeof value !== 'object') return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Deep merges two objects, recursively merging nested plain objects.\n * Arrays, functions, and other non-plain objects are replaced (not merged).\n */\nexport function deepMerge(target: T, source: Partial): T {\n const output = { ...target };\n\n if (!source) return output;\n\n Object.keys(source).forEach(key => {\n const targetValue = (output as Record)[key];\n const sourceValue = (source as Record)[key];\n\n // Only deep merge if both values are plain objects\n if (isPlainObject(targetValue) && isPlainObject(sourceValue)) {\n (output as Record)[key] = deepMerge(targetValue, sourceValue);\n } else if (sourceValue !== undefined) {\n // For arrays, functions, primitives, and other non-plain objects: replace\n (output as Record)[key] = sourceValue;\n }\n });\n\n return output;\n}\n\n/**\n * Deep equality comparison for comparing two values.\n * Handles primitives, arrays, objects, and Date instances.\n */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n // Handle identical references and primitives\n if (a === b) return true;\n\n // Handle null/undefined\n if (a == null || b == null) return a === b;\n\n // Handle different types\n if (typeof a !== typeof b) return false;\n\n // Handle arrays\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n return a.every((item, index) => deepEqual(item, b[index]));\n }\n\n // Handle dates (must check before generic objects since Date is also an object)\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n // Handle objects (after Date check to avoid treating Dates as plain objects)\n if (typeof a === 'object' && typeof b === 'object') {\n const aObj = a as Record;\n const bObj = b as Record;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n\n if (aKeys.length !== bKeys.length) return false;\n\n // Verify that bObj has the same keys as aObj before comparing values\n return aKeys.every(key => Object.prototype.hasOwnProperty.call(bObj, key) && deepEqual(aObj[key], bObj[key]));\n }\n\n return false;\n}\n\n/**\n * Generate an empty object from a JSON Schema definition.\n * Accepts both a JSON string and a pre-parsed object.\n * Recursively initializes nested object properties and respects default values.\n */\nexport function generateEmptyFromSchema(schema: string | Record): Record {\n try {\n const parsedSchema = typeof schema === 'string' ? JSON.parse(schema) : schema;\n if (!parsedSchema || parsedSchema.type !== 'object' || !parsedSchema.properties) return {};\n const obj: Record = {};\n for (const [key, prop] of Object.entries>(\n parsedSchema.properties as Record>,\n )) {\n if (prop.default !== undefined) {\n obj[key] =\n typeof prop.default === 'object' && prop.default !== null\n ? JSON.parse(JSON.stringify(prop.default))\n : prop.default;\n } else if (prop.type === 'object' && prop.properties) {\n obj[key] = generateEmptyFromSchema(prop);\n } else if (prop.type === 'object') {\n obj[key] = {};\n } else if (prop.type === 'string') {\n obj[key] = '';\n } else if (prop.type === 'array') {\n obj[key] = [];\n } else if (prop.type === 'number' || prop.type === 'integer') {\n obj[key] = 0;\n } else if (prop.type === 'boolean') {\n obj[key] = false;\n } else {\n obj[key] = null;\n }\n }\n return obj;\n } catch {\n return {};\n }\n}\n\nexport interface TagMaskOptions {\n /** Called when masking begins */\n onStart?: () => void;\n /** Called when masking ends */\n onEnd?: () => void;\n /** Called for each chunk that is masked */\n onMask?: (chunk: string) => void;\n}\n\n/**\n * Transforms a stream by masking content between XML tags.\n * @param stream Input stream to transform\n * @param tag Tag name to mask between (e.g. for ..., use 'foo')\n * @param options Optional configuration for masking behavior\n */\nexport async function* maskStreamTags(\n stream: AsyncIterable,\n tag: string,\n options: TagMaskOptions = {},\n): AsyncIterable {\n const { onStart, onEnd, onMask } = options;\n const openTag = `<${tag}>`;\n const closeTag = ``;\n\n let buffer = '';\n let fullContent = '';\n let isMasking = false;\n let isBuffering = false;\n\n // used for checking in chunks that include tags or partial tags + some other non-tag text\n // eg: \"o w\", can trim before-start to get \"\"\n const trimOutsideDelimiter = (text: string, delimiter: string, trim: 'before-start' | 'after-end') => {\n if (!text.includes(delimiter)) {\n return text;\n }\n\n const parts = text.split(delimiter);\n\n if (trim === `before-start`) {\n return `${delimiter}${parts[1]}`;\n }\n\n return `${parts[0]}${delimiter}`;\n };\n\n // Helper to check if text starts with pattern (ignoring whitespace)\n // When checking partial tags: startsWith(buffer, openTag) checks if buffer could be start of tag\n // When checking full tags: startsWith(chunk, openTag) checks if chunk starts with full tag\n const startsWith = (text: string, pattern: string) => {\n // check start of opening tag\n if (pattern.includes(openTag.substring(0, 3))) {\n // our pattern for checking the start is always based on xml-like tags\n // if the pattern looks like our opening tag and the pattern also includes\n // some other chunked text before it, we just wanted to check the xml part of the pattern\n pattern = trimOutsideDelimiter(pattern, `<`, `before-start`);\n }\n\n return text.trim().startsWith(pattern.trim());\n };\n\n for await (const chunk of stream) {\n fullContent += chunk;\n\n if (isBuffering) buffer += chunk;\n\n const chunkHasTag = startsWith(chunk, openTag);\n const bufferHasTag = !chunkHasTag && isBuffering && startsWith(openTag, buffer);\n\n let toYieldBeforeMaskedStartTag = ``;\n // Check if we should start masking chunks\n if (!isMasking && (chunkHasTag || bufferHasTag)) {\n isMasking = true;\n isBuffering = false;\n\n // check if the buffered text includes text before the start tag. ex \"o yet eg but we don't know yet)\n if (!isMasking && !isBuffering && startsWith(openTag, chunk) && chunk.trim() !== '') {\n isBuffering = true;\n buffer += chunk;\n continue;\n }\n\n // We're buffering, need to check again if our buffer has deviated from the opening eg \n if (isBuffering && buffer && !startsWith(openTag, buffer)) {\n yield buffer;\n buffer = '';\n isBuffering = false;\n continue;\n }\n\n // Check if we should stop masking chunks (since the content includes the closing )\n if (isMasking && fullContent.includes(closeTag)) {\n onMask?.(chunk);\n onEnd?.();\n isMasking = false;\n const lastFullContent = fullContent;\n fullContent = ``; // reset to handle streams with multiple full tags that have text inbetween\n\n // check to see if we have a partial chunk outside the close tag. if we do we need to yield it so it isn't swallowed with the masked text\n const textUntilEndTag = trimOutsideDelimiter(lastFullContent, closeTag, 'after-end');\n if (textUntilEndTag !== lastFullContent) {\n yield lastFullContent.replace(textUntilEndTag, ``);\n }\n\n continue;\n }\n\n // We're currently masking chunks inside a \n if (isMasking) {\n onMask?.(chunk);\n // in the case that there was a chunk that included a tag to mask and some other text, ex \"o {\n name: string;\n runId?: string;\n threadId?: string;\n resourceId?: string;\n logger?: IMastraLogger;\n description?: string;\n mastra?: (Mastra & MastraPrimitives) | MastraPrimitives;\n requestContext: RequestContext;\n tracingPolicy?: TracingPolicy;\n memory?: MastraMemory;\n agentName?: string;\n agentId?: string;\n model?: MastraLanguageModel | MastraLegacyLanguageModel;\n /**\n * Optional async writer used to stream tool output chunks back to the caller. Tools should treat this as fire-and-forget I/O.\n */\n outputWriter?: OutputWriter;\n requireApproval?:\n | boolean\n | ((\n input: any,\n ctx?: { requestContext?: Record; workspace?: Workspace },\n ) => boolean | Promise);\n // Workflow-specific properties\n workflow?: any;\n workflowId?: string;\n state?: any;\n setState?: (state: any) => void;\n /**\n * Workspace available for tool execution. When provided, tools can access\n * workspace.filesystem and workspace.sandbox for file operations and command execution.\n */\n workspace?: Workspace;\n backgroundConfig?: ToolBackgroundConfig;\n /**\n * Browser available for tool execution. When provided, tools can access\n * browser capabilities for web automation, screenshots, and data extraction.\n */\n browser?: MastraBrowser;\n}\n\n/**\n * Checks if a value is a Zod type\n * @param value - The value to check\n * @returns True if the value is a Zod type, false otherwise\n */\nexport function isZodType(value: unknown): value is z.ZodType {\n // Check if it's a Zod schema by looking for common Zod properties and methods\n return (\n typeof value === 'object' &&\n value !== null &&\n '_def' in value &&\n 'parse' in value &&\n typeof (value as any).parse === 'function' &&\n 'safeParse' in value &&\n typeof (value as any).safeParse === 'function'\n );\n}\n\n// Helper function to create a deterministic hash\nfunction createDeterministicId(input: string): string {\n return createHash('sha256').update(input).digest('hex').slice(0, 8); // Take first 8 characters for a shorter but still unique ID\n}\n\n/**\n * Sets the properties for a Vercel Tool, including an ID and inputSchema\n * @param tool - The tool to set the properties for\n * @returns The tool with the properties set\n */\nfunction setVercelToolProperties(tool: VercelTool) {\n // Check if the tool already has inputSchema (v5 format)\n // If it does, use it directly (it might be a function)\n // Otherwise, convert the parameters to inputSchema\n const inputSchema = 'inputSchema' in tool ? tool.inputSchema : convertVercelToolParameters(tool);\n\n const toolId = !('id' in tool)\n ? tool.description\n ? `tool-${createDeterministicId(tool.description)}`\n : `tool-${Math.random().toString(36).substring(2, 9)}`\n : tool.id;\n\n return {\n ...tool,\n id: toolId,\n inputSchema,\n };\n}\n\n/**\n * Ensures a tool has an ID and inputSchema by generating one if not present\n * @param tool - The tool to ensure has an ID and inputSchema\n * @returns The tool with an ID and inputSchema\n */\nexport function ensureToolProperties(tools: ToolsInput): ToolsInput {\n const toolsWithProperties = Object.keys(tools).reduce((acc, key) => {\n const tool = tools?.[key];\n if (tool) {\n // Check if the tool is a plain function (not a Tool instance or Vercel tool)\n // This catches the common mistake of passing a tool factory function instead of the tool itself\n // We need to cast to unknown first since ToolsInput doesn't include functions in its type,\n // but users can still pass functions at runtime which causes silent failures\n if (typeof tool === 'function' && !((tool as unknown) instanceof Tool) && !isVercelTool(tool)) {\n throw new MastraError({\n id: 'TOOL_INVALID_FORMAT',\n domain: ErrorDomain.TOOL,\n category: ErrorCategory.USER,\n text: `Tool \"${key}\" is not a valid tool format. Tools must be created using createTool() or be a valid Vercel AI SDK tool. Received a function.`,\n });\n }\n\n if (isVercelTool(tool)) {\n acc[key] = setVercelToolProperties(tool) as VercelTool;\n } else {\n acc[key] = tool;\n }\n }\n return acc;\n }, {});\n\n return toolsWithProperties;\n}\n\nfunction convertVercelToolParameters(tool: VercelTool): z.ZodType {\n // If the tool is a Vercel Tool, check if the parameters are already a zod object\n // If not, convert the parameters to a zod object using jsonSchemaToZod\n // Handle case where parameters (or inputSchema in v5) is a function that returns a schema\n let schema = tool.parameters ?? z.object({});\n\n // If schema is a function, call it to get the actual schema\n if (typeof schema === 'function') {\n schema = schema();\n }\n\n return isZodType(schema) ? schema : resolveSerializedZodOutput(jsonSchemaToZod(schema));\n}\n\n/**\n * Converts a Vercel Tool or Mastra Tool into a CoreTool format\n * @param originalTool - The tool to convert (either VercelTool or ToolAction)\n * @param options - Tool options including Mastra-specific settings\n * @param logType - Type of tool to log (tool or toolset)\n * @returns A CoreTool that can be used by the system\n */\nexport function makeCoreTool(\n originalTool: ToolToConvert,\n options: ToolOptions,\n logType?: 'tool' | 'toolset' | 'client-tool',\n autoResumeSuspendedTools?: boolean,\n backgroundTaskEnabled?: boolean,\n): CoreTool {\n return new CoreToolBuilder({\n originalTool,\n options,\n logType,\n autoResumeSuspendedTools,\n backgroundTaskEnabled,\n }).build();\n}\n\nexport function makeCoreToolV5(\n originalTool: ToolToConvert,\n options: ToolOptions,\n logType?: 'tool' | 'toolset' | 'client-tool',\n autoResumeSuspendedTools?: boolean,\n backgroundTaskEnabled?: boolean,\n): VercelToolV5 {\n return new CoreToolBuilder({\n originalTool,\n options,\n logType,\n autoResumeSuspendedTools,\n backgroundTaskEnabled,\n }).buildV5();\n}\n\n/**\n * Creates a proxy for a Mastra instance to handle deprecated properties\n * @param mastra - The Mastra instance to proxy\n * @param logger - The logger to use for warnings\n * @returns A proxy for the Mastra instance\n */\nexport function createMastraProxy({ mastra, logger }: { mastra: Mastra; logger: IMastraLogger }) {\n return new Proxy(mastra, {\n get(target, prop) {\n const hasProp = Reflect.has(target, prop);\n\n if (hasProp) {\n const value = Reflect.get(target, prop);\n const isFunction = typeof value === 'function';\n if (isFunction) {\n return value.bind(target);\n }\n return value;\n }\n\n if (prop === 'logger') {\n logger.warn(\"Please use 'getLogger' instead, logger is deprecated\");\n return Reflect.apply(target.getLogger, target, []);\n }\n\n if (prop === 'storage') {\n logger.warn(\"Please use 'getStorage' instead, storage is deprecated\");\n return Reflect.get(target, 'storage');\n }\n\n if (prop === 'agents') {\n logger.warn(\"Please use 'listAgents' instead, agents is deprecated\");\n return Reflect.apply(target.listAgents, target, []);\n }\n\n if (prop === 'tts') {\n logger.warn(\"Please use 'getTTS' instead, tts is deprecated\");\n return Reflect.apply(target.getTTS, target, []);\n }\n\n if (prop === 'vectors') {\n logger.warn(\"Please use 'getVectors' instead, vectors is deprecated\");\n return Reflect.apply(target.getVectors, target, []);\n }\n\n if (prop === 'memory') {\n logger.warn(\"Please use 'getMemory' instead, memory is deprecated\");\n return Reflect.get(target, 'memory');\n }\n\n return Reflect.get(target, prop);\n },\n });\n}\n\nexport function checkEvalStorageFields(traceObject: any, logger?: IMastraLogger) {\n const missingFields = [];\n if (!traceObject.input) missingFields.push('input');\n if (!traceObject.output) missingFields.push('output');\n if (!traceObject.agentName) missingFields.push('agent_name');\n if (!traceObject.metricName) missingFields.push('metric_name');\n if (!traceObject.instructions) missingFields.push('instructions');\n if (!traceObject.globalRunId) missingFields.push('global_run_id');\n if (!traceObject.runId) missingFields.push('run_id');\n\n if (missingFields.length > 0) {\n if (logger) {\n logger.warn('Skipping evaluation storage due to missing required fields', {\n missingFields,\n runId: traceObject.runId,\n agentName: traceObject.agentName,\n });\n } else {\n console.warn('Skipping evaluation storage due to missing required fields', {\n missingFields,\n runId: traceObject.runId,\n agentName: traceObject.agentName,\n });\n }\n return false;\n }\n\n return true;\n}\n\n// lifted from https://github.com/vercel/ai/blob/main/packages/ai/core/prompt/detect-prompt-type.ts#L27\nfunction detectSingleMessageCharacteristics(\n message: any,\n): 'has-ui-specific-parts' | 'has-core-specific-parts' | 'message' | 'other' {\n if (\n typeof message === 'object' &&\n message !== null &&\n (message.role === 'function' || // UI-only role\n message.role === 'data' || // UI-only role\n 'toolInvocations' in message || // UI-specific field\n 'parts' in message || // UI-specific field\n 'experimental_attachments' in message)\n ) {\n return 'has-ui-specific-parts';\n } else if (\n typeof message === 'object' &&\n message !== null &&\n 'content' in message &&\n (Array.isArray(message.content) || // Core messages can have array content\n 'experimental_providerMetadata' in message ||\n 'providerOptions' in message)\n ) {\n return 'has-core-specific-parts';\n } else if (\n typeof message === 'object' &&\n message !== null &&\n 'role' in message &&\n 'content' in message &&\n typeof message.content === 'string' &&\n ['system', 'user', 'assistant', 'tool'].includes(message.role)\n ) {\n return 'message';\n } else {\n return 'other';\n }\n}\n\nexport function isUiMessage(message: CoreMessage | AiMessageType): message is AiMessageType {\n return detectSingleMessageCharacteristics(message) === `has-ui-specific-parts`;\n}\nexport function isCoreMessage(message: CoreMessage | AiMessageType): message is CoreMessage {\n return [`has-core-specific-parts`, `message`].includes(detectSingleMessageCharacteristics(message));\n}\n\n/** Represents a validated SQL identifier (e.g., table or column name). */\ntype SqlIdentifier = string & { __brand: 'SqlIdentifier' };\n/** Represents a validated dot-separated SQL field key. */\ntype FieldKey = string & { __brand: 'FieldKey' };\n\nconst SQL_IDENTIFIER_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * Parses and returns a valid SQL identifier (such as a table or column name).\n * The identifier must:\n * - Start with a letter (a-z, A-Z) or underscore (_)\n * - Contain only letters, numbers, or underscores\n * - Be at most 63 characters long\n *\n * @param name - The identifier string to parse.\n * @param kind - Optional label for error messages (e.g., 'table name').\n * @returns The validated identifier as a branded type.\n * @throws {Error} If the identifier does not conform to SQL naming rules.\n *\n * @example\n * const id = parseSqlIdentifier('my_table'); // Ok\n * parseSqlIdentifier('123table'); // Throws error\n */\nexport function parseSqlIdentifier(name: string, kind = 'identifier'): SqlIdentifier {\n if (!SQL_IDENTIFIER_PATTERN.test(name) || name.length > 63) {\n throw new Error(\n `Invalid ${kind}: ${name}. Must start with a letter or underscore, contain only letters, numbers, or underscores, and be at most 63 characters long.`,\n );\n }\n return name as SqlIdentifier;\n}\n\n/**\n * Parses and returns a valid dot-separated SQL field key (e.g., 'user.profile.name').\n * Each segment must:\n * - Start with a letter (a-z, A-Z) or underscore (_)\n * - Contain only letters, numbers, or underscores\n * - Be at most 63 characters long\n *\n * @param key - The dot-separated field key string to parse.\n * @returns The validated field key as a branded type.\n * @throws {Error} If any segment of the key is invalid.\n *\n * @example\n * const key = parseFieldKey('user_profile.name'); // Ok\n * parseFieldKey('user..name'); // Throws error\n * parseFieldKey('user.123name'); // Throws error\n */\nexport function parseFieldKey(key: string): FieldKey {\n if (!key) throw new Error('Field key cannot be empty');\n const segments = key.split('.');\n for (const segment of segments) {\n if (!SQL_IDENTIFIER_PATTERN.test(segment) || segment.length > 63) {\n throw new Error(`Invalid field key segment: ${segment} in ${key}`);\n }\n }\n return key as FieldKey;\n}\n\n/**\n * Removes specific keys from an object.\n * @param obj - The original object\n * @param keysToOmit - Keys to exclude from the returned object\n * @returns A new object with the specified keys removed\n */\nexport function omitKeys>(obj: T, keysToOmit: string[]): Partial {\n return Object.fromEntries(Object.entries(obj).filter(([key]) => !keysToOmit.includes(key))) as Partial;\n}\n\n/**\n * Selectively extracts specific fields from an object using dot notation.\n * Does not error if fields don't exist - simply omits them from the result.\n * @param obj - The source object to extract fields from\n * @param fields - Array of field paths (supports dot notation like 'output.text')\n * @returns New object containing only the specified fields\n */\nexport function selectFields(obj: any, fields: string[]): any {\n if (!obj || typeof obj !== 'object') {\n return obj;\n }\n\n const result: any = {};\n\n for (const field of fields) {\n const value = getNestedValue(obj, field);\n if (value !== undefined) {\n setNestedValue(result, field, value);\n }\n }\n\n return result;\n}\n\n/**\n * Gets a nested value from an object using dot notation\n * @param obj - Source object\n * @param path - Dot notation path (e.g., 'output.text')\n * @returns The value at the path, or undefined if not found\n */\nexport function getNestedValue(obj: any, path: string): any {\n return path.split('.').reduce((current, key) => {\n return current && typeof current === 'object' ? current[key] : undefined;\n }, obj);\n}\n\n/**\n * Sets a nested value in an object using dot notation\n * @param obj - Target object\n * @param path - Dot notation path (e.g., 'output.text')\n * @param value - Value to set\n */\nexport function setNestedValue(obj: any, path: string, value: any): void {\n const keys = path.split('.');\n const lastKey = keys.pop();\n if (!lastKey) return;\n\n // Validate every segment up-front so we never walk or assign through\n // a prototype-mutating key like \"__proto__\", \"constructor\", or \"prototype\".\n for (const key of keys) {\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return;\n }\n }\n if (lastKey === '__proto__' || lastKey === 'constructor' || lastKey === 'prototype') {\n return;\n }\n\n let current = obj;\n for (const key of keys) {\n const existing = Object.prototype.hasOwnProperty.call(current, key) ? current[key] : undefined;\n if (existing === null || typeof existing !== 'object') {\n // Use a null-prototype object so intermediate containers cannot be\n // used as a prototype-pollution sink even if a sanitizer check is\n // bypassed upstream.\n const container = Object.create(null);\n Object.defineProperty(current, key, { value: container, writable: true, enumerable: true, configurable: true });\n }\n current = current[key];\n }\n\n Object.defineProperty(current, lastKey, { value, writable: true, enumerable: true, configurable: true });\n}\n\nexport const removeUndefinedValues = (obj: Record) => {\n return Object.fromEntries(Object.entries(obj).filter(([_, value]) => value !== undefined));\n};\n"]}