UNPKG

@robota-sdk/tools

Version:

Tools and utilities package for Robota SDK - providing AI function calling and tool integration capabilities

1,775 lines (1,736 loc) 47.9 kB
import { z } from 'zod'; /** * Function schema interface */ interface FunctionSchema { name: string; description?: string; parameters: { type: 'object'; properties: Record<string, { type: string; description?: string; enum?: any[]; default?: any; }>; required?: string[]; }; } /** * Function definition interface */ interface FunctionDefinition { name: string; description?: string; parameters?: { type: string; properties?: Record<string, { type: string; description?: string; enum?: any[]; default?: any; }>; required?: string[]; }; } /** * Function call interface */ interface FunctionCall { name: string; arguments: Record<string, any> | string; } /** * Function call result interface */ interface FunctionCallResult { name: string; result?: any; error?: string; } /** * Function creation utilities * * @module FunctionFactory * @description * Pure functions for creating tool functions with validation and error handling. * These functions are side-effect free and can be easily tested. */ /** * Function result type */ type FunctionResult<TResult = unknown> = { result: TResult; }; /** * Function options interface */ interface FunctionOptions<TParams = unknown, TResult = unknown> { name: string; description?: string; parameters: z.ZodObject<any> | any; execute: (params: TParams) => Promise<TResult> | TResult; } /** * Function interface */ interface ToolFunction<TParams = unknown, TResult = unknown> { name: string; description?: string; schema: FunctionDefinition; execute: (params: TParams) => Promise<TResult>; } /** * Create a function with validation and error handling * * @template TParams - Function parameter type * @template TResult - Function return result type * @param options - Function creation options * @returns Created function object with validation */ declare function createFunction<TParams = unknown, TResult = unknown>(options: FunctionOptions<TParams, TResult>): ToolFunction<TParams, TResult>; /** * Convert callback function to ToolFunction object * * @param name - Function name * @param fn - Callback function to convert * @param description - Optional function description * @returns Created function object */ declare function functionFromCallback(name: string, fn: (...args: any[]) => any, description?: string): ToolFunction<Record<string, any>, any>; /** * Create function with enhanced validation * * @param options - Function options with enhanced validation * @returns Function with comprehensive error handling */ declare function createValidatedFunction<TParams = unknown, TResult = unknown>(options: FunctionOptions<TParams, TResult> & { validateResult?: (result: TResult) => boolean; resultErrorMessage?: string; }): ToolFunction<TParams, TResult>; /** * Function Registry for managing tool functions * * @module FunctionRegistry * @description * Registry class for managing function definitions and execution. * Provides registration, lookup, and execution capabilities. */ /** * Function call handler type */ type FunctionHandler = (args: Record<string, any>, context?: any) => Promise<any>; /** * Function call registry * * Manages function definitions and their execution handlers. * Provides a centralized way to register, lookup, and execute functions. */ declare class FunctionRegistry { /** @internal Map of function names to handlers */ private functions; /** @internal Map of function names to definitions */ private definitions; /** * Register a function with its definition and handler * * @param definition - Function definition with schema * @param handler - Function execution handler */ register(definition: FunctionDefinition, handler: FunctionHandler): void; /** * Unregister a function by name * * @param name - Function name to unregister * @returns True if function was found and removed */ unregister(name: string): boolean; /** * Check if a function is registered * * @param name - Function name to check * @returns True if function is registered */ has(name: string): boolean; /** * Get all registered function definitions * * @returns Array of all function definitions */ getAllDefinitions(): FunctionDefinition[]; /** * Get function definition by name * * @param name - Function name * @returns Function definition if found */ getDefinition(name: string): FunctionDefinition | undefined; /** * Get all registered function names * * @returns Array of function names */ getFunctionNames(): string[]; /** * Get total number of registered functions * * @returns Number of registered functions */ getCount(): number; /** * Clear all registered functions */ clear(): void; /** * Execute function call * * @param functionCall - Function call with name and arguments * @param context - Optional execution context * @returns Promise resolving to function call result */ execute(functionCall: FunctionCall, context?: any): Promise<FunctionCallResult>; /** * Parse function arguments safely * * @param args - Arguments to parse (string or object) * @returns Parsed arguments object */ private parseArguments; } /** * Zod to JSON Schema conversion utilities * * @module ZodToJson * @description * Pure functions for converting Zod schemas to JSON Schema format. * These functions are side-effect free and can be easily tested. */ /** * Convert zod schema to JSON schema format * * @param schema - Zod object schema * @returns JSON schema representation */ declare function zodToJsonSchema(schema: z.ZodObject<any>): any; /** * Convert zod type to JSON schema type * * @param zodType - Zod type to convert * @param fieldName - Field name for error messages * @returns JSON schema type representation */ declare function convertZodTypeToJsonSchema(zodType: z.ZodTypeAny, fieldName: string): any; /** * Extract description from zod type * * @param zodType - Zod type to extract description from * @returns Description string if available */ declare function getZodDescription(zodType: z.ZodTypeAny): string | undefined; /** * Check if zod type is optional * * @param zodType - Zod type to check * @returns True if the type is optional */ declare function isOptionalType(zodType: z.ZodTypeAny): boolean; /** * Check if zod type allows null * * @param zodType - Zod type to check * @returns True if the type is nullable */ declare function isNullableType(zodType: z.ZodTypeAny): boolean; /** * JSON Schema to Zod conversion utilities * * @module JsonToZod * @description * Pure functions for converting JSON Schema to Zod schema format. * These functions are side-effect free and can be easily tested. */ /** * Create Zod schema from function definition * * @param definition - Function definition with JSON schema parameters * @returns Zod schema for validation */ declare function createFunctionSchema(definition: FunctionDefinition): z.ZodObject<any>; /** * Function tool schema and type definitions module * * Provides utility functions for converting Zod schemas to JSON schemas. * Supports type definitions and conversion functionality for Robota's function tool definitions. * * @module zod-schema * @description * Provides utility functions for converting Zod schemas to JSON schemas. * Supports type definitions and conversion functionality for Robota's function tool definitions. */ /** * Zod schema-based function tool definition interface */ interface ZodFunctionTool<T extends z.ZodTypeAny = z.ZodTypeAny> { /** Tool name */ name: string; /** Tool description */ description: string; /** Tool parameter schema */ parameters: T; /** Tool handler function */ handler: (params: z.infer<T>) => Promise<unknown>; } /** * Converts a Zod function tool to a Robota-compatible function schema. * * @param tool - Zod-based function tool definition * @returns Robota-compatible function schema */ declare function zodFunctionToSchema<T extends z.ZodObject<z.ZodRawShape>>(tool: ZodFunctionTool<T>): { name: string; description: string; parameters: { type: string; properties: Record<string, unknown>; required?: string[]; }; }; /** * Cache Manager for Tool Performance Optimization * * @module cache-manager * @description * Caches tool loading and function schema conversion results to optimize performance. */ /** * Cache item interface */ interface CacheItem<T> { /** Cached data */ data: T; /** Cache creation timestamp */ timestamp: number; /** Time to live (milliseconds) */ ttl?: number; /** Access count */ accessCount: number; /** Last accessed timestamp */ lastAccessed: number; } /** * Cache statistics information */ interface CacheStats { /** Total cache items count */ totalItems: number; /** Cache hits count */ hits: number; /** Cache misses count */ misses: number; /** Hit rate (0-1) */ hitRate: number; /** Expired items count */ expired: number; /** Estimated memory usage */ estimatedMemoryUsage: number; } /** * Cache manager class * * Supports LRU (Least Recently Used) algorithm and TTL (Time To Live). */ declare class CacheManager<T = any> { private cache; private maxSize; private defaultTTL?; private hits; private misses; private expired; constructor(options?: { maxSize?: number; defaultTTL?: number; }); /** * Get value from cache */ get(key: string): T | undefined; /** * Set value in cache */ set(key: string, value: T, ttl?: number): void; /** * Delete item from cache */ delete(key: string): boolean; /** * Check if specific key exists in cache */ has(key: string): boolean; /** * Clear entire cache */ clear(): void; /** * Clean up expired items */ cleanup(): number; /** * Get cache statistics */ getStats(): CacheStats; /** * Get all cache keys */ keys(): string[]; /** * Get all cache values */ values(): T[]; /** * Get cache size */ size(): number; /** * Check if item has expired */ private isExpired; /** * Evict least recently used item using LRU algorithm */ private evictLRU; /** * Estimate object size (approximate) */ private estimateObjectSize; } /** * Function schema specific cache manager */ declare class FunctionSchemaCacheManager extends CacheManager<FunctionSchema[]> { constructor(); /** * Generate cache key from tool definitions */ generateKey(toolDefinitions: Record<string, any>): string; /** * Simple hash function */ private simpleHash; } /** * Global cache manager instances */ declare const globalFunctionSchemaCache: FunctionSchemaCacheManager; declare const globalToolCache: CacheManager<any>; /** * Utility for periodically executing cache cleanup tasks */ declare class CacheCleanupScheduler { private intervals; /** * Start periodic cache cleanup */ start(cacheManagers: CacheManager[], intervalMs?: number): void; /** * Stop periodic cache cleanup */ stop(): void; } /** * Global cache cleanup scheduler */ declare const globalCacheCleanupScheduler: CacheCleanupScheduler; /** * Tool Provider interface * * Unified interface for various tool providers (MCP, OpenAPI, ZodFunction, etc.) * Tool providers enable AI models to call tools. */ interface ToolProvider { /** * Call a tool. All tool providers must implement this interface. * * @param toolName Name of the tool to call * @param parameters Parameters to pass to the tool * @returns Tool call result */ callTool(toolName: string, parameters: Record<string, any>): Promise<any>; /** * List of all function schemas provided by the tool provider * Used when passing tool list to AI models. */ functions?: FunctionSchema[]; /** * Get available tool names * * @returns Array of available tool names */ getAvailableTools?(): string[]; /** * Check if a tool exists * * @param toolName Name of the tool to check * @returns True if tool exists, false otherwise */ hasTool?(toolName: string): boolean; } /** * Tool Provider error types */ declare class ToolProviderError extends Error { readonly code: string; readonly context?: Record<string, any>; constructor(message: string, code?: string, context?: Record<string, any>); } declare class ToolNotFoundError extends ToolProviderError { constructor(toolName: string, availableTools?: string[]); } declare class ToolExecutionError extends ToolProviderError { constructor(toolName: string, originalError: unknown); } /** * Base Tool Provider abstract class * * Provides common functionality for all tool providers. */ declare abstract class BaseToolProvider implements ToolProvider { protected logger?: (message: string, context?: Record<string, any>) => void; constructor(options?: { logger?: (message: string, context?: Record<string, any>) => void; }); /** * Abstract method to be implemented by concrete providers */ abstract callTool(toolName: string, parameters: Record<string, any>): Promise<any>; /** * Abstract property to be implemented by concrete providers */ abstract functions?: FunctionSchema[]; /** * Get available tool names from functions list */ getAvailableTools(): string[]; /** * Check if a tool exists */ hasTool(toolName: string): boolean; /** * Validate tool existence before calling */ protected validateToolExists(toolName: string): void; /** * Log error with context */ protected logError(message: string, context?: Record<string, any>): void; /** * Handle tool execution with common error handling and performance monitoring */ protected executeToolSafely<T>(toolName: string, parameters: Record<string, any>, executor: () => Promise<T>): Promise<T>; } /** * Zod schema-based function tool provider options */ interface ZodFunctionToolProviderOptions { /** Tool definition object */ tools: Record<string, ZodFunctionTool<z.ZodObject<z.ZodRawShape>>>; /** Logger function (optional) */ logger?: (message: string, context?: Record<string, any>) => void; /** Whether to use cache (default: true) */ enableCache?: boolean; /** Custom cache manager (optional) */ cacheManager?: FunctionSchemaCacheManager; } /** * Creates a Zod schema-based function tool provider. * * @param options - Function tool provider options * @returns Tool provider instance (implements ToolProvider interface) * * @see {@link ../../apps/examples/02-functions | Function Tool Examples} */ declare function createZodFunctionToolProvider(options: ZodFunctionToolProviderOptions): ToolProvider; /** * MCP client interface * Compatible with Client from @modelcontextprotocol/sdk */ interface MCPClient { chat: (options: any) => Promise<any>; stream: (options: any) => AsyncIterable<any>; callTool: (toolName: string, parameters: Record<string, any>) => Promise<any>; listTools?: () => Promise<{ tools: Array<{ name: string; description?: string; inputSchema?: any; }>; }>; } /** * MCP tool provider options */ interface MCPToolProviderOptions { /** MCP client instance */ mcpClient: MCPClient; /** Logger function (optional) */ logger?: (message: string, context?: Record<string, any>) => void; } /** * MCP (Model Context Protocol) based tool provider class */ declare class MCPToolProvider extends BaseToolProvider { private readonly mcpClient; functions?: FunctionSchema[]; constructor(options: MCPToolProviderOptions); /** * Get tool list from MCP client and convert to function schema */ private initializeFunctions; /** * Tool call implementation */ callTool(toolName: string, parameters: Record<string, any>): Promise<any>; /** * Return available tool list (override) * For MCP, function list may not exist, so handle dynamically */ getAvailableTools(): string[]; /** * Check if specific tool exists (override) * For MCP, tool may exist even without function list, so always return true */ hasTool(toolName: string): boolean; } /** * MCP (Model Context Protocol) based tool provider creation function * * @param mcpClient MCP client instance * @returns MCP-based tool provider object */ declare function createMcpToolProvider(mcpClient: MCPClient): ToolProvider; /** * OpenAPI tool provider options */ interface OpenAPIToolProviderOptions { /** OpenAPI spec object or URL */ openApiSpec: any; /** Base URL configuration */ baseUrl?: string; /** Logger function (optional) */ logger?: (message: string, context?: Record<string, any>) => void; } /** * OpenAPI-based tool provider class */ declare class OpenAPIToolProvider extends BaseToolProvider { private openApiSpec; private readonly baseUrl?; functions?: FunctionSchema[]; constructor(options: OpenAPIToolProviderOptions); /** * Convert OpenAPI spec to function list */ private convertOpenAPIToFunctions; /** * Initialize OpenAPI spec (lazy loading) */ private initializeSpec; /** * Tool call implementation */ callTool(toolName: string, parameters: Record<string, any>): Promise<any>; /** * Return available tool list (override) */ getAvailableTools(): string[]; /** * Check if specific tool exists (override) */ hasTool(toolName: string): boolean; } /** * Creates a tool provider based on OpenAPI specifications. * * @param openApiSpec OpenAPI spec object or URL * @param options Base URL configuration * @returns OpenAPI-based tool provider */ declare function createOpenAPIToolProvider(openApiSpec: any, options?: { baseUrl?: string; }): ToolProvider; /** * Tool Provider Factory * * @module tool-provider-factory * @description * Provides factory class and utility functions for creating and managing various types of tool providers. */ /** * Tool Provider type definition */ type ToolProviderType = 'zod-function' | 'openapi' | 'mcp'; /** * Tool Provider configuration options */ interface ToolProviderConfigs { 'zod-function': ZodFunctionToolProviderOptions; 'openapi': OpenAPIToolProviderOptions; 'mcp': MCPToolProviderOptions; } /** * Tool Provider Factory class * * Creates and manages various types of tool providers. */ declare class ToolProviderFactory { private providers; private logger?; constructor(options?: { logger?: (message: string, context?: Record<string, any>) => void; }); /** * Create Zod Function Tool Provider */ createZodFunctionProvider(name: string, tools: Record<string, ZodFunctionTool<z.ZodObject<z.ZodRawShape>>>): ToolProvider; /** * Create OpenAPI Tool Provider */ createOpenAPIProvider(name: string, openApiSpec: any, options?: { baseUrl?: string; }): ToolProvider; /** * Create MCP Tool Provider */ createMCPProvider(name: string, mcpClient: MCPClient): ToolProvider; /** * Generic Tool Provider creation method */ createProvider<T extends ToolProviderType>(type: T, name: string, config: ToolProviderConfigs[T]): ToolProvider; /** * Get registered Provider */ getProvider(name: string): ToolProvider | undefined; /** * Get all registered Provider list */ getAllProviders(): Record<string, ToolProvider>; /** * Remove Provider */ removeProvider(name: string): boolean; /** * Get integrated list of available tools from all Providers */ getAllAvailableTools(): Record<string, string[]>; /** * Find Provider that provides specific tool */ findProviderForTool(toolName: string): { providerName: string; provider: ToolProvider; } | undefined; /** * Tool call (automatically find appropriate Provider) */ callTool(toolName: string, parameters: Record<string, any>): Promise<any>; } /** * Get global Tool Provider Factory instance */ declare function getGlobalToolProviderFactory(): ToolProviderFactory; /** * Convenience functions through factory */ /** * Zod Function Tool Provider creation convenience function (factory version) */ declare function createZodFunctionProvider(tools: Record<string, ZodFunctionTool<z.ZodObject<z.ZodRawShape>>>, options?: { logger?: (message: string, context?: Record<string, any>) => void; }): ToolProvider; /** * OpenAPI Tool Provider creation convenience function (factory version) */ declare function createOpenAPIProvider(openApiSpec: any, options?: { baseUrl?: string; logger?: (message: string, context?: Record<string, any>) => void; }): ToolProvider; /** * MCP Tool Provider creation convenience function (factory version) */ declare function createMCPProvider(mcpClient: MCPClient, options?: { logger?: (message: string, context?: Record<string, any>) => void; }): ToolProvider; /** * Tool interfaces and type definitions * * @module ToolInterfaces * @description * Common interfaces and type definitions used in the Tool module. */ /** * Tool result interface * * @template TResult - Result data type */ interface ToolResult$1<TResult = any> { status: 'success' | 'error'; data?: TResult; error?: string; } /** * Tool interface * * @description * Base interface that all tools must implement. */ interface ToolInterface { /** * Tool name */ name: string; /** * Tool description */ description?: string; /** * Tool schema */ schema: any; /** * Tool execution function */ execute: (args: any) => Promise<any>; /** * Convert to function definition */ toFunctionDefinition(): FunctionDefinition; } /** * Base tool options interface * * @template TParams - Parameter type * @template TResult - Result type */ interface BaseToolOptions<TParams = any, TResult = any> { name: string; description: string; category?: string; version?: string; validateParams?: boolean; execute: (params: TParams) => Promise<ToolResult$1<TResult>> | ToolResult$1<TResult>; beforeExecute?: (params: TParams) => Promise<TParams> | TParams; afterExecute?: (result: ToolResult$1<TResult>) => Promise<ToolResult$1<TResult>> | ToolResult$1<TResult>; } /** * Zod tool options interface * * @template TParams - Parameter type * @template TResult - Result type */ interface ZodToolOptions<TParams = any, TResult = any> extends BaseToolOptions<TParams, TResult> { parameters: z.ZodObject<any>; } /** * MCP tool options interface * * @template TParams - Parameter type * @template TResult - Result type */ interface McpToolOptions<TParams = any, TResult = any> extends BaseToolOptions<TParams, TResult> { parameters: { type: 'object'; properties: Record<string, any>; required?: string[]; }; } /** * OpenAPI tool options interface * * @template TParams - Parameter type * @template TResult - Result type */ interface OpenApiToolOptions<TParams = any, TResult = any> extends BaseToolOptions<TParams, TResult> { parameters: FunctionSchema['parameters']; } /** * Base tool abstract class * * @module BaseTool * @description * Base implementation for all tools. */ /** * Base tool abstract class * * @abstract * @class BaseTool * @implements {ToolInterface} * @description * Provides base implementation for all tools. * Common functionality is implemented here, schema-related methods are implemented in subclasses. * * @template TParams - Tool parameter type * @template TResult - Tool result type */ declare abstract class BaseTool<TParams = any, TResult = any> implements ToolInterface { /** * Tool name */ readonly name: string; /** * Tool description */ readonly description: string; /** * Tool category */ readonly category?: string; /** * Tool version */ readonly version?: string; /** * Whether to validate parameters */ protected readonly validateParams: boolean; /** * Tool execution function */ private readonly _execute; /** * Pre-execution hook */ private readonly beforeExecute?; /** * Post-execution hook */ private readonly afterExecute?; /** * Constructor * * @param options - Base tool options */ constructor(options: BaseToolOptions<TParams, TResult>); /** * Tool schema (implemented by subclasses) */ abstract get schema(): any; /** * Convert to JSON schema (implemented by subclasses) * * @returns JSON schema format parameter definition */ protected abstract toJsonSchema(): FunctionSchema['parameters']; /** * Validate parameters (implemented by subclasses) * * @param params - Parameters to validate * @returns Validated parameters */ protected abstract validateParameters(params: any): TParams; /** * Execute tool * * @param params - Tool parameters * @returns Tool execution result */ execute(params: TParams): Promise<ToolResult$1<TResult>>; /** * Convert to function schema * * @returns Function schema */ toFunctionSchema(): FunctionSchema; /** * Convert to function definition * * @returns Function definition */ toFunctionDefinition(): FunctionDefinition; /** * Generate string representation * * @returns String representation of the tool */ toString(): string; } /** * Zod schema-based tool * * @module ZodTool * @description * Tool that uses Zod schema for parameter validation. */ /** * Zod schema-based tool class * * @class ZodTool * @extends BaseTool * @description Tool that uses Zod schema for parameter validation. * * @template TParams - Tool parameter type * @template TResult - Tool result type * * @see {@link ../../../../apps/examples/02-functions | Function Tool Examples} */ declare class ZodTool<TParams = any, TResult = any> extends BaseTool<TParams, TResult> { /** * Zod schema */ private readonly parameters; /** * Constructor * * @param options - Zod tool options */ constructor(options: ZodToolOptions<TParams, TResult>); /** * Tool schema (returns Zod schema) * * @returns Zod schema */ get schema(): z.ZodObject<any>; /** * Convert Zod schema to JSON schema * * @returns JSON schema format parameter definition */ protected toJsonSchema(): FunctionSchema['parameters']; /** * Validate parameters using Zod schema * * @param params - Parameters to validate * @returns Validated parameters */ protected validateParameters(params: any): TParams; /** * Extract description from Zod type * * @param zodType - Zod type * @returns Description string */ private getZodDescription; /** * Convert Zod schema type to JSON schema type * * @param schema - Zod schema * @returns JSON schema type string */ private getSchemaType; /** * Check if Zod type is optional * * @param zodType - Zod type * @returns Whether the type is optional */ private isOptionalType; /** * Zod tool creation helper method * * @param options - Zod tool options * @returns ZodTool instance */ static create<TParams = any, TResult = any>(options: ZodToolOptions<TParams, TResult>): ZodTool<TParams, TResult>; } /** * MCP schema-based tool * * @module McpTool * @description * Tool that uses MCP (Model Context Protocol) schema format. */ /** * MCP schema-based tool class * * @class McpTool * @extends BaseTool * @description * Tool that uses MCP (Model Context Protocol) schema format for parameter definition. * * @template TParams - Tool parameter type * @template TResult - Tool result type * * @see {@link ../../../../apps/examples/03-integrations/01-mcp-client.ts | MCP Integration Example} */ declare class McpTool<TParams = any, TResult = any> extends BaseTool<TParams, TResult> { /** * MCP schema definition */ private readonly parameters; /** * Constructor * * @param options - MCP tool options */ constructor(options: McpToolOptions<TParams, TResult>); /** * Tool schema (returns MCP schema) * * @returns MCP schema */ get schema(): any; /** * Convert MCP schema to JSON schema * * @returns JSON schema format parameter definition */ protected toJsonSchema(): FunctionSchema['parameters']; /** * Validate parameters using MCP schema * * @param params - Parameters to validate * @returns Validated parameters (basic validation) */ protected validateParameters(params: any): TParams; /** * MCP tool creation helper method * * @param options - MCP tool options * @returns McpTool instance */ static create<TParams = any, TResult = any>(options: McpToolOptions<TParams, TResult>): McpTool<TParams, TResult>; } /** * OpenAPI schema-based tool * * @module OpenApiTool * @description * Tool that uses OpenAPI specification schema format. */ /** * OpenAPI schema-based tool class * * @class OpenApiTool * @extends BaseTool * @description Tool that uses OpenAPI specification schema format for parameter definition. * * @template TParams - Tool parameter type * @template TResult - Tool result type * * @see {@link ../../../../apps/examples/03-integrations/03-api-integration.ts | API Integration Example} */ declare class OpenApiTool<TParams = any, TResult = any> extends BaseTool<TParams, TResult> { /** * OpenAPI parameter schema */ private readonly parameters; /** * Constructor * * @param options - OpenAPI tool options */ constructor(options: OpenApiToolOptions<TParams, TResult>); /** * Tool schema (returns OpenAPI schema) * * @returns OpenAPI schema */ get schema(): FunctionSchema['parameters']; /** * Convert OpenAPI schema to JSON schema * * @returns JSON schema format parameter definition */ protected toJsonSchema(): FunctionSchema['parameters']; /** * Validate parameters using OpenAPI schema * * @param params - Parameters to validate * @returns Validated parameters (basic validation) */ protected validateParameters(params: any): TParams; /** * OpenAPI tool creation helper method * * @param options - OpenAPI tool options * @returns OpenApiTool instance */ static create<TParams = any, TResult = any>(options: OpenApiToolOptions<TParams, TResult>): OpenApiTool<TParams, TResult>; } /** * Lazy Loading System for Tool Performance Optimization * * @module lazy-loader * @description * Loads tools and related resources only when needed to optimize memory usage and initial loading time. */ /** * Interface for lazy loadable resources */ interface LazyLoadable<T> { /** Resource identifier */ id: string; /** Function to load the resource */ loader: () => Promise<T> | T; /** Whether the resource is loaded */ isLoaded: boolean; /** Loaded resource */ resource?: T; /** Last access time */ lastAccessed?: number; /** Loading priority (lower number = higher priority) */ priority?: number; } /** * Lazy loading statistics */ interface LazyLoadStats { /** Total registered resources count */ totalResources: number; /** Loaded resources count */ loadedResources: number; /** Load successes count */ loadSuccesses: number; /** Load failures count */ loadFailures: number; /** Average loading time (milliseconds) */ averageLoadTime: number; /** Total estimated memory usage */ estimatedMemoryUsage: number; } /** * Lazy loading manager class */ declare class LazyLoader<T = any> { private resources; private loadPromises; private loadTimes; private loadSuccesses; private loadFailures; private cache?; private maxConcurrentLoads; private currentLoads; private loadQueue; constructor(options?: { cache?: CacheManager<T>; maxConcurrentLoads?: number; }); /** * Register a lazy loadable resource */ register(resource: Omit<LazyLoadable<T>, 'isLoaded'>): void; /** * Register multiple resources at once */ registerMany(resources: Array<Omit<LazyLoadable<T>, 'isLoaded'>>): void; /** * Load resource (async) */ load(id: string): Promise<T>; /** * Load multiple resources in parallel */ loadMany(ids: string[]): Promise<T[]>; /** * Preload resources by priority */ preload(maxCount?: number): Promise<void>; /** * Unload resource (memory cleanup) */ unload(id: string): boolean; /** * Unload oldest resources (LRU based) */ unloadOldest(count: number): number; /** * Unload all resources */ unloadAll(): void; /** * Check if resource is loaded */ isLoaded(id: string): boolean; /** * Get all registered resource IDs */ getResourceIds(): string[]; /** * Get loaded resource IDs */ getLoadedResourceIds(): string[]; /** * Get lazy loading statistics */ getStats(): LazyLoadStats; /** * Perform actual loading */ private performLoad; /** * Process pending loading requests */ private processQueue; /** * Estimate resource size */ private estimateResourceSize; } /** * Tool-specific lazy loader */ declare class ToolLazyLoader extends LazyLoader<any> { constructor(); /** * Create lazy loading resource from tool definition */ registerTool(toolId: string, toolDefinition: any, priority?: number): void; } /** * Global tool lazy loader instance */ declare const globalToolLazyLoader: ToolLazyLoader; /** * Resource Manager for Memory Leak Prevention * * @module resource-manager * @description * Provides a system to prevent memory leaks and monitor resource usage. */ /** * Resource type definition */ type ResourceType = 'cache' | 'loader' | 'provider' | 'connection' | 'timer' | 'other'; /** * Resource information interface */ interface ResourceInfo { /** Resource identifier */ id: string; /** Resource type */ type: ResourceType; /** Creation time */ createdAt: number; /** Last used time */ lastUsed: number; /** Cleanup function */ cleanup: () => Promise<void> | void; /** Estimated memory usage */ memoryUsage?: number; /** Description */ description?: string; } /** * Memory usage information */ interface MemoryInfo { /** Heap usage (bytes) */ heapUsed: number; /** Heap size (bytes) */ heapTotal: number; /** External memory (bytes) */ external: number; /** RSS (Resident Set Size) */ rss: number; } /** * Resource statistics */ interface ResourceStats { /** Total resources count */ totalResources: number; /** Resource count by type */ byType: Record<ResourceType, number>; /** Oldest resource age (milliseconds) */ oldestResourceAge: number; /** Average resource age (milliseconds) */ averageResourceAge: number; /** Total estimated memory usage */ estimatedMemoryUsage: number; /** System memory information */ systemMemory: MemoryInfo; } /** * Resource manager class */ declare class ResourceManager { private resources; private cleanupInterval?; private memoryCheckInterval?; private maxAge; private maxMemoryUsage; private isShuttingDown; constructor(options?: { maxAge?: number; maxMemoryUsage?: number; cleanupIntervalMs?: number; memoryCheckIntervalMs?: number; }); /** * Register resource */ register(resourceInfo: Omit<ResourceInfo, 'createdAt' | 'lastUsed'>): void; /** * Update resource usage record */ markUsed(id: string): void; /** * Cleanup resource */ cleanup(id: string): Promise<boolean>; /** * Cleanup all resources */ cleanupAll(): Promise<number>; /** * Cleanup old resources */ cleanupOld(maxAge?: number): Promise<number>; /** * Cleanup high memory usage resources */ cleanupHighMemoryUsage(): Promise<number>; /** * Check if resource exists */ has(id: string): boolean; /** * Get all registered resource IDs */ getResourceIds(): string[]; /** * Get resource IDs by type */ getResourceIdsByType(type: ResourceType): string[]; /** * Get resource statistics */ getStats(): ResourceStats; /** * Cleanup on system shutdown */ shutdown(): Promise<void>; /** * Calculate total memory usage */ private getTotalMemoryUsage; /** * Perform periodic cleanup */ private performCleanup; /** * Check memory usage */ private checkMemoryUsage; /** * Get system memory information */ private getSystemMemoryInfo; } /** * Resource manager for Tool Providers */ declare class ToolProviderResourceManager extends ResourceManager { constructor(); /** * Register cache manager */ registerCache(id: string, cache: CacheManager, description?: string): void; /** * Register lazy loader */ registerLazyLoader(id: string, loader: LazyLoader, description?: string): void; /** * Register cleanup scheduler */ registerCleanupScheduler(id: string, scheduler: CacheCleanupScheduler, description?: string): void; } /** * Global resource manager instance */ declare const globalResourceManager: ToolProviderResourceManager; /** * Performance Monitor for Tool Performance Tracking * * @module performance-monitor * @description * Provides a system for real-time monitoring of tool performance and collecting metrics. */ /** * Performance metrics interface */ interface PerformanceMetrics { /** Tool call count */ toolCallCount: number; /** Average tool call time (milliseconds) */ averageCallTime: number; /** Maximum tool call time (milliseconds) */ maxCallTime: number; /** Minimum tool call time (milliseconds) */ minCallTime: number; /** Successful calls count */ successfulCalls: number; /** Failed calls count */ failedCalls: number; /** Success rate (0-1) */ successRate: number; /** Throughput (TPS - Transactions Per Second) */ throughput: number; /** Memory usage statistics */ memoryUsage: MemoryUsageMetrics; /** Cache performance statistics */ cacheMetrics: CacheStats | null; /** Lazy loading statistics */ lazyLoadMetrics: LazyLoadStats | null; /** Resource management statistics */ resourceMetrics: ResourceStats | null; } /** * Memory usage metrics */ interface MemoryUsageMetrics { /** Current heap usage (bytes) */ currentHeapUsed: number; /** Maximum heap usage (bytes) */ maxHeapUsed: number; /** Average heap usage (bytes) */ averageHeapUsed: number; /** External memory usage (bytes) */ external: number; /** RSS (Resident Set Size) */ rss: number; } /** * Tool call record */ interface ToolCallRecord { /** Tool name */ toolName: string; /** Call start time */ startTime: number; /** Call end time */ endTime: number; /** Execution duration (milliseconds) */ duration: number; /** Success status */ success: boolean; /** Error message (on failure) */ error?: string; /** Parameter size (bytes) */ parameterSize: number; /** Response size (bytes) */ responseSize: number; } /** * Performance event listener type */ type PerformanceEventListener = (metrics: PerformanceMetrics) => void; /** * Performance monitor class */ declare class PerformanceMonitor { private callRecords; private memorySnapshots; private maxRecords; private monitoringInterval?; private eventListeners; private isMonitoring; private cacheStatsProvider?; private lazyLoadStatsProvider?; private resourceStatsProvider?; constructor(options?: { maxRecords?: number; monitoringIntervalMs?: number; }); /** * Start monitoring */ startMonitoring(intervalMs?: number): void; /** * Stop monitoring */ stopMonitoring(): void; /** * Record tool call */ recordToolCall(record: ToolCallRecord): void; /** * Helper for recording tool call start time */ startToolCall(toolName: string, parameters: any): string; /** * Helper for recording tool call completion */ endToolCall(callId: string, success: boolean, response?: any, error?: string): void; /** * Register external statistics providers */ setCacheStatsProvider(provider: () => CacheStats): void; setLazyLoadStatsProvider(provider: () => LazyLoadStats): void; setResourceStatsProvider(provider: () => ResourceStats): void; /** * Register event listener */ addEventListener(listener: PerformanceEventListener): void; /** * Remove event listener */ removeEventListener(listener: PerformanceEventListener): void; /** * Get current performance metrics */ getMetrics(): PerformanceMetrics; /** * Get performance metrics for specific tool */ getToolMetrics(toolName: string): Partial<PerformanceMetrics>; /** * Reset performance metrics */ reset(): void; /** * Generate performance report */ generateReport(): string; /** * Collect memory snapshot */ private collectMemorySnapshot; /** * Calculate memory metrics */ private calculateMemoryMetrics; /** * Collect metrics and trigger events */ private collectMetrics; /** * Estimate object size */ private estimateObjectSize; } /** * Global performance monitor instance */ declare const globalPerformanceMonitor: PerformanceMonitor; /** * @module @robota-sdk/tools * * Tool library for Robota AI agents */ /** * Tool execution result type */ interface ToolResult<T = any> { /** * Whether tool execution was successful */ success: boolean; /** * Tool execution result data */ data?: T; /** * Error that occurred during tool execution */ error?: string; /** * Additional metadata */ metadata?: Record<string, any>; } /** * Tool parameter type */ interface ToolParameter { name: string; type: 'string' | 'number' | 'boolean' | 'object' | 'array'; description?: string; required?: boolean; defaultValue?: any; } /** * Tool interface */ interface Tool<TInput = any, TOutput = any> { /** * Tool name */ name: string; /** * Tool description */ description?: string; /** * Tool parameter definitions */ parameters?: ToolParameter[]; /** * Tool execution function * * @param input - Tool input parameters * @returns Execution result */ execute: (input: TInput) => Promise<ToolResult<TOutput>>; } /** * Tool creation options */ interface CreateToolOptions<TInput = any, TOutput = any> { /** * Tool name */ name: string; /** * Tool description */ description?: string; /** * Tool parameter definitions */ parameters?: ToolParameter[]; /** * Tool execution function */ execute: (input: TInput) => Promise<TOutput | ToolResult<TOutput>>; } /** * Tool creation function * * @param options - Tool creation options * @returns Created tool * * @see {@link ../../apps/examples/02-functions | Function Tool Examples} */ declare function createTool<TInput = any, TOutput = any>(options: CreateToolOptions<TInput, TOutput>): Tool<TInput, TOutput>; /** * Tool registry class * * Class for registering and managing multiple tools */ declare class ToolRegistry { private tools; /** * Register a tool * * @param tool - Tool to register */ register(tool: Tool): ToolRegistry; /** * Register multiple tools * * @param tools - Array of tools to register */ registerMany(tools: Tool[]): ToolRegistry; /** * Get a tool * * @param name - Name of the tool to get * @returns Tool or undefined */ getTool(name: string): Tool | undefined; /** * Get all tools * * @returns Array of all registered tools */ getAllTools(): Tool[]; /** * Execute a tool * * @param name - Name of the tool to execute * @param input - Tool input parameters * @returns Tool execution result */ executeTool<TInput = any, TOutput = any>(name: string, input: TInput): Promise<ToolResult<TOutput>>; } export { BaseTool, type BaseToolOptions, BaseToolProvider, CacheCleanupScheduler, type CacheItem, CacheManager, type CacheStats, type CreateToolOptions, type FunctionCall, type FunctionCallResult, type FunctionDefinition, type FunctionHandler, type FunctionOptions, FunctionRegistry, type FunctionResult, type FunctionSchema, FunctionSchemaCacheManager, type LazyLoadStats, type LazyLoadable, LazyLoader, type MCPClient, MCPToolProvider, type MCPToolProviderOptions, McpTool, type McpToolOptions, type MemoryInfo, type MemoryUsageMetrics, OpenAPIToolProvider, type OpenAPIToolProviderOptions, OpenApiTool, type OpenApiToolOptions, type PerformanceEventListener, type PerformanceMetrics, PerformanceMonitor, type ResourceInfo, ResourceManager, type ResourceStats, type ResourceType, type Tool, type ToolCallRecord, ToolExecutionError, type ToolFunction, type ToolInterface, ToolLazyLoader, ToolNotFoundError, type ToolParameter, type ToolProvider, type ToolProviderConfigs, ToolProviderError, ToolProviderFactory, ToolProviderResourceManager, type ToolProviderType, ToolRegistry, type ToolResult, type ZodFunctionTool, type ZodFunctionToolProviderOptions, ZodTool, type ZodToolOptions, convertZodTypeToJsonSchema, createFunction, createFunctionSchema, createMCPProvider, createMcpToolProvider, createOpenAPIProvider, createOpenAPIToolProvider, createTool, createValidatedFunction, createZodFunctionProvider, createZodFunctionToolProvider, functionFromCallback, getGlobalToolProviderFactory, getZodDescription, globalCacheCleanupScheduler, globalFunctionSchemaCache, globalPerformanceMonitor, globalResourceManager, globalToolCache, globalToolLazyLoader, isNullableType, isOptionalType, zodFunctionToSchema, zodToJsonSchema };