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

@haip/server

v1.0.1

Published

Reference implementation of HAIP (Human-Agent Interaction Protocol) server

Readme

HAIP Server

npm version npm downloads License: MIT

A reference implementation of the HAIP (Human-Agent Interaction Protocol) server with support for WebSocket, Server-Sent Events (SSE), and HTTP streaming transports.

Features

  • Full HAI Protocol Support - Complete implementation of HAIP 1.1.2
  • Multiple Transports - WebSocket, SSE, and HTTP streaming
  • Authentication - JWT-based authentication
  • Flow Control - Credit-based flow control with back-pressure management
  • Tool Integration - Model Context Protocol (MCP) tool support
  • Run Management - Complete run lifecycle management
  • Binary Data - Support for audio chunks and binary frames
  • Heartbeat - Automatic ping/pong for connection health
  • Replay Support - Message replay with sequence ranges
  • Error Handling - Comprehensive error handling and recovery
  • Performance Monitoring - Real-time server statistics

Quick Start

Installation

# Clone the repository
git clone https://github.com/haiprotocol/haip-server.git
cd haip-server

# Install dependencies
npm install

# Build the server
npm run build

# Start the server
npm start

Environment Variables

# Server configuration
PORT=8080
HOST=0.0.0.0

# Security
JWT_SECRET=your-secret-key-change-in-production
JWT_EXPIRES_IN=24h

# Performance
MAX_CONNECTIONS=1000
HEARTBEAT_INTERVAL=30000
HEARTBEAT_TIMEOUT=5000

# Features
ENABLE_CORS=true
ENABLE_COMPRESSION=true
ENABLE_LOGGING=true

Development

# Start in development mode
npm run dev

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Lint code
npm run lint

# Fix linting issues
npm run lint:fix

API Endpoints

WebSocket

ws://localhost:8080?token=your-jwt-token

Server-Sent Events (SSE)

GET /haip/sse?token=your-jwt-token

HTTP Streaming

POST /haip/stream
Authorization: Bearer your-jwt-token

Health Check

GET /health

Server Statistics

GET /stats

Usage Examples

WebSocket Connection

import { createHAIPClient } from '@haip/sdk';

const client = createHAIPClient({
  url: 'ws://localhost:8080',
  token: 'your-jwt-token'
});

await client.connect();

// Send a text message
const messageId = await client.sendTextMessage('USER', 'Hello, HAIP!');

// Start a run
const runId = await client.startRun('thread-123', { metadata: 'test' });

// Call a tool
const callId = await client.callTool('AGENT', 'echo', { message: 'Hello' });

Server-Sent Events

const eventSource = new EventSource('/haip/sse?token=your-jwt-token');

eventSource.onmessage = (event) => {
  const message = JSON.parse(event.data);
  console.log('Received message:', message);
};

eventSource.onerror = (error) => {
  console.error('SSE error:', error);
};

HTTP Streaming

const response = await fetch('/haip/stream', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer your-jwt-token',
    'Content-Type': 'application/json'
  }
});

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  
  const chunk = decoder.decode(value);
  const messages = chunk.split('\n').filter(line => line.trim());
  
  for (const messageStr of messages) {
    const message = JSON.parse(messageStr);
    console.log('Received message:', message);
  }
}

Tool Integration

Registering Tools

import { HAIPServer } from 'haip-server';

const server = new HAIPServer();

// Register a simple echo tool
server.registerTool({
  name: 'echo',
  description: 'Echo back the input',
  inputSchema: {
    type: 'object',
    properties: {
      message: { type: 'string' }
    },
    required: ['message']
  },
  outputSchema: {
    type: 'object',
    properties: {
      echoed: { type: 'string' }
    }
  }
});

// Register a math tool
server.registerTool({
  name: 'add',
  description: 'Add two numbers',
  inputSchema: {
    type: 'object',
    properties: {
      a: { type: 'number' },
      b: { type: 'number' }
    },
    required: ['a', 'b']
  },
  outputSchema: {
    type: 'object',
    properties: {
      result: { type: 'number' }
    }
  }
});

Custom Tool Implementation

// Handle tool calls
server.on('toolCall', (sessionId, execution) => {
  console.log(`Tool call: ${execution.toolName}`, execution.arguments);
  
  // Implement your tool logic here
  if (execution.toolName === 'echo') {
    const result = { echoed: execution.arguments.message };
    server.sendToolDone(sessionId, execution.callId, 'OK', result);
  } else if (execution.toolName === 'add') {
    const result = { result: execution.arguments.a + execution.arguments.b };
    server.sendToolDone(sessionId, execution.callId, 'OK', result);
  }
});

Flow Control

The server implements credit-based flow control to prevent overwhelming the system:

// Flow control configuration
const flowControl = {
  enabled: true,
  initialCredits: 1000,
  minCredits: 100,
  maxCredits: 10000,
  creditThreshold: 200,
  backPressureThreshold: 0.8,
  adaptiveAdjustment: true,
  initialCreditMessages: 1000,
  initialCreditBytes: 1024 * 1024
};

const server = new HAIPServer({
  flowControl
});

Error Handling

The server provides comprehensive error handling:

// Handle server events
server.on('error', (error) => {
  console.error('Server error:', error);
});

server.on('connect', (sessionId) => {
  console.log('Client connected:', sessionId);
});

server.on('disconnect', (sessionId) => {
  console.log('Client disconnected:', sessionId);
});

server.on('handshake', (sessionId, payload) => {
  console.log('Handshake completed:', sessionId, payload);
});

Performance Monitoring

Monitor server performance with built-in statistics:

// Get server statistics
const stats = server.getStats();
console.log('Server stats:', {
  activeConnections: stats.activeConnections,
  totalConnections: stats.totalConnections,
  messagesPerSecond: stats.messagesPerSecond,
  averageLatency: stats.averageLatency,
  errorRate: stats.errorRate,
  uptime: stats.uptime
});

Security

JWT Authentication

The server uses JWT tokens for authentication:

// Generate a JWT token (client-side)
const jwt = require('jsonwebtoken');

const token = jwt.sign(
  { userId: 'user-123', exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60) },
  'your-secret-key'
);

CORS Configuration

Enable CORS for browser clients:

const server = new HAIPServer({
  enableCORS: true
});

Testing

Unit Tests

npm test

Integration Tests

npm run test:integration

Load Testing

npm run test:load

Deployment

Docker

FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY dist ./dist

EXPOSE 8080

CMD ["node", "dist/index.js"]

Docker Compose

version: '3.8'
services:
  haip-server:
    build: .
    ports:
      - "8080:8080"
    environment:
      - JWT_SECRET=your-secret-key
      - PORT=8080
    restart: unless-stopped

Kubernetes

apiVersion: apps/v1
kind: Deployment
metadata:
  name: haip-server
spec:
  replicas: 3
  selector:
    matchLabels:
      app: haip-server
  template:
    metadata:
      labels:
        app: haip-server
    spec:
      containers:
      - name: haip-server
        image: haip-protocol/haip-server:latest
        ports:
        - containerPort: 8080
        env:
        - name: JWT_SECRET
          valueFrom:
            secretKeyRef:
              name: haip-secrets
              key: jwt-secret
        - name: PORT
          value: "8080"
---
apiVersion: v1
kind: Service
metadata:
  name: haip-server
spec:
  selector:
    app: haip-server
  ports:
  - port: 8080
    targetPort: 8080
  type: LoadBalancer

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Run the test suite
  6. Submit a pull request

License

MIT License - see LICENSE file for details.

Protocol Version

This SDK implements HAIP version 1.1.2. For protocol documentation, see the HAI Protocol Specification.