Skip to content

@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

typescript
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

Core Interfaces

Other Interfaces

Type Aliases

Variables

Functions

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

core/AiAgent.ts:212


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
NameTypeDescription
resultanyThe authentication result (e.g., token, auth data) of any type
Returns

void | Promise<void>

Defined in

core/auth/AuthStrategy.ts:8


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
NameType
expiresAtnumber
Returns

void

Defined in

core/auth/PreAuthStrategy.ts:6


Persona

Ƭ Persona: typeof PERSONA[keyof typeof PERSONA]

Type definitions for persona values

Defined in

core/message/types.ts:36


Role

Ƭ Role: typeof ROLE[keyof typeof ROLE]

Type definitions for role values

Defined in

core/message/types.ts:41

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

core/message/types.ts:4


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

core/message/types.ts:11


ERROR_CODES

Const ERROR_CODES: Readonly<{ STALE_TOKEN: "401-012" = "401-012"; UNAUTHORIZED_PREFIX: "401" = "401"; FORBIDDEN_PREFIX: "403" = "403" }>

Defined in

core/message/types.ts:27

Functions

getLevelName

getLevelName(level): string

Get the string name of a log level

Parameters

NameTypeDescription
levelLogLevelThe log level

Returns

string

The string name of the level

Defined in

core/logging/LogLevel.ts:19


getLevelValue

getLevelValue(level): number

Get the numeric value of a log level

Parameters

NameTypeDescription
levelLogLevelThe log level

Returns

number

The numeric value

Defined in

core/logging/LogLevel.ts:28


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

NameTypeDescription
levelLogLevelThe log level to check
thresholdLogLevelThe minimum log level threshold

Returns

boolean

True if the level should be logged

Defined in

core/logging/LogLevel.ts:39


createContextMessage

createContextMessage(params): MessageObject

Create a context message object

Parameters

NameTypeDescription
paramsContextMessageParamsContext message parameters

Returns

MessageObject

Message object compatible with AiAgent.send()

Defined in

core/message/MessageTypes.ts:90


createEscalationMessage

createEscalationMessage(params): MessageObject

Create an escalation event message object

Parameters

NameTypeDescription
paramsEscalationMessageParamsEscalation message parameters

Returns

MessageObject

Message object compatible with AiAgent.send()

Defined in

core/message/MessageTypes.ts:109


createFeedbackMessage

createFeedbackMessage(params): MessageObject

Create a feedback message object

Parameters

NameTypeDescription
paramsFeedbackMessageParamsFeedback message parameters

Returns

MessageObject

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

NameTypeDescription
paramsAgentMessageParamsAgent message parameters

Returns

MessageObject

Message object compatible with AiAgent.send()

Defined in

core/message/MessageTypes.ts:149


createGracefulDisconnectMessage

createGracefulDisconnectMessage(params?): MessageObject

Create a graceful disconnect message object

Parameters

NameTypeDescription
params?GracefulDisconnectParamsOptional graceful disconnect parameters

Returns

MessageObject

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

NameTypeDescription
paramsTokenMessageParamsToken message parameters

Returns

MessageObject

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

typescript
const entry: CacheEntry<UserData> = {
  value: { userId: "123", name: "John" },
  timestamp: Date.now()
};

Type parameters

Name
T

Defined in

core/api/CacheAdapter.ts:109

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

typescript
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

core/api/CacheAdapter.ts:160

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

typescript
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

core/api/CacheAdapter.ts:219

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

typescript
// 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

core/api/CacheAdapter.ts:283

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

core/api/CacheAdapter.ts:367


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

NameTypeDefault valueDescription
storageTypeCacheStorageType'session'The preferred storage type

Returns

CacheAdapter

The appropriate cache adapter for the environment

Example

typescript
// Auto-detect best adapter
const cache = createCacheAdapter();

// Force memory adapter
const memoryCache = createCacheAdapter('memory');

// Use localStorage in browser
const persistentCache = createCacheAdapter('local');

Defined in

core/api/CacheAdapter.ts:394

Released under the MIT License.