npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@meshailabs/sdk

v0.3.0

Published

MeshAI SDK for JavaScript/TypeScript - Universal AI Agent Orchestration with Memory

Downloads

16

Readme

MeshAI SDK for JavaScript/TypeScript

npm version TypeScript License: MIT

Universal AI Agent Orchestration Platform

MeshAI SDK enables seamless communication and orchestration between AI agents built on different frameworks. Connect agents from OpenAI, Anthropic, Google, LangChain, CrewAI, and more in a unified platform.

Features

  • Cross-Framework Communication - Agents from different platforms work together seamlessly
  • Intelligent Routing - Advanced strategies for optimal agent selection
  • Agent Instructions - Define comprehensive behavioral guidelines and guardrails
  • Context Preservation - Maintain conversation context across agents
  • Real-time Monitoring - WebSocket support for live task updates
  • TypeScript Support - Full type safety and IntelliSense
  • Production Ready - Built-in error handling, retries, and circuit breakers

Installation

npm install @meshailabs/sdk
# or
yarn add @meshailabs/sdk
# or
pnpm add @meshailabs/sdk

Quick Start

Basic Setup

Set your MeshAI API key:

export MESHAI_API_KEY="your-api-key"

Simple Task Execution

import { MeshClient } from '@meshailabs/sdk';

// Create client
const client = await MeshClient.createAndInitialize();

// Execute a task
const result = await client.quickExecute(
  'Analyze the sentiment of this text: I love using MeshAI!',
  ['sentiment-analysis']
);

console.log('Result:', result.result);

Advanced Usage

import { MeshClient, RoutingStrategy, TaskStatus } from '@meshailabs/sdk';

const client = new MeshClient({
  apiKey: process.env.MESHAI_API_KEY,
  defaultRoutingStrategy: RoutingStrategy.PERFORMANCE_BASED,
  timeout: 30000,
  maxRetries: 3
});

// Initialize the client
await client.initialize();

// Create a task with specific routing
const task = client.createTask(
  { prompt: 'Generate a business plan for a tech startup' },
  {
    taskType: 'generation',
    requiredCapabilities: ['business-planning', 'strategic-thinking'],
    routingStrategy: RoutingStrategy.CAPABILITY_MATCH,
    preserveContext: true,
    conversationId: 'session-123'
  }
);

// Execute with real-time updates
const result = await client.execute(task, {
  async: true,
  onProgress: (status, details) => {
    console.log(`Task status: ${status}`, details);
  },
  callback: (finalResult) => {
    console.log('Task completed:', finalResult);
  }
});

Agent Discovery

// Discover agents by capabilities
const agents = await client.discoverAgents({
  requiredCapabilities: ['code-generation', 'debugging'],
  preferredFramework: 'langchain',
  limit: 5
});

agents.forEach(agent => {
  console.log(`Agent: ${agent.name} (${agent.framework})`);
  console.log(`Capabilities: ${agent.capabilities?.join(', ')}`);
});

Agent Instructions

Define comprehensive behavioral guidelines for agents:

// Register agent with instructions
const agent = await client.registerAgent({
  id: 'assistant-001',
  name: 'Customer Assistant',
  framework: 'openai',
  capabilities: ['customer-support', 'problem-solving'],
  endpoint: 'https://api.openai.com/v1/chat/completions',

  // Define agent behavior
  instructions: {
    guidelines: [
      'Be professional and empathetic',
      'Provide clear, actionable solutions',
      'Follow company policies strictly'
    ],
    taskBoundaries: [
      'DO provide product support',
      'DO NOT share customer data',
      'DO NOT make unauthorized promises'
    ],
    outputFormat: 'Structured response with: Problem, Solution, Next Steps',
    guardrails: [
      'Verify customer identity before account changes',
      'Escalate complex technical issues'
    ]
  }
});

// Override instructions for specific tasks
const result = await client.execute({
  taskType: 'urgent_support',
  input: 'Customer complaint about service',
  instructions: {
    taskGuidelines: ['Prioritize immediate resolution'],
    constraints: ['Response within 2 minutes']
  }
});

Context Management

// Maintain conversation context
const conversationId = 'conv-' + Date.now();

// First task
const task1 = await client.execute(
  client.createTask('What is quantum computing?', {
    preserveContext: true,
    conversationId
  })
);

// Follow-up task with context
const task2 = await client.execute(
  client.createTask('How does it differ from classical computing?', {
    preserveContext: true,
    conversationId
  })
);

// Get full conversation history
const history = await client.getTaskHistory(conversationId);

Routing Strategies

| Strategy | Description | Use Case | |----------|-------------|----------| | ROUND_ROBIN | Distribute tasks evenly | Load balancing | | CAPABILITY_MATCH | Match agent capabilities | Specialized tasks | | LEAST_LOADED | Route to least busy agent | Performance optimization | | PERFORMANCE_BASED | Choose best performing | Quality-critical tasks | | STICKY_SESSION | Keep same agent | Context preservation | | COST_OPTIMIZED | Most cost-effective | Budget management | | GEOGRAPHIC | Geographic proximity | Latency optimization |

Configuration

const client = new MeshClient({
  // Authentication
  apiKey: 'your-api-key',
  
  // Service URLs (optional - defaults to MeshAI cloud)
  registryUrl: 'https://api.meshai.dev/registry',
  runtimeUrl: 'https://api.meshai.dev/runtime',
  
  // Performance
  timeout: 30000,              // 30 seconds
  maxRetries: 3,
  maxConcurrentTasks: 100,
  
  // Circuit breaker
  circuitBreakerEnabled: true,
  circuitBreakerThreshold: 5,
  
  // Monitoring
  metricsEnabled: true,
  logLevel: 'info'
});

