@egain/ai-agent-sdk

中文文档
0.4.2发布于 2026/11/06MITTypeScriptES Module构建来源已验证近 30 天下载 1973

TypeScript SDK for eGain's AI Agent platform

原始使用文档
文档目录19 节
  1. Features
  2. Installation
  3. Quick Start
  4. Generating An Access Token using PKCE Flow
  5. Sample Code
  6. Contact center (portal flow)
  7. Documentation
  8. Authentication Options
  9. Events
  10. Message Helpers
  11. Node.js Setup
  12. Browser (UMD)
  13. Development
  14. Examples
  15. API Reference
  16. AiAgent Methods
  17. Configuration
  18. License
  19. Support

@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

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
  • 🎭 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.read
  • knowledge.portalmgr.manage
  • core.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).

📚 Full Documentation

GuideDescription
Getting StartedIntroduction and concepts
InstallationSetup instructions
Quick StartFirst integration
AuthenticationAuth strategies
EventsEvent handling
Portal initializationCC portal / agent / profile pipeline
Platform connectorsConnector scripts and HookContract
Message FlowSending/receiving messages
API ReferenceTypeDoc: classes, interfaces, and methods
TypesPortal, 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

MethodDescription
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.

版本与发布记录

@egain/ai-agent-sdk 共发布 30 个版本,首次发布于 2026/05/01;过去 12 个月发布了 30 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.4.2latest2026/11/068 天前
0.4.12026/11/059 天前
0.4.02026/10/3015 天前
0.3.32026/10/2322 天前
0.3.22026/10/1530 天前
0.3.12026/10/101 个月前

其他发布通道:beta → 0.2.5-beta.0。

关于 @egain/ai-agent-sdk 的常见问题

@egain/ai-agent-sdk 是什么?

TypeScript SDK for eGain's AI Agent platform

如何安装 @egain/ai-agent-sdk?

在项目目录运行 npm install @egain/ai-agent-sdk,或使用 pnpm add / yarn add / bun add。

@egain/ai-agent-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@egain/ai-agent-sdk 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@egain/ai-agent-sdk 可以商用吗?

@egain/ai-agent-sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@egain/ai-agent-sdk 的下载量有多少?

根据 npm 官方下载统计,@egain/ai-agent-sdk 在 2026/10/13 – 2026/11/11 这 30 天内被下载 1,973 次,日均约 66 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@egain/ai-agent-sdk 还在维护吗?

最新版本 0.4.2 发布于 2026/11/06(8 天前);至今共发布 30 个版本,其中过去 12 个月发布了 30 个;首次发布于 2026/05/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。