@mastra/core
Version:
254 lines • 12.6 kB
TypeScript
import type { CoreMessage } from './_types/@internal_ai-sdk-v4@0.0.98/dist/index.js';
import { z } from 'zod/v4';
import type { MastraPrimitives } from './action/index.js';
import type { ToolsInput } from './agent/index.js';
import type { FGACheckContext, MastraFGAPermissionInput } from './auth/ee/index.js';
import type { AgentBackgroundConfig, ToolBackgroundConfig } from './background-tasks/index.js';
import type { MastraBrowser } from './browser/browser.js';
import type { MastraLanguageModel, MastraLegacyLanguageModel } from './llm/model/shared.types.js';
import type { IMastraLogger } from './logger/index.js';
import type { Mastra } from './mastra/index.js';
import type { AiMessageType, MastraMemory } from './memory/index.js';
import type { ObservabilityContext, TracingPolicy } from './observability/index.js';
import type { RequestContext } from './request-context/index.js';
import type { CoreTool, VercelToolV5 } from './tools/index.js';
import type { ToolToConvert } from './tools/tool-builder/builder.js';
import type { OutputWriter } from './workflows/types.js';
import type { Workspace } from './workspace/workspace.js';
export { getZodTypeName, getZodDef, isZodArray, isZodObject } from './utils/zod-utils.js';
export { fetchWithRetry } from './utils/fetchWithRetry.js';
export type { FetchWithRetryOptions } from './utils/fetchWithRetry.js';
export { boundedStringify, ensureSerializable, isBoundedSerializable, safeStringify } from './utils/safe-stringify.js';
export { deepEqual } from './utils/deep-equal.js';
export { getRequestUser, resolveDynamicArgument } from './utils/dynamic-argument.js';
/** Resolves after `ms`, or as soon as `signal` aborts. */
export declare const delay: (ms: number, signal?: AbortSignal) => Promise<void>;
/**
* Read a positive-integer environment variable (e.g. a TTL in ms). Unset, empty,
* non-numeric, fractional, or non-positive values fall back to `fallback`.
*/
export declare function readPositiveIntEnv(name: string, fallback: number): number;
/**
* Deep merges two objects, recursively merging nested plain objects.
* Arrays, functions, and other non-plain objects are replaced (not merged).
*/
export declare function deepMerge<T extends object = object>(target: T, source: Partial<T>): T;
/**
* Generate an empty object from a JSON Schema definition.
* Accepts both a JSON string and a pre-parsed object.
* Recursively initializes nested object properties and respects default values.
*/
export declare function generateEmptyFromSchema(schema: string | Record<string, unknown>): Record<string, unknown>;
export interface TagMaskOptions {
/** Called when masking begins */
onStart?: () => void;
/** Called when masking ends */
onEnd?: () => void;
/** Called for each chunk that is masked */
onMask?: (chunk: string) => void;
}
/**
* Transforms a stream by masking content between XML tags.
* @param stream Input stream to transform
* @param tag Tag name to mask between (e.g. for <foo>...</foo>, use 'foo')
* @param options Optional configuration for masking behavior
*/
export declare function maskStreamTags(stream: AsyncIterable<string>, tag: string, options?: TagMaskOptions): AsyncIterable<string>;
/**
* Resolve serialized zod output - This function takes the string output ot the `jsonSchemaToZod` function
* and instantiates the zod object correctly.
*
* @param schema - serialized zod object
* @returns resolved zod object
*/
export declare function resolveSerializedZodOutput(schema: string): z.ZodType;
export interface ToolOptions extends Partial<ObservabilityContext> {
name: string;
runId?: string;
threadId?: string;
resourceId?: string;
logger?: IMastraLogger;
description?: string;
mastra?: (Mastra & MastraPrimitives) | MastraPrimitives;
requestContext: RequestContext;
tracingPolicy?: TracingPolicy;
memory?: MastraMemory;
agentName?: string;
agentId?: string;
model?: MastraLanguageModel | MastraLegacyLanguageModel;
/**
* Optional async writer used to stream tool output chunks back to the caller. Tools should treat this as fire-and-forget I/O.
*/
outputWriter?: OutputWriter;
requireApproval?: boolean | ((input: any, ctx?: {
requestContext?: Record<string, unknown>;
workspace?: Workspace;
}) => boolean | Promise<boolean>);
workflow?: any;
workflowId?: string;
state?: any;
setState?: (state: any) => void;
/**
* Workspace available for tool execution. When provided, tools can access
* workspace.filesystem and workspace.sandbox for file operations and command execution.
*/
workspace?: Workspace;
backgroundConfig?: ToolBackgroundConfig;
/**
* Agent-level backgroundTasks config. Combined with `backgroundConfig` (the
* tool-level config) to decide whether the `_background` override schema is
* injected for this specific tool. See `isToolBackgroundEligible`.
*/
agentBackgroundConfig?: AgentBackgroundConfig;
/**
* Browser available for tool execution. When provided, tools can access
* browser capabilities for web automation, screenshots, and data extraction.
*/
browser?: MastraBrowser;
/**
* Resolves what this tool's `tools:execute` check authorizes against, when the tool's owner has its
* own rule (`MCPServer` checks its tools against its own resource and `fga` mapping). Without it,
* the check uses the standalone or agent tool resource.
* @internal
*/
resolveExecuteFGA?: (ctx: {
user: unknown;
requestContext?: RequestContext;
}) => Promise<ToolExecuteFGACheck>;
}
/**
* The FGA check a tool runs before each execution, as returned by `ToolOptions.resolveExecuteFGA`.
* @internal
*/
export interface ToolExecuteFGACheck {
resource: {
type: string;
id: string;
};
permission: MastraFGAPermissionInput;
/** Merged into the check context the FGA provider receives. */
context?: FGACheckContext;
/** Merged into the check metadata the FGA provider receives. */
metadata?: Record<string, unknown>;
}
/**
* Checks if a value is a Zod type
* @param value - The value to check
* @returns True if the value is a Zod type, false otherwise
*/
export declare function isZodType(value: unknown): value is z.ZodType;
/**
* Ensures a tool has an ID and inputSchema by generating one if not present
* @param tool - The tool to ensure has an ID and inputSchema
* @returns The tool with an ID and inputSchema
*/
export declare function ensureToolProperties(tools: ToolsInput): ToolsInput;
/**
* Converts a Vercel Tool or Mastra Tool into a CoreTool format
* @param originalTool - The tool to convert (either VercelTool or ToolAction)
* @param options - Tool options including Mastra-specific settings
* @param logType - Type of tool to log (tool or toolset)
* @returns A CoreTool that can be used by the system
*/
export declare function makeCoreTool(originalTool: ToolToConvert, options: ToolOptions, logType?: 'tool' | 'toolset' | 'client-tool', autoResumeSuspendedTools?: boolean, backgroundTaskEnabled?: boolean): CoreTool;
/**
* Converts a raw tool an input processor added during a step. The processor does not run
* again before a suspended call resumes, so the converted tool remembers how to rebuild
* itself for the resuming call's request context (see {@link rebindProcessorTools}).
*/
export declare function makeProcessorCoreTool(...args: Parameters<typeof makeCoreTool>): CoreTool;
/**
* Rebuilds the processor-added tools in `tools` for `requestContext`, the way request tools
* are rebuilt when a suspended run resumes, so an approved processor tool runs with the
* approver's request context like a statically defined tool does.
*/
export declare function rebindProcessorTools<T extends Record<string, unknown>>(tools: T, requestContext: RequestContext): T;
export declare function makeCoreToolV5(originalTool: ToolToConvert, options: ToolOptions, logType?: 'tool' | 'toolset' | 'client-tool', autoResumeSuspendedTools?: boolean, backgroundTaskEnabled?: boolean): VercelToolV5;
/**
* Creates a proxy for a Mastra instance to handle deprecated properties
* @param mastra - The Mastra instance to proxy
* @param logger - The logger to use for warnings
* @returns A proxy for the Mastra instance
*/
export declare function createMastraProxy({ mastra, logger }: {
mastra: Mastra;
logger: IMastraLogger;
}): Mastra<Record<string, import("./agent").Agent<any, ToolsInput, undefined, any, import("./agent").AgentEditorConfig | undefined>>, Record<string, import("./workflows").AnyWorkflow>, Record<string, import("./vector").MastraVector<any>>, Record<string, import("./tts").MastraTTS>, IMastraLogger, Record<string, import("./mcp").MCPServerBase<any>>, Record<string, import("./evals").MastraScorer<any, any, any, any>>, Record<string, import("./tools").ToolAction<any, any, any, any, any, any, unknown>>, Record<string, import("./processors").Processor<any, unknown>>, Record<string, MastraMemory>, Record<string, import("./channels").ChannelProvider>, Record<string, import("./classifier").Classifier<any>>, Record<string, import("./knowledge").Knowledge>>;
export declare function checkEvalStorageFields(traceObject: any, logger?: IMastraLogger): boolean;
export declare function isUiMessage(message: CoreMessage | AiMessageType): message is AiMessageType;
export declare function isCoreMessage(message: CoreMessage | AiMessageType): message is CoreMessage;
/** Represents a validated SQL identifier (e.g., table or column name). */
type SqlIdentifier = string & {
__brand: 'SqlIdentifier';
};
/** Represents a validated dot-separated SQL field key. */
type FieldKey = string & {
__brand: 'FieldKey';
};
/**
* Parses and returns a valid SQL identifier (such as a table or column name).
* The identifier must:
* - Start with a letter (a-z, A-Z) or underscore (_)
* - Contain only letters, numbers, or underscores
* - Be at most 63 characters long
*
* @param name - The identifier string to parse.
* @param kind - Optional label for error messages (e.g., 'table name').
* @returns The validated identifier as a branded type.
* @throws {Error} If the identifier does not conform to SQL naming rules.
*
* @example
* const id = parseSqlIdentifier('my_table'); // Ok
* parseSqlIdentifier('123table'); // Throws error
*/
export declare function parseSqlIdentifier(name: string, kind?: string): SqlIdentifier;
/**
* Parses and returns a valid dot-separated SQL field key (e.g., 'user.profile.name').
* Each segment must:
* - Start with a letter (a-z, A-Z) or underscore (_)
* - Contain only letters, numbers, or underscores
* - Be at most 63 characters long
*
* @param key - The dot-separated field key string to parse.
* @returns The validated field key as a branded type.
* @throws {Error} If any segment of the key is invalid.
*
* @example
* const key = parseFieldKey('user_profile.name'); // Ok
* parseFieldKey('user..name'); // Throws error
* parseFieldKey('user.123name'); // Throws error
*/
export declare function parseFieldKey(key: string): FieldKey;
/**
* Removes specific keys from an object.
* @param obj - The original object
* @param keysToOmit - Keys to exclude from the returned object
* @returns A new object with the specified keys removed
*/
export declare function omitKeys<T extends Record<string, any>>(obj: T, keysToOmit: string[]): Partial<T>;
/**
* Selectively extracts specific fields from an object using dot notation.
* Does not error if fields don't exist - simply omits them from the result.
* @param obj - The source object to extract fields from
* @param fields - Array of field paths (supports dot notation like 'output.text')
* @returns New object containing only the specified fields
*/
export declare function selectFields(obj: any, fields: string[]): any;
/**
* Gets a nested value from an object using dot notation
* @param obj - Source object
* @param path - Dot notation path (e.g., 'output.text')
* @returns The value at the path, or undefined if not found
*/
export declare function getNestedValue(obj: any, path: string): any;
/**
* Sets a nested value in an object using dot notation
* @param obj - Target object
* @param path - Dot notation path (e.g., 'output.text')
* @param value - Value to set
*/
export declare function setNestedValue(obj: any, path: string, value: any): void;
export declare const removeUndefinedValues: (obj: Record<string, any>) => {
[k: string]: any;
};
//# sourceMappingURL=utils.d.ts.map