Error Handling

import { 
  MeshError, 
  AuthenticationError, 
  TaskExecutionError,
  TimeoutError 
} from '@meshailabs/sdk';

try {
  const result = await client.execute(task);
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof TaskExecutionError) {
    console.error('Task failed:', error.taskId, error.message);
  } else if (error instanceof TimeoutError) {
    console.error('Task timed out');
  } else {
    console.error('Unknown error:', error);
  }
}

TypeScript Support

The SDK is written in TypeScript and provides full type definitions:

import {
  MeshClient,
  TaskData,
  TaskResult,
  AgentInfo,
  AgentRegistration,
  RoutingStrategy,
  TaskStatus,
  AgentStatus
} from '@meshailabs/sdk';

// All types are fully typed
const task: TaskData = {
  taskType: 'analysis',
  input: { data: 'sample' },
  requiredCapabilities: ['analysis'],
  routingStrategy: RoutingStrategy.CAPABILITY_MATCH,
  // New: Task-specific instructions
  instructions: {
    taskGuidelines: ['Focus on key insights'],
    outputRequirements: 'JSON format with findings array'
  }
};

// Agent with instructions
const agent: AgentRegistration = {
  id: 'agent-001',
  name: 'Analysis Agent',
  framework: 'langchain',
  capabilities: ['analysis'],
  endpoint: 'https://api.example.com',
  instructions: {
    guidelines: ['Provide data-driven insights'],
    guardrails: ['No PII in outputs']
  }
};

const result: TaskResult = await client.execute(task);

API Reference

MeshClient

Main client for interacting with MeshAI:

  • initialize() - Initialize the client
  • execute(task, options?) - Execute a task
  • executeWithAgent(agentId, task, options?) - Execute with specific agent
  • discoverAgents(query) - Find agents by capabilities
  • getAgent(agentId) - Get agent details
  • listAgents(limit?, offset?) - List all agents
  • quickExecute(input, capabilities?) - Simplified task execution

RegistryClient

Agent management operations:

  • registerAgent(registration) - Register new agent
  • updateAgent(agentId, updates) - Update agent info
  • deregisterAgent(agentId) - Remove agent
  • checkAgentHealth(agentId) - Health check
  • getAgentMetrics(agentId) - Performance metrics

RuntimeClient

Task execution operations:

  • execute(task, options?) - Execute task
  • executeBatch(tasks) - Execute multiple tasks
  • getTaskStatus(taskId) - Check task status
  • cancelTask(taskId) - Cancel running task
  • retryTask(taskId) - Retry failed task

MemoryClient

Persistent memory and learning capabilities:

  • healthCheck() - Check Memory Service health
  • storeEpisodic(memory) - Store complete task interaction
  • getEpisodic(memoryId) - Retrieve specific memory
  • listEpisodic(filters) - List memories with filters
  • searchSemantic(query) - Vector similarity search
  • getStats(filters?) - Memory statistics
  • generateSummary(agentId, hours) - Generate summary memory
  • getSummary(agentId, hours) - Retrieve summary
  • listProcedures(agentId, limit) - List learned patterns
  • getProcedure(procedureId) - Get procedure details
  • reflect(agentId, type, hours, areas?) - Perform self-evaluation
  • getReflection(agentId, type) - Retrieve reflection

Memory Client Example

import { MeshConfig, MemoryClient } from '@meshailabs/sdk';

const config = new MeshConfig({ apiKey: process.env.MESHAI_API_KEY });
const memory = new MemoryClient(config);

// Store episodic memory
await memory.storeEpisodic({
  agentId: 'agent-001',
  sessionId: 'session-123',
  interactionType: 'customer_query',
  inputData: { query: 'How do I reset my password?' },
  outputData: { response: 'Go to Settings > Security' },
  success: true,
  durationMs: 1250,
  tokensUsed: 150,
  tags: ['password', 'security']
});

// Semantic search for similar past interactions
const results = await memory.searchSemantic({
  agentId: 'agent-001',
  queryText: 'I forgot my login credentials',
  topK: 5,
  minSimilarity: 0.7
});

// Get memory statistics
const stats = await memory.getStats({ agentId: 'agent-001' });
console.log(`Total memories: ${stats.totalMemories}`);
console.log(`Success rate: ${(stats.successRate * 100).toFixed(1)}%`);

// Agent self-reflection
const reflection = await memory.reflect(
  'agent-001',
  'performance_analysis',
  168, // last week
  ['accuracy', 'response_time']
);
console.log('Insights:', reflection.insights);

For complete examples, see examples/memory-client.ts.

Examples

Basic Example

import { MeshClient } from '@meshailabs/sdk';

async function main() {
  const client = await MeshClient.createAndInitialize();
  
  const result = await client.quickExecute(
    'Translate "Hello World" to Spanish'
  );
  
  console.log(result.result);
  client.disconnect();
}

main().catch(console.error);

WebSocket Monitoring

const result = await client.execute(task, {
  async: true,
  onProgress: (status, details) => {
    console.log(`Status: ${status}`);
    if (details) {
      console.log('Details:', details);
    }
  },
  callback: (result) => {
    if (result.status === TaskStatus.COMPLETED) {
      console.log('Success:', result.result);
    } else if (result.status === TaskStatus.FAILED) {
      console.error('Failed:', result.error);
    }
  }
});

Support

License

MIT License - see LICENSE file for details

Contributing

Contributions are welcome! Please read our Contributing Guide for details.