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

@agentxjs/network

v1.9.0

Published

Network layer abstraction for AgentX platform - WebSocket client/server with heartbeat and auto-reconnect

Downloads

2,228

Readme

@agentxjs/network

WebSocket communication layer for AgentX with reliable message delivery.

Features

  • Reliable Message Delivery - ACK-based confirmation with timeout handling
  • Cross-Platform Client - Node.js and Browser support with auto-reconnect
  • Heartbeat - Connection health monitoring via ping/pong
  • Modular Design - Separate protocol, server, and client modules

Installation

bun add @agentxjs/network

Quick Start

Server

import { WebSocketServer } from "@agentxjs/network";

const server = new WebSocketServer({
  heartbeat: true,
  heartbeatInterval: 30000,
});

server.onConnection((connection) => {
  console.log("Client connected:", connection.id);

  connection.onMessage((message) => {
    console.log("Received:", message);
  });

  // Send with delivery confirmation
  connection.sendReliable(JSON.stringify({ type: "welcome" }), {
    onAck: () => console.log("Client received the message"),
    timeout: 5000,
    onTimeout: () => console.log("Client did not acknowledge"),
  });
});

await server.listen(5200);

Client (Node.js)

import { createWebSocketClient } from "@agentxjs/network";

const client = await createWebSocketClient({
  serverUrl: "ws://localhost:5200",
});

client.onMessage((message) => {
  console.log("Received:", message);
  // ACK is sent automatically for reliable messages
});

client.send(JSON.stringify({ type: "hello" }));

Client (Browser)

import { createWebSocketClient } from "@agentxjs/network";

const client = await createWebSocketClient({
  serverUrl: "ws://localhost:5200",
  autoReconnect: true,
  maxReconnectionDelay: 10000,
});

client.onMessage((message) => {
  console.log("Received:", message);
});

client.onClose(() => {
  console.log("Disconnected, will auto-reconnect...");
});

API Reference

WebSocketServer

import { WebSocketServer } from "@agentxjs/network";

const server = new WebSocketServer(options?: ChannelServerOptions);

Options:

| Option | Type | Default | Description | | ------------------- | --------- | ------- | -------------------------- | | heartbeat | boolean | true | Enable ping/pong heartbeat | | heartbeatInterval | number | 30000 | Heartbeat interval in ms |

Methods:

| Method | Description | | --------------------------- | ------------------------------ | | listen(port, host?) | Start standalone server | | attach(httpServer, path?) | Attach to existing HTTP server | | onConnection(handler) | Register connection handler | | broadcast(message) | Send to all connections | | close() | Close all connections | | dispose() | Release all resources |

WebSocketConnection

Server-side representation of a client connection.

interface ChannelConnection {
  readonly id: string;

  // Basic send (fire-and-forget)
  send(message: string): void;

  // Reliable send with ACK
  sendReliable(message: string, options?: SendReliableOptions): void;

  // Event handlers
  onMessage(handler: (message: string) => void): Unsubscribe;
  onClose(handler: () => void): Unsubscribe;
  onError(handler: (error: Error) => void): Unsubscribe;

  close(): void;
}

SendReliableOptions:

interface SendReliableOptions {
  onAck?: () => void; // Called when client acknowledges
  timeout?: number; // ACK timeout in ms (default: 5000)
  onTimeout?: () => void; // Called if ACK times out
}

WebSocketClient

import { createWebSocketClient } from "@agentxjs/network";

const client = await createWebSocketClient(options: ChannelClientOptions);

Options:

| Option | Type | Default | Description | | ---------------------- | -------------------- | ---------------- | ----------------------------- | | serverUrl | string | required | WebSocket server URL | | autoReconnect | boolean | true (browser) | Auto-reconnect on disconnect | | minReconnectionDelay | number | 1000 | Min delay between reconnects | | maxReconnectionDelay | number | 10000 | Max delay between reconnects | | maxRetries | number | Infinity | Max reconnection attempts | | connectionTimeout | number | 4000 | Connection timeout in ms | | headers | object \| function | - | Custom headers (Node.js only) |

Methods:

| Method | Description | | -------------------- | ------------------------ | | send(message) | Send message to server | | onMessage(handler) | Handle incoming messages | | onOpen(handler) | Handle connection open | | onClose(handler) | Handle connection close | | onError(handler) | Handle errors | | close() | Close connection | | dispose() | Release all resources |

Reliable Message Protocol

The sendReliable() method provides guaranteed message delivery:

Server                              Client
   │                                   │
   │  ──── { __msgId, __payload } ──►  │
   │                                   │
   │  ◄──── { __ack: msgId } ────────  │
   │                                   │
   ▼ onAck() called                    ▼

How it works:

  1. Server wraps message with unique __msgId
  2. Client receives, extracts payload, auto-sends __ack
  3. Server receives ACK, triggers onAck callback
  4. If no ACK within timeout, triggers onTimeout

Use cases:

  • Persist data only after client confirms receipt
  • Track message delivery status
  • Implement at-least-once delivery semantics

Architecture

@agentxjs/network
├── protocol/
│   └── reliable-message.ts    # ACK protocol types
│
├── server/
│   ├── WebSocketConnection.ts # Connection with sendReliable
│   └── WebSocketServer.ts     # Server management
│
├── client/
│   ├── WebSocketClient.ts     # Node.js client
│   └── BrowserWebSocketClient.ts # Browser client with reconnect
│
└── factory.ts                 # createWebSocketClient

Examples

Attach to HTTP Server

import { createServer } from "node:http";
import { WebSocketServer } from "@agentxjs/network";

const httpServer = createServer((req, res) => {
  res.end("HTTP endpoint");
});

const wsServer = new WebSocketServer();
wsServer.attach(httpServer, "/ws");

httpServer.listen(5200);

Custom Headers (Node.js)

const client = await createWebSocketClient({
  serverUrl: "ws://localhost:5200",
  headers: {
    Authorization: "Bearer token123",
  },
});

// Or dynamic headers
const client = await createWebSocketClient({
  serverUrl: "ws://localhost:5200",
  headers: async () => ({
    Authorization: `Bearer ${await getToken()}`,
  }),
});

Reliable Delivery with Persistence

server.onConnection((connection) => {
  // Only persist after client confirms receipt
  connection.sendReliable(JSON.stringify(event), {
    onAck: () => {
      database.save(event);
      console.log("Event persisted after client ACK");
    },
    timeout: 10000,
    onTimeout: () => {
      console.log("Client did not acknowledge, will retry...");
    },
  });
});

Testing

bun test

52 tests covering:

  • Protocol type guards
  • Connection send/sendReliable
  • ACK handling and timeouts
  • Server lifecycle
  • Client auto-ACK

License

MIT