@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.3.3
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/PlatformComponentServicefor integrators - 🎭 Data masking - Department chat patterns when enabled in agent config; masks outbound customer messages and
maskContent()for UI/escalation
Installation
npm install @egain/ai-agent-sdk
Quick Start
The sample below uses the pre-auth option, where your server obtains an access token and passes it directly to the SDK. Before running it, generate an access token using the PKCE flow:
Generating An Access Token using PKCE Flow
Required scopes:
core.aiservices.readknowledge.portalmgr.managecore.customermgr.read(required for AI Agent for Customer Self Service only)
Sample Code
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).
| 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"
}
All built-in strategies treat an access token as stale five minutes before its JWT exp, so session create and other APIs stay ahead of the server’s ~290s “token will expire soon” guard. The same value is exported for custom hosts:
import {
ACCESS_TOKEN_REFRESH_BUFFER_MS,
ACCESS_TOKEN_REFRESH_BUFFER_MINUTES
} from "@egain/ai-agent-sdk";
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 */
});
agent.on("contextValidation", (event) => {
/* Rejected context attributes */
});
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(options?) | Initialize the agent (optional { context } for portal/profile auto-select) |
connect() | Connect to the server |
disconnect(options?) | Disconnect from server |
restartConnection() | Restart with new session |
send(data, options?) | Send a message |
maskContent(text) | Mask plain text with loaded patterns (UI/escalation; send() masks eligible messages automatically) |
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 (persists select, busts profile list caches, restarts session) |
getUserDetails() | User/customer details from init when the agent is authenticated (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
initParams?: Record<string, string>, // CC: portalIds, authType, platform, etc.
context?: Record<string, unknown>, // Optional; merged with initialize({ context })
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. Release notes: changelog.