@egain/ai-agent-sdk API Reference
@egain/ai-agent-sdk API Reference - v0.1.1
@egain/ai-agent-sdk
TypeScript-first SDK for eGain's AI Agent platform.
Features
- 🔌 WebSocket-based real-time communication
- 📬 Automatic message queuing when offline
- 🔐 Multiple authentication strategies
- 🎯 Type-safe events with full TypeScript support
- 📝 Built-in transcript management
- 🛡️ Comprehensive error handling
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
});
await agent.initialize();
agent.on("agentMessage", (event) => {
console.log("Agent:", event.payload.message?.content);
});
await agent.send("Hello!");Table of contents
Enumerations
Core Classes
Events Classes
Other Classes
- ApiHelper
- AnonymousAuthStrategy
- AuthenticationService
- ClientCredentialsAuthStrategy
- PKCEAuthStrategy
- PreAuthStrategy
- Connection
- Transport
- WebSocketTransport
- SDKError
- AuthError
- ConnectionError
- MessageError
- Logger
- Message
- MessageProcessor
- AgentMessageHandler
- ChatHistoryHandler
- ErrorMessageHandler
- HeartbeatHandler
- TokenRefreshHandler
Core Interfaces
Other Interfaces
- AgentEventPayloadMap
- AgentEvent
- AgentEvents
- CacheConfig
- ApiHelperConfig
- UserDetails
- GetUserDetailsOptions
- GetCustomerDetailsOptions
- GetAiAgentDetailsOptions
- GetAiAgentSessionOptions
- GetPortalDetailsOptions
- GetConnectedAppsOptions
- GetPreviousTranscriptOptions
- GetMaskingPatternsOptions
- GetMyPortalsOptions
- GetAgentsByPortalOptions
- GetUserProfilesOptions
- SelectUserProfileOptions
- AnonymousAuthCacheConfig
- AnonymousAuthConfig
- AuthProvider
- AuthStrategyInitializeOptions
- AuthStrategy
- AnonymousAuthServiceConfig
- PKCEAuthServiceConfig
- PreAuthServiceConfig
- ClientCredentialsAuthServiceConfig
- ClientCredentialsAuthConfig
- PKCEAuthConfig
- PreAuthConfig
- ConnectionEvents
- ConnectionConfig
- TransportEvents
- TransportConfig
- WebSocketTransportConfig
- LoggerConfig
- LogEntry
- LoggerEvents
- ContextMessageParams
- EscalationMessageParams
- FeedbackMessageParams
- AgentMessageParams
- GracefulDisconnectParams
- MessageObject
- TokenMessageParams
- TokenRefreshHandlerOptions
- MessageData
- MessageHandlerResult
- CallTranscriptEntry
- CallerInfo
- HookContract
- PlatformComponentService
- Portal
- UserProfile
- AgentListItem
Type Aliases
- AgentEventType
- PostAuthenticationCallback
- AuthenticationType
- AuthenticationServiceConfig
- AuthenticationInput
- TokenExpiringCallback
- Persona
- Role
Variables
Functions
- getLevelName
- getLevelValue
- isLevelEnabled
- createContextMessage
- createEscalationMessage
- createFeedbackMessage
- createAgentMessage
- createGracefulDisconnectMessage
- createTokenMessage
Features Caching
Advanced CustomHandlers
Features MessageQueue
Features Transcript
Type Aliases
AgentEventType
Ƭ AgentEventType: "connected" | "message" | "agentMessage" | "errorMessage" | "error" | "closed" | "stateChanged" | "queueFlushed" | "heartbeat" | "tokenExpiring" | "transcriptUpdate" | "callTranscriptUpdate" | "callerInfoUpdate" | "conversationIdUpdate" | "userContextUpdate" | "filterTagsUpdate" | "initialized" | "portalsAvailable" | "agentsAvailable" | "profilesAvailable"
Agent event type identifiers
Defined in
PostAuthenticationCallback
Ƭ PostAuthenticationCallback: (result: any) => void | Promise<void>
Callback function called after authentication is complete This is called after authenticate() completes successfully
Type declaration
▸ (result): void | Promise<void>
Parameters
| Name | Type | Description |
|---|---|---|
result | any | The authentication result (e.g., token, auth data) of any type |
Returns
void | Promise<void>
Defined in
AuthenticationType
Ƭ AuthenticationType: "anonymous" | "pkce" | "pre-auth" | "client-credentials"
Authentication types supported by the service
Defined in
core/auth/AuthenticationService.ts:16
AuthenticationServiceConfig
Ƭ AuthenticationServiceConfig: AnonymousAuthServiceConfig | PKCEAuthServiceConfig | PreAuthServiceConfig | ClientCredentialsAuthServiceConfig
Union type of all authentication service configurations
Defined in
core/auth/AuthenticationService.ts:74
AuthenticationInput
Ƭ AuthenticationInput: AuthenticationServiceConfig | AuthProvider | AuthStrategy | undefined
Input types that AuthenticationService can accept
- AuthenticationServiceConfig: Configuration object for automatic strategy selection
- AuthProvider: Custom auth provider implementing getToken()
- AuthStrategy: Full authentication strategy with lifecycle
- undefined: Falls back to anonymous authentication
Defined in
core/auth/AuthenticationService.ts:87
TokenExpiringCallback
Ƭ TokenExpiringCallback: (expiresAt: number) => void
Callback type for token expiring notification
Type declaration
▸ (expiresAt): void
Parameters
| Name | Type |
|---|---|
expiresAt | number |
Returns
void
Defined in
core/auth/PreAuthStrategy.ts:6
Persona
Ƭ Persona: typeof PERSONA[keyof typeof PERSONA]
Type definitions for persona values
Defined in
Role
Ƭ Role: typeof ROLE[keyof typeof ROLE]
Type definitions for role values
Defined in
Variables
globalLogger
• Const globalLogger: Logger
Global logger instance for application-wide logging Default level: INFO Default console output: enabled
Defined in
core/logging/globalLogger.ts:9
PERSONA
• Const PERSONA: Readonly<{ METADATA: "metadata" = "metadata"; SYSTEM: "system" = "system"; AGENT: "agent" = "agent"; CUSTOMER: "customer" = "customer" }>
Message type constants
Defined in
ROLE
• Const ROLE: Readonly<{ STALE_TOKEN: "stale_token" = "stale_token"; EXPIRED_TOKEN: "expired_token" = "expired_token"; TOKEN: "token" = "token"; CHAT_HISTORY: "chat history" = "chat history"; ERROR: "error" = "error"; HEARTBEAT: "heartbeat" = "heartbeat"; FOLLOW_UP_QUESTION: "follow up question agent" = "follow up question agent"; CUSTOMER_SUPPORT: "customer support agent" = "customer support agent"; CONTEXT: "context" = "context"; GRACEFUL_DISCONNECT: "graceful disconnect" = "graceful disconnect"; ESCALATION: "escalation" = "escalation"; FEEDBACK: "feedback" = "feedback"; HUMAN: "human" = "human" }>
Defined in
ERROR_CODES
• Const ERROR_CODES: Readonly<{ STALE_TOKEN: "401-012" = "401-012"; UNAUTHORIZED_PREFIX: "401" = "401"; FORBIDDEN_PREFIX: "403" = "403" }>
Defined in
Functions
getLevelName
▸ getLevelName(level): string
Get the string name of a log level
Parameters
| Name | Type | Description |
|---|---|---|
level | LogLevel | The log level |
Returns
string
The string name of the level
Defined in
getLevelValue
▸ getLevelValue(level): number
Get the numeric value of a log level
Parameters
| Name | Type | Description |
|---|---|---|
level | LogLevel | The log level |
Returns
number
The numeric value
Defined in
isLevelEnabled
▸ isLevelEnabled(level, threshold): boolean
Check if a log level is enabled based on the current threshold A level is enabled if it is greater than or equal to the threshold
Parameters
| Name | Type | Description |
|---|---|---|
level | LogLevel | The log level to check |
threshold | LogLevel | The minimum log level threshold |
Returns
boolean
True if the level should be logged
Defined in
createContextMessage
▸ createContextMessage(params): MessageObject
Create a context message object
Parameters
| Name | Type | Description |
|---|---|---|
params | ContextMessageParams | Context message parameters |
Returns
Message object compatible with AiAgent.send()
Defined in
core/message/MessageTypes.ts:90
createEscalationMessage
▸ createEscalationMessage(params): MessageObject
Create an escalation event message object
Parameters
| Name | Type | Description |
|---|---|---|
params | EscalationMessageParams | Escalation message parameters |
Returns
Message object compatible with AiAgent.send()
Defined in
core/message/MessageTypes.ts:109
createFeedbackMessage
▸ createFeedbackMessage(params): MessageObject
Create a feedback message object
Parameters
| Name | Type | Description |
|---|---|---|
params | FeedbackMessageParams | Feedback message parameters |
Returns
Message object compatible with AiAgent.send()
Defined in
core/message/MessageTypes.ts:128
createAgentMessage
▸ createAgentMessage(params): MessageObject
Create a normal customer/agent message object
Parameters
| Name | Type | Description |
|---|---|---|
params | AgentMessageParams | Agent message parameters |
Returns
Message object compatible with AiAgent.send()
Defined in
core/message/MessageTypes.ts:149
createGracefulDisconnectMessage
▸ createGracefulDisconnectMessage(params?): MessageObject
Create a graceful disconnect message object
Parameters
| Name | Type | Description |
|---|---|---|
params? | GracefulDisconnectParams | Optional graceful disconnect parameters |
Returns
Message object compatible with AiAgent.send()
Defined in
core/message/MessageTypes.ts:165
createTokenMessage
▸ createTokenMessage(params): MessageObject
Create a token message object for authentication Used to send authentication token to the agent after connection is established
Parameters
| Name | Type | Description |
|---|---|---|
params | TokenMessageParams | Token message parameters |
Returns
Message object compatible with AiAgent.send()
Defined in
core/message/MessageTypes.ts:191
Features Caching
• CacheEntry<T>: Object
Cache entry with timestamp for TTL support.
Example
const entry: CacheEntry<UserData> = {
value: { userId: "123", name: "John" },
timestamp: Date.now()
};Type parameters
| Name |
|---|
T |
Defined in
• CacheAdapter: Object
Cache adapter interface for implementing custom storage backends.
Implement this interface to create custom cache adapters for Redis, IndexedDB, or other storage systems.
Example
class CustomCacheAdapter implements CacheAdapter {
private store = new Map<string, string>();
get<T>(key: string): CacheEntry<T> | null {
const data = this.store.get(key);
return data ? JSON.parse(data) : null;
}
set<T>(key: string, entry: CacheEntry<T>): void {
this.store.set(key, JSON.stringify(entry));
}
delete(key: string): void {
this.store.delete(key);
}
clear(prefix?: string): void {
if (prefix) {
for (const key of this.store.keys()) {
if (key.startsWith(prefix)) this.store.delete(key);
}
} else {
this.store.clear();
}
}
keys(prefix?: string): string[] {
const allKeys = Array.from(this.store.keys());
return prefix ? allKeys.filter(k => k.startsWith(prefix)) : allKeys;
}
}Defined in
• MemoryCacheAdapter: Object
In-memory cache adapter for Node.js environments.
Uses a JavaScript Map for storage. Data persists only for the lifetime of the process. Suitable for server-side applications and testing.
Example
const cache = new MemoryCacheAdapter();
// Store a value
cache.set('user:123', {
value: { name: 'John' },
timestamp: Date.now()
});
// Retrieve the value
const entry = cache.get<{ name: string }>('user:123');
console.log(entry?.value.name); // "John"Defined in
• StorageCacheAdapter: Object
Browser storage cache adapter using localStorage or sessionStorage.
Automatically serializes values to JSON for storage. Falls back gracefully if storage is unavailable or full.
Example
// Use sessionStorage (cleared when tab closes)
const sessionCache = new StorageCacheAdapter('session');
// Use localStorage (persistent)
const localCache = new StorageCacheAdapter('local');
// Store data
sessionCache.set('config', {
value: { theme: 'dark' },
timestamp: Date.now()
});Defined in
CacheStorageType
Ƭ CacheStorageType: "local" | "session" | "memory"
Cache storage type options.
local: Browser localStorage (persistent across sessions)session: Browser sessionStorage (cleared when tab closes)memory: In-memory storage (cleared when process ends)
Defined in
createCacheAdapter
▸ createCacheAdapter(storageType?): CacheAdapter
Factory function to create the appropriate cache adapter based on environment.
Automatically detects the environment and creates the best available adapter:
- In browsers: Creates StorageCacheAdapter (with fallback to memory if storage unavailable)
- In Node.js: Creates MemoryCacheAdapter
Parameters
| Name | Type | Default value | Description |
|---|---|---|---|
storageType | CacheStorageType | 'session' | The preferred storage type |
Returns
The appropriate cache adapter for the environment
Example
// Auto-detect best adapter
const cache = createCacheAdapter();
// Force memory adapter
const memoryCache = createCacheAdapter('memory');
// Use localStorage in browser
const persistentCache = createCacheAdapter('local');