@meshailabs/sdk
Version:
MeshAI SDK for JavaScript/TypeScript - Universal AI Agent Orchestration
490 lines (479 loc) • 14.1 kB
text/typescript
/**
* Type definitions for MeshAI SDK
*/
declare enum TaskStatus {
PENDING = "pending",
ROUTING = "routing",
EXECUTING = "executing",
COMPLETED = "completed",
FAILED = "failed",
CANCELLED = "cancelled"
}
declare enum AgentStatus {
ACTIVE = "active",
INACTIVE = "inactive",
ERROR = "error"
}
declare enum RoutingStrategy {
ROUND_ROBIN = "round_robin",
CAPABILITY_MATCH = "capability_match",
LEAST_LOADED = "least_loaded",
PERFORMANCE_BASED = "performance_based",
STICKY_SESSION = "sticky_session",
COST_OPTIMIZED = "cost_optimized",
GEOGRAPHIC = "geographic"
}
interface TaskData {
taskId?: string;
taskType: string;
input: string | Record<string, any>;
parameters?: Record<string, any>;
context?: Record<string, any>;
instructions?: string | {
taskGuidelines?: string[];
constraints?: string[];
outputRequirements?: string;
prioritization?: string[];
};
requiredCapabilities?: string[];
preferredFramework?: string;
routingStrategy?: RoutingStrategy;
timeoutSeconds?: number;
maxRetries?: number;
preserveContext?: boolean;
conversationId?: string;
createdAt?: Date;
sourceAgent?: string;
correlationId?: string;
}
interface TaskResult {
taskId: string;
status: TaskStatus;
result?: string | Record<string, any>;
error?: string;
agentId?: string;
executionTimeSeconds?: number;
startedAt?: Date;
completedAt?: Date;
retryCount?: number;
routingStrategyUsed?: RoutingStrategy;
contextUpdates?: Record<string, any>;
}
interface AgentInfo {
id: string;
name: string;
framework: string;
status: AgentStatus;
capabilities?: string[];
endpoint?: string;
instructions?: string | {
guidelines?: string[];
taskBoundaries?: string[];
outputFormat?: string;
edgeCaseHandling?: string[];
guardrails?: string[];
};
metadata?: Record<string, any>;
totalExecutions?: number;
successfulRuns?: number;
failedRuns?: number;
averageResponseTime?: number;
lastExecuted?: Date;
version?: string;
createdAt?: Date;
updatedAt?: Date;
}
interface AgentRegistration {
id: string;
name: string;
framework: string;
capabilities: string[];
endpoint: string;
instructions?: string | {
guidelines?: string[];
taskBoundaries?: string[];
outputFormat?: string;
edgeCaseHandling?: string[];
guardrails?: string[];
};
metadata?: Record<string, any>;
healthCheckEndpoint?: string;
maxConcurrentTasks?: number;
}
interface DiscoveryQuery {
requiredCapabilities?: string[];
preferredFramework?: string;
tags?: string[];
excludeAgentIds?: string[];
limit?: number;
}
/**
* Configuration management for MeshAI SDK
*/
interface MeshConfigOptions {
apiKey?: string;
registryUrl?: string;
runtimeUrl?: string;
timeout?: number;
maxRetries?: number;
retryDelay?: number;
connectionPoolSize?: number;
maxConcurrentTasks?: number;
circuitBreakerEnabled?: boolean;
circuitBreakerThreshold?: number;
circuitBreakerResetTimeout?: number;
defaultRoutingStrategy?: RoutingStrategy;
metricsEnabled?: boolean;
logLevel?: 'debug' | 'info' | 'warn' | 'error';
customHeaders?: Record<string, string>;
validateSsl?: boolean;
}
declare class MeshConfig {
readonly apiKey: string;
readonly registryUrl: string;
readonly runtimeUrl: string;
readonly timeout: number;
readonly maxRetries: number;
readonly retryDelay: number;
readonly connectionPoolSize: number;
readonly maxConcurrentTasks: number;
readonly circuitBreakerEnabled: boolean;
readonly circuitBreakerThreshold: number;
readonly circuitBreakerResetTimeout: number;
readonly defaultRoutingStrategy: RoutingStrategy;
readonly metricsEnabled: boolean;
readonly logLevel: 'debug' | 'info' | 'warn' | 'error';
readonly customHeaders: Record<string, string>;
readonly validateSsl: boolean;
constructor(options?: MeshConfigOptions);
/**
* Get headers for API requests
*/
getHeaders(): Record<string, string>;
/**
* Validate configuration
*/
validate(): void;
/**
* Create a copy of the config with overrides
*/
withOverrides(overrides: Partial<MeshConfigOptions>): MeshConfig;
}
/**
* Registry Client for MeshAI SDK
* Handles agent registration, discovery, and management
*/
declare class RegistryClient {
private config;
private client;
constructor(config: MeshConfig);
private setupInterceptors;
/**
* Register a new agent with MeshAI
*/
registerAgent(registration: AgentRegistration): Promise<AgentInfo>;
/**
* Update an existing agent
*/
updateAgent(agentId: string, updates: Partial<AgentRegistration>): Promise<AgentInfo>;
/**
* Deregister an agent
*/
deregisterAgent(agentId: string): Promise<void>;
/**
* Get agent information by ID
*/
getAgent(agentId: string): Promise<AgentInfo>;
/**
* List all registered agents
*/
listAgents(limit?: number, offset?: number): Promise<AgentInfo[]>;
/**
* Discover agents based on capabilities and requirements
*/
discoverAgents(query: DiscoveryQuery): Promise<AgentInfo[]>;
/**
* Check health of a specific agent
*/
checkAgentHealth(agentId: string): Promise<{
status: AgentStatus;
lastCheck: Date;
responseTime?: number;
error?: string;
}>;
/**
* Get agent metrics and statistics
*/
getAgentMetrics(agentId: string): Promise<{
totalExecutions: number;
successfulRuns: number;
failedRuns: number;
averageResponseTime: number;
lastExecuted?: Date;
}>;
/**
* Update agent status
*/
updateAgentStatus(agentId: string, status: AgentStatus): Promise<void>;
/**
* Heartbeat to maintain agent registration
*/
sendHeartbeat(agentId: string): Promise<void>;
/**
* Get system-wide statistics
*/
getSystemStats(): Promise<{
totalAgents: number;
activeAgents: number;
totalTasks: number;
avgResponseTime: number;
systemHealth: string;
}>;
}
/**
* Runtime Client for MeshAI SDK
* Handles task execution, routing, and monitoring
*/
interface ExecuteOptions {
async?: boolean;
callback?: (result: TaskResult) => void;
onProgress?: (status: TaskStatus, details?: any) => void;
}
declare class RuntimeClient {
private config;
private client;
private websocket?;
private taskCallbacks;
private progressCallbacks;
constructor(config: MeshConfig);
private setupInterceptors;
/**
* Execute a task through MeshAI runtime
*/
execute(task: TaskData, options?: ExecuteOptions): Promise<TaskResult>;
/**
* Execute task with specific agent
*/
executeWithAgent(agentId: string, task: TaskData, options?: ExecuteOptions): Promise<TaskResult>;
/**
* Execute batch of tasks
*/
executeBatch(tasks: TaskData[]): Promise<TaskResult[]>;
/**
* Get task status
*/
getTaskStatus(taskId: string): Promise<TaskResult>;
/**
* Cancel a running task
*/
cancelTask(taskId: string): Promise<void>;
/**
* Retry a failed task
*/
retryTask(taskId: string): Promise<TaskResult>;
/**
* Get task history for a conversation
*/
getTaskHistory(conversationId: string): Promise<TaskResult[]>;
/**
* Get conversation context
*/
getConversationContext(conversationId: string): Promise<Record<string, any>>;
/**
* Update conversation context
*/
updateConversationContext(conversationId: string, updates: Record<string, any>): Promise<void>;
/**
* Setup WebSocket monitoring for async tasks
*/
private setupWebSocketMonitoring;
/**
* Connect to WebSocket for real-time updates
*/
private connectWebSocket;
/**
* Handle WebSocket messages
*/
private handleWebSocketMessage;
/**
* Disconnect WebSocket
*/
disconnect(): void;
}
/**
* Main MeshClient for MeshAI SDK
* Coordinates Registry and Runtime operations
*/
declare class MeshClient {
readonly config: MeshConfig;
readonly registry: RegistryClient;
readonly runtime: RuntimeClient;
private initialized;
constructor(options?: MeshConfigOptions);
/**
* Initialize the client and validate configuration
*/
initialize(): Promise<void>;
/**
* Register an agent with MeshAI
*/
registerAgent(registration: AgentRegistration): Promise<AgentInfo>;
/**
* Execute a task using intelligent routing
*/
execute(task: TaskData, options?: ExecuteOptions): Promise<TaskResult>;
/**
* Execute a task with a specific agent
*/
executeWithAgent(agentId: string, task: TaskData, options?: ExecuteOptions): Promise<TaskResult>;
/**
* Discover agents based on capabilities
*/
discoverAgents(query: DiscoveryQuery): Promise<AgentInfo[]>;
/**
* Get agent by ID
*/
getAgent(agentId: string): Promise<AgentInfo>;
/**
* List all available agents
*/
listAgents(limit?: number, offset?: number): Promise<AgentInfo[]>;
/**
* Update agent information
*/
updateAgent(agentId: string, updates: Partial<AgentRegistration>): Promise<AgentInfo>;
/**
* Deregister an agent
*/
deregisterAgent(agentId: string): Promise<void>;
/**
* Check agent health
*/
checkAgentHealth(agentId: string): Promise<{
status: AgentStatus;
lastCheck: Date;
responseTime?: number;
error?: string;
}>;
/**
* Get task status
*/
getTaskStatus(taskId: string): Promise<TaskResult>;
/**
* Cancel a running task
*/
cancelTask(taskId: string): Promise<void>;
/**
* Retry a failed task
*/
retryTask(taskId: string): Promise<TaskResult>;
/**
* Execute batch of tasks
*/
executeBatch(tasks: TaskData[]): Promise<TaskResult[]>;
/**
* Get conversation context
*/
getConversationContext(conversationId: string): Promise<Record<string, any>>;
/**
* Update conversation context
*/
updateConversationContext(conversationId: string, updates: Record<string, any>): Promise<void>;
/**
* Get task history for a conversation
*/
getTaskHistory(conversationId: string): Promise<TaskResult[]>;
/**
* Get system statistics
*/
getSystemStats(): Promise<{
totalAgents: number;
activeAgents: number;
totalTasks: number;
avgResponseTime: number;
systemHealth: string;
}>;
/**
* Get agent metrics
*/
getAgentMetrics(agentId: string): Promise<{
totalExecutions: number;
successfulRuns: number;
failedRuns: number;
averageResponseTime: number;
lastExecuted?: Date;
}>;
/**
* Update agent status
*/
updateAgentStatus(agentId: string, status: AgentStatus): Promise<void>;
/**
* Send heartbeat to maintain agent registration
*/
sendHeartbeat(agentId: string): Promise<void>;
/**
* Create a task with default configuration
*/
createTask(input: string | Record<string, any>, options?: Partial<TaskData>): TaskData;
/**
* Quick execute - simplified task execution
*/
quickExecute(input: string | Record<string, any>, capabilities?: string[]): Promise<TaskResult>;
/**
* Disconnect and cleanup resources
*/
disconnect(): void;
/**
* Ensure client is initialized
*/
private ensureInitialized;
/**
* Create a new MeshClient instance
*/
static create(options?: MeshConfigOptions): MeshClient;
/**
* Create and initialize a MeshClient
*/
static createAndInitialize(options?: MeshConfigOptions): Promise<MeshClient>;
}
/**
* Custom error classes for MeshAI SDK
*/
declare class MeshError extends Error {
readonly code?: string;
readonly statusCode?: number;
readonly details?: Record<string, any>;
constructor(message: string, code?: string, statusCode?: number, details?: Record<string, any>);
}
declare class AuthenticationError extends MeshError {
constructor(message?: string, details?: Record<string, any>);
}
declare class AuthorizationError extends MeshError {
constructor(message?: string, details?: Record<string, any>);
}
declare class ValidationError extends MeshError {
constructor(message: string, details?: Record<string, any>);
}
declare class NotFoundError extends MeshError {
constructor(resource: string, identifier?: string);
}
declare class TimeoutError extends MeshError {
constructor(message?: string, timeoutSeconds?: number);
}
declare class RateLimitError extends MeshError {
readonly retryAfter?: number;
constructor(message?: string, retryAfter?: number);
}
declare class NetworkError extends MeshError {
constructor(message?: string, details?: Record<string, any>);
}
declare class AgentError extends MeshError {
readonly agentId?: string;
constructor(message: string, agentId?: string, details?: Record<string, any>);
}
declare class TaskExecutionError extends MeshError {
readonly taskId?: string;
readonly agentId?: string;
constructor(message: string, taskId?: string, agentId?: string, details?: Record<string, any>);
}
export { AgentError, AgentInfo, AgentRegistration, AgentStatus, AuthenticationError, AuthorizationError, DiscoveryQuery, MeshClient, MeshConfig, MeshError, NetworkError, NotFoundError, RateLimitError, RegistryClient, RoutingStrategy, RuntimeClient, TaskData, TaskExecutionError, TaskResult, TaskStatus, TimeoutError, ValidationError };