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

@egain/ai-agent-sdk

v0.1.1

Published

TypeScript SDK for eGain's AI Agent platform

Readme

@egain/ai-agent-sdk

TypeScript-first SDK for eGain's AI Agent platform with WebSocket communication, automatic reconnection, and comprehensive message handling.

Current release: v0.0.14

npm version TypeScript License: MIT

Features

  • 🔌 WebSocket Communication - Real-time bidirectional messaging with auto-reconnection
  • 📬 Message Queuing - Automatic queuing when offline, flush on reconnect
  • 🔐 Multiple Auth Strategies - Pre-Auth, Anonymous, PKCE, Client Credentials
  • 🎯 Type-Safe Events - Full TypeScript support with strongly-typed events
  • 📝 Transcript Management - Built-in conversation history with filtering
  • 🧠 Context Persistence - Automatic caching and restoration on reconnect
  • 🛡️ Error Handling - Comprehensive typed errors that protect your app
  • 🌐 Universal - Works in Browser and Node.js
  • 🏢 Portal initialization - Contact center REST pipeline (portals, agents, profiles) before WebSocket connect()
  • 🔌 Platform connectors - Load CC connector scripts; typed HookContract / PlatformComponentService for integrators

Installation

npm install @egain/ai-agent-sdk

Quick Start

import { AiAgent } from "@egain/ai-agent-sdk";

const agent = new AiAgent({
  id: "your-agent-id",
  endpoint: "https://your-endpoint.com",
  auth: { type: "pre-auth", accessToken: "your-access-token" },
  autoConnect: true
});

agent.on("agentMessage", (event) => {
  console.log("Agent:", event.payload.message?.content);
});

agent.on("error", (event) => {
  console.error("Error:", event.payload.error);
});

await agent.initialize();
await agent.send("Hello!");

Contact center (portal flow)

For agents that use the portal / profile pipeline, listen for selection events and call connect() after initialized:

import { AiAgent } from "@egain/ai-agent-sdk";

const agent = new AiAgent({
  id: "your-agent-id",
  endpoint: "https://your-endpoint.com",
  initParams: { authType: "user", userid: "user-1", platform: "standalone" },
  authScheme: "popup",
});

agent.on("portalsAvailable", (e) => agent.selectPortal(e.payload.portals[0]));
agent.on("profilesAvailable", (e) => agent.selectUserProfile(e.payload.profiles[0]));
agent.on("initialized", async () => {
  await agent.connect();
});

await agent.initialize();

See the Portal initialization guide for the full flow.

Documentation

Published docs and TypeDoc on the site below describe the current release (version at top of this file).

📚 Full Documentation

| Guide | Description | |-------|-------------| | Getting Started | Introduction and concepts | | Installation | Setup instructions | | Quick Start | First integration | | Authentication | Auth strategies | | Events | Event handling | | Portal initialization | CC portal / agent / profile pipeline | | Platform connectors | Connector scripts and HookContract | | Message Flow | Sending/receiving messages | | API Reference | TypeDoc: classes, interfaces, and methods | | Types | Portal, UserProfile, AgentListItem, API options (see TypeDoc index) |

Authentication Options

// Pre-Auth (API Key / Token)
auth: { type: "pre-auth", accessToken: "your-access-token" }

// Anonymous
auth: { type: "anonymous" }

// PKCE (Browser OAuth)
auth: {
  type: "pkce",
  config: {
    authorizationUrl: "https://auth.example.com/authorize",
    tokenUrl: "https://auth.example.com/token",
    clientId: "your-client-id",
    redirectUri: "https://your-app.com/callback"
  }
}

// Pre-Auth (Server-provided token)
auth: {
  type: "pre-auth",
  accessToken: "token-from-server"
}

Events

agent.on("connected", (event) => { /* Connected */ });
agent.on("agentMessage", (event) => { /* Agent response */ });
agent.on("message", (event) => { /* Any message */ });
agent.on("heartbeat", (event) => { /* Agent typing */ });
agent.on("error", (event) => { /* Error occurred */ });
agent.on("closed", (event) => { /* Disconnected */ });
agent.on("stateChanged", (event) => { /* State change */ });
agent.on("queueFlushed", (event) => { /* Queue sent */ });
agent.on("tokenExpiring", (event) => { /* Token refresh needed */ });
agent.on("transcriptUpdate", (event) => { /* Chat transcript line */ });
agent.on("initialized", (event) => { /* CC init done; safe to connect */ });
agent.on("portalsAvailable", (event) => { /* Call selectPortal */ });
agent.on("agentsAvailable", (event) => { /* Call selectAgent */ });
agent.on("profilesAvailable", (event) => { /* Call selectUserProfile */ });

Message Helpers

import {
  createContextMessage,
  createFeedbackMessage,
  createEscalationMessage
} from "@egain/ai-agent-sdk";

// Send context (auto-cached for reconnect)
await agent.send(createContextMessage({
  context: { userId: "123", language: "en" }
}));

// Send feedback
await agent.send(createFeedbackMessage({
  rating: 5,
  answerMessageId: "msg-456"
}));

// Trigger escalation
await agent.send(createEscalationMessage({
  escalationEvent: { type: "transfer", reason: "complex" }
}));

Node.js Setup

npm install ws

The SDK automatically loads the ws package when running in Node.js. Just import and use:

import { AiAgent } from "@egain/ai-agent-sdk";

const agent = new AiAgent({
  id: "your-agent-id",
  endpoint: "https://your-endpoint.com",
  auth: { type: "pre-auth", accessToken: process.env.AI_AGENT_TOKEN }
});
// ... rest of code

If the automatic polyfill doesn't work in your environment, you can set it up manually:

import WebSocket from "ws";
(global as any).WebSocket = WebSocket;

import { AiAgent } from "@egain/ai-agent-sdk";
// ... rest of code

Browser (UMD)

<script src="https://unpkg.com/@egain/ai-agent-sdk/dist/browser.js"></script>
<script>
  const agent = new eGain.AiAgent({ ... });
</script>

Development

# Install dependencies
npm install

# Build
npm run build:all

# Test
npm test

# Documentation
npm run docs:dev     # Dev server
npm run docs:build   # Build docs

Examples

See usage-examples in this repository for complete examples:

  • Basic Usage - Simple getting started
  • Browser Test - Browser integration with UI
  • Server Test - Node.js implementation

API Reference

AiAgent Methods

| Method | Description | |--------|-------------| | initialize() | Initialize the agent (required) | | connect() | Connect to the server | | disconnect(options?) | Disconnect from server | | restartConnection() | Restart with new session | | send(data, options?) | Send a message | | getState() | Get connection state | | isConnected() | Check if connected | | getTranscript(options?) | Get conversation transcript | | getContext() | Get stored context | | removeContext() | Remove stored context | | updateAccessToken(token) | Update auth token | | selectPortal(portal) | CC: continue after portalsAvailable | | selectAgent(agent) | CC Flow B: continue after agentsAvailable | | selectUserProfile(profile) | CC: continue after profilesAvailable | | getInitParams() | Copy of configured initParams | | getIsInitialized() | Whether initialize() completed | | restartPortalInitializer() | Re-run CC portal pipeline (or restartConnection fallback) | | updateUserProfile(profile) | Switch profile after CC init without full pipeline restart | | getUserDetails() | User details from init (or null) | | getCallTranscript() / clearCallTranscript() | Telephony call transcript (connector) | | getCallerInfo() / getConversationId() | Connector-provided CTI state |

Configuration

new AiAgent({
  id: string,                    // Required: Agent ID
  endpoint: string,              // Required: Endpoint URL
  auth?: AuthenticationInput,    // Optional: Auth config (defaults to anonymous)
  autoConnect?: boolean,         // Auto-connect (default: false)
  maxQueueSize?: number,         // Queue size (default: 1000)
  maxReconnectAttempts?: number, // Reconnect attempts (default: Infinity)
  baseReconnectDelay?: number,   // Base delay ms (default: 1000)
  maxReconnectDelay?: number,    // Max delay ms (default: 30000)
  logLevel?: LogLevel,           // Log level (default: INFO)
  transcriptConfig?: TranscriptConfig,
  cache?: CacheConfig,
  sessionId?: string | number,  // Skip session fetch if already known
  scopes?: string[],              // OAuth resource scopes
  initParams?: Record<string, string>, // CC: portalIds, authType, platform, etc.
  platformScriptUrl?: string,     // Override connector script URL
  authScheme?: "popup" | "redirect" // Auto-built PKCE only
});

License

MIT

Support

For issues and questions, please open an issue on GitHub.