Skip to content

@egain/ai-agent-sdk API Reference - v0.3.2 / AiAgent

Class: AiAgent ​

Type-safe event emitter implementation.

Compatible with both browser and Node.js environments. Provides a foundation for event-driven communication throughout the SDK.

Example

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

interface MyEvents {
  data: { value: number };
  error: { message: string };
}

class MyService extends EventEmitter<MyEvents> {
  doSomething() {
    this.emit("data", { value: 42 });
  }
}

const service = new MyService();
service.on("data", (event) => {
  console.log(event.value); // Typed as number
});

Hierarchy ​

Table of contents ​

Constructors ​

Properties ​

Methods ​

Constructors ​

constructor ​

• new AiAgent(config): AiAgent

Parameters ​

NameType
configAiAgentConfig

Returns ​

AiAgent

Overrides ​

EventEmitter.constructor

Defined in ​

core/AiAgent.ts:600

Properties ​

logger ​

• logger: Logger

Defined in ​

core/AiAgent.ts:568

Methods ​

initialize ​

▸ initialize(options?): Promise<void>

Initialize the agent. Must be called after construction and awaited before use.

Authenticates (falls back to AnonymousAuthStrategy if no auth is configured), then:

  • Direct flow: fetches session, creates the WebSocket connection, emits initialized. With autoConnect, opens the WebSocket automatically.
  • Contact Center flow: runs portal / agent / profile selection over REST only (no WebSocket yet). May emit portalsAvailable, agentsAvailable, or profilesAvailable — call the corresponding select* method. Then emits initialized. Call AiAgent.connect afterward (or rely on autoConnect after the pipeline completes).

Parameters ​

NameType
options?AiAgentInitializeOptions

Returns ​

Promise<void>

Example

typescript
const agent = new AiAgent({ id: 'agent-id', endpoint: 'https://...' });
await agent.initialize({ context: { egain_portal_id: { value: '123' } } });
// Direct flow: often already connected if autoConnect. CC flow: connect after `initialized`.
await agent.connect();

Defined in ​

core/AiAgent.ts:795


maskContent ​

▸ maskContent(text): string

Mask sensitive text using loaded department patterns (cc-widget maskData parity). No-op when masking is inactive (see agentDetails.enableDataMasking and platform gates).

Parameters ​

NameType
textstring

Returns ​

string

Defined in ​

core/AiAgent.ts:1274


getAgentDetails ​

▸ getAgentDetails(): Promise<any>

Get the agent details Returns cached agent details if available, otherwise fetches from network. If called before initialize(), performs minimal initialization to fetch agent details only (gets deployment info, fetches anonymous token, fetches agent details - without getting session ID or creating connection).

Returns ​

Promise<any>

Promise resolving to the agent details

Defined in ​

core/AiAgent.ts:1367


getDeploymentInfo ​

▸ getDeploymentInfo(): Promise<any>

Get the deployment information Returns cached deployment info if available, otherwise fetches from network. Does not require initialization - only needs the endpoint URL.

Returns ​

Promise<any>

Promise resolving to the deployment information

Defined in ​

core/AiAgent.ts:1416


getIsInitialized ​

▸ getIsInitialized(): boolean

Whether the agent has completed initialization. Becomes true after the init pipeline completes (e.g. after the initialized event).

Returns ​

boolean

true if initialized, false otherwise

Example

typescript
if (agent.getIsInitialized()) {
  await agent.connect();
} else {
  agent.once('initialized', () => agent.connect());
}

Defined in ​

core/AiAgent.ts:1623


getState ​

▸ getState(): ConnectionState

Get current connection state.

Returns ​

ConnectionState

The current connection state

Throws

Error if agent is not initialized

Example

typescript
const state = agent.getState();
if (state === ConnectionState.CONNECTED) {
  console.log("Ready to send messages");
}

See

ConnectionState for available states

Defined in ​

core/AiAgent.ts:1643


isConnected ​

▸ isConnected(): boolean

Check if the agent is currently connected.

Returns ​

boolean

true if connected, false otherwise

Example

typescript
if (agent.isConnected()) {
  await agent.send("Hello!");
} else {
  console.log("Waiting for connection...");
}

Defined in ​

core/AiAgent.ts:1666


connect ​

▸ connect(): Promise<void>

Connect to the agent endpoint.

Establishes a WebSocket connection to the AI Agent server. Must call initialize first.

For Contact Center agents, the connection object is created lazily on this call (session fetch uses the resolved agent ID, including Flow B after agent selection).

Returns ​

Promise<void>

Throws

Error if agent is not initialized

Example

typescript
await agent.initialize();
await agent.connect();
console.log("Connected!");

Defined in ​

core/AiAgent.ts:1687


disconnect ​

▸ disconnect(options?): Promise<void>

Disconnect from the agent endpoint.

By default, sends a graceful disconnect message before closing the connection. Use skipGracefulDisconnect: true for immediate disconnection.

Parameters ​

NameTypeDescription
options?ObjectDisconnect options
options.skipGracefulDisconnect?booleanIf true, skip sending graceful disconnect message

Returns ​

Promise<void>

Example

typescript
await agent.disconnect();

Example

typescript
await agent.disconnect({ skipGracefulDisconnect: true });

Defined in ​

core/AiAgent.ts:1745


selectPortal ​

▸ selectPortal(portal): Promise<void>

Select a portal (CC flow). Call when portalsAvailable event is emitted and user has chosen.

Parameters ​

NameTypeDescription
portalPortalThe selected portal

Returns ​

Promise<void>

Throws

Error if portal initializer is not active

Throws

InitializationPipelineError when the portal step fails

Example

typescript
agent.on('portalsAvailable', async (e) => {
  const portal = showPortalPicker(e.payload.portals);
  await agent.selectPortal(portal);
});

Defined in ​

core/AiAgent.ts:1789


selectAgent ​

▸ selectAgent(agent): Promise<void>

Select an agent (Flow B only — initParams.isDefaultAgent === "true"). Call when agentsAvailable is emitted and the user has chosen.

Parameters ​

NameTypeDescription
agentAgentListItemThe selected agent

Returns ​

Promise<void>

Throws

Error if portal initializer is not active

Throws

InitializationPipelineError when the agent step fails

Example

typescript
agent.on('agentsAvailable', async (e) => {
  const selected = showAgentPicker(e.payload.agents);
  await agent.selectAgent(selected);
});

Defined in ​

core/AiAgent.ts:1813


selectUserProfile ​

▸ selectUserProfile(profile): Promise<void>

Select a user profile (CC flow). Call when profilesAvailable event is emitted and user has chosen.

Parameters ​

NameTypeDescription
profileUserProfileThe selected profile

Returns ​

Promise<void>

Throws

Error if portal initializer is not active

Throws

InitializationPipelineError when the profile step fails

Example

typescript
agent.on('profilesAvailable', async (e) => {
  const profile = showProfilePicker(e.payload.profiles);
  await agent.selectUserProfile(profile);
});

Defined in ​

core/AiAgent.ts:1836


getInitParams ​

▸ getInitParams(): Record<string, string>

Get the stored initialization parameters from config.

Returns ​

Record<string, string>

The init params object (empty object if none provided)

Example

typescript
const initParams = agent.getInitParams();
const userId = initParams.userid;

Defined in ​

core/AiAgent.ts:1854


restartPortalInitializer ​

▸ restartPortalInitializer(): Promise<void>

Restart the CC widget initialization pipeline from scratch.

This method tears down the current initialization state and re-runs the full pipeline (portal selection → agent selection → profile selection), allowing the consumer to make new selections. After completion, the initialized event fires again and the consumer should call connect().

What it does:

  1. Checks completedPortalPipeline: if false (non-CC agent), delegates to restartConnection() and returns
  2. Destroys the current PortalInitializer instance (rejects any pending gating promises)
  3. Disconnects the current WebSocket connection (if any) and clears session, queue, transcript
  4. Resets resolvedAgentId to config.id and isInitialized to false
  5. Re-obtains an auth token and calls onAuthComplete to restart the pipeline (or direct flow)

Important: For agents that completed the CC initialization pipeline (portal → agent → profile selection), this re-runs the full pipeline. For agents that did not complete it (e.g. direct flow from the start, or contact-center agents that fell back to direct flow because they have no portals), this method delegates to restartConnection() so the consumer can call it for any restart without branching. The consumer must re-register or still have active event listeners for portalsAvailable, agentsAvailable, profilesAvailable, and initialized before calling this method (CC pipeline path only).

Returns ​

Promise<void>

Throws

Error if authentication token cannot be obtained (CC path) or for restart (direct path)

Example

typescript
// User wants to switch portals — restart the pipeline
agent.on('portalsAvailable', (e) => {
  showPortalPicker(e.payload.portals, (p) => agent.selectPortal(p));
});

agent.on('initialized', async () => {
  await agent.connect();
});

await agent.restartPortalInitializer();

Defined in ​

core/AiAgent.ts:1899


restartCcWidgetInitializer ​

▸ restartCcWidgetInitializer(): Promise<void>

Returns ​

Promise<void>

Deprecated

Use restartPortalInitializer instead.

Defined in ​

core/AiAgent.ts:1938


updateUserProfile ​

▸ updateUserProfile(profile): Promise<void>

Update the active user profile after initialization.

Use this when the consumer wants to switch profiles without re-running the full portal/agent selection pipeline. This method:

  1. Persists the new profile selection via the selectUserProfile API (if the profile is not already the last-used profile)
  2. Disconnects the current WebSocket connection (if any)
  3. Clears the message queue and transcript
  4. Fetches a new session ID and reconnects
  5. Emits initialized with the updated profile in the payload

This is the equivalent of the cc-widget's profile dropdown behavior: change the profile → restart session → re-send user context.

Important: This method is only valid after the CC initialization pipeline has completed. Calling it on a non-CC agent or before initialization throws an error.

Parameters ​

NameTypeDescription
profileUserProfileThe new user profile to activate

Returns ​

Promise<void>

Throws

Error if agent is not initialized

Throws

Error if agent did not go through the CC initialization flow

Throws

Error if no portal is currently selected

Example

typescript
// User picks a different profile from a dropdown
const profiles = cachedProfiles; // from the profilesAvailable event
agent.on("initialized", async () => {
  await agent.connect();
});
await agent.updateUserProfile(profiles[2]);

Defined in ​

core/AiAgent.ts:1976


restartConnection ​

▸ restartConnection(options?): Promise<void>

Restart the connection with a fresh session.

This method:

  1. Gracefully disconnects from the current session
  2. Clears all queued messages and transcript
  3. Obtains a new session ID (or uses provided one)
  4. Reconnects to the new session
  5. Persists stored context while creating the new session

Note: All queued messages will be lost during restart.

Parameters ​

NameTypeDescription
options?ObjectOptional restart options
options.sessionId?string | numberOptional session ID to use for restart. If provided, skips fetching from network.

Returns ​

Promise<void>

Throws

Error if agent is not initialized

Example

typescript
// Start a fresh conversation (fetches new sessionId)
await agent.restartConnection();

// Restart with a specific sessionId
await agent.restartConnection({ sessionId: 'existing-session-id' });

// Context is automatically restored
await agent.send("Hello again!");

Defined in ​

core/AiAgent.ts:2053


send ​

▸ send(data, options?): Promise<string>

Send a message to the agent Messages are queued if offline and automatically sent when connected Context messages are automatically stored in cache for use on reconnection

Parameters ​

NameTypeDescription
dataanyMessage data (can be a Message instance, plain object, or string)
options?ObjectOptional message options
options.id?stringOptional message ID
options.from?stringOptional sender identifier (agent ID, customer ID, etc.)
options.to?stringOptional recipient identifier (agent ID, etc.)

Returns ​

Promise<string>

Message ID

Defined in ​

core/AiAgent.ts:2205


getQueueSize ​

▸ getQueueSize(): number

Get the current queue size

Returns ​

number

Defined in ​

core/AiAgent.ts:2284


clearQueue ​

▸ clearQueue(): void

Clear the message queue

Returns ​

void

Defined in ​

core/AiAgent.ts:2291


getTranscript ​

▸ getTranscript(options?): TranscriptEntry[]

Get transcript entries

Parameters ​

NameTypeDescription
options?TranscriptOptionsOptional filtering options

Returns ​

TranscriptEntry[]

Array of transcript entries with Message objects

Defined in ​

core/AiAgent.ts:2300


getTranscriptAsJSON ​

▸ getTranscriptAsJSON(options?): any[]

Get transcript entries as plain objects (JSON-serializable)

Parameters ​

NameTypeDescription
options?TranscriptOptionsOptional filtering options

Returns ​

any[]

Array of plain objects representing transcript entries

Defined in ​

core/AiAgent.ts:2309


getTranscriptSize ​

▸ getTranscriptSize(): number

Get the number of entries in the transcript

Returns ​

number

Number of transcript entries

Defined in ​

core/AiAgent.ts:2317


clearTranscript ​

▸ clearTranscript(): void

Clear all transcript entries

Returns ​

void

Defined in ​

core/AiAgent.ts:2324


getCallTranscript ​

▸ getCallTranscript(): CallTranscriptEntry[]

Get the call transcript — the live customer-agent conversation from the telephony platform (Genesys, Amazon Connect, etc.), pushed by the platform connector via the HookContract.

This is distinct from getTranscript, which returns the AI Agent chat transcript (WebSocket messages).

Returns ​

CallTranscriptEntry[]

A shallow copy of the call transcript entries

Defined in ​

core/AiAgent.ts:2338


getCallerInfo ​

▸ getCallerInfo(): null | CallerInfo

Get the caller information set by the platform connector via HookContract.setCallerInfo(). Available after the platform connector has initialized (typically before the initialized event fires).

Returns ​

null | CallerInfo

The caller info object, or null if not yet set

Defined in ​

core/AiAgent.ts:2349


getUserDetails ​

▸ getUserDetails(): null | UserDetails

Returns the authenticated user's or customer's details fetched after authentication. Only fetched when agentDetails.isAuthenticated is true (otherwise remains null). Available after the initialized event fires. Returns null if details were not fetched or could not be fetched.

Returns ​

null | UserDetails

Defined in ​

core/AiAgent.ts:2359


getConversationId ​

▸ getConversationId(): null | string

Returns ​

null | string

Defined in ​

core/AiAgent.ts:2363


clearCallTranscript ​

▸ clearCallTranscript(): void

Clear all call transcript entries.

Returns ​

void

Defined in ​

core/AiAgent.ts:2370


getContext ​

▸ getContext(): null | object

Get the stored context for this agent Returns the context object that was previously sent via a context message

Returns ​

null | object

The stored context object or null if no context is stored

Defined in ​

core/AiAgent.ts:2449


removeContext ​

▸ removeContext(): void

Remove the stored context for this agent Clears any previously stored context from the cache

Returns ​

void

Defined in ​

core/AiAgent.ts:2462


setContext ​

▸ setContext(context, options?): Promise<void>

Set context for this agent Merges the context into the cache and optionally sends only changed values to the agent immediately

Parameters ​

NameTypeDescription
contextobjectThe context object to set
options?ObjectOptional settings
options.sendImmediately?booleanIf true, sends the context to the agent right away (default: false)

Returns ​

Promise<void>

Promise that resolves when context is set (and sent if sendImmediately is true)

Example

typescript
agent.setContext({ userId: "123", plan: "premium" });

Example

typescript
await agent.setContext({ userId: "123", plan: "premium" }, { sendImmediately: true });

Defined in ​

core/AiAgent.ts:2486


resetContext ​

▸ resetContext(): void

Reset (clear) the context for this agent Removes any stored context from the cache This is an alias for removeContext() with additional logging

Returns ​

void

Example

typescript
agent.resetContext();

Defined in ​

core/AiAgent.ts:2509


getMessageProcessor ​

▸ getMessageProcessor(): MessageProcessor

Get the message processor instance Allows adding custom handlers

Returns ​

MessageProcessor

Defined in ​

core/AiAgent.ts:2876


getAccessToken ​

▸ getAccessToken(): Promise<null | string>

Get the current access token from the authentication strategy Returns the access token that the agent is currently using for authentication

Returns ​

Promise<null | string>

Promise resolving to the access token string, or null if no token is available

Example

typescript
const token = await agent.getAccessToken();
if (token) {
  // Use the token for external API calls
  fetch('https://api.example.com/data', {
    headers: { Authorization: `Bearer ${token}` }
  });
}

Defined in ​

core/AiAgent.ts:2896


logout ​

▸ logout(): Promise<void>

Log out of the identity provider.

Disconnects chat (errors ignored), then delegates to AuthenticationService.logout. PKCE matches login authScheme (logoutPopup / logoutRedirect). Takes no options — post-logout URI, idTokenHint, and redirect state are built inside PKCE. Strategies without logout() (anonymous, pre-auth) no-op after the disconnect.

Returns ​

Promise<void>

Example

typescript
await agent.logout();

Defined in ​

core/AiAgent.ts:2926


updateAccessToken ​

▸ updateAccessToken(token): Promise<void>

Update the access token at runtime Use this method when you receive a tokenExpiring event to provide a new token

Parameters ​

NameTypeDescription
tokenstringThe new access token

Returns ​

Promise<void>

Throws

Error if the authentication strategy doesn't support token updates

Example

typescript
agent.on('tokenExpiring', async (event) => {
  const newToken = await fetchNewTokenFromServer();
  await agent.updateAccessToken(newToken);
});

Defined in ​

core/AiAgent.ts:2945


setSessionId ​

▸ setSessionId(sessionId): void

Set or update the session ID at runtime Updates the sessionId property, which will be used for future connections and logging.

Note: If the agent is currently connected, changing the sessionId will not automatically switch the connection to the new session. You should either:

  • Disconnect and reconnect with the new sessionId
  • Use restartConnection({ sessionId: newSessionId }) to restart with the new session

Parameters ​

NameTypeDescription
sessionIdstring | numberThe new session ID to set

Returns ​

void

Example

typescript
// Update sessionId after initialization
agent.setSessionId('new-session-id');

// If connected, restart with the new sessionId
if (agent.isConnected()) {
  await agent.restartConnection({ sessionId: 'new-session-id' });
}

Defined in ​

core/AiAgent.ts:2973


on ​

▸ on<K>(event, handler): this

Register an event handler.

The handler will be called every time the event is emitted.

Type parameters ​

NameType
Kextends keyof AgentEvents

Parameters ​

NameTypeDescription
eventKThe event name to listen for
handlerEventHandler<AgentEvents[K]>The function to call when the event is emitted

Returns ​

this

this for method chaining

Example

typescript
agent.on("message", (event) => {
  console.log("Received:", event.payload);
});

Inherited from ​

EventEmitter.on

Defined in ​

core/events/EventEmitter.ts:64


once ​

▸ once<K>(event, handler): this

Register a one-time event handler.

The handler will be called only once, then automatically removed.

Type parameters ​

NameType
Kextends keyof AgentEvents

Parameters ​

NameTypeDescription
eventKThe event name to listen for
handlerEventHandler<AgentEvents[K]>The function to call when the event is emitted

Returns ​

this

this for method chaining

Example

typescript
agent.once("connected", () => {
  console.log("First connection established!");
});

Inherited from ​

EventEmitter.once

Defined in ​

core/events/EventEmitter.ts:88


off ​

▸ off<K>(event, handler?): this

Remove an event handler.

If no handler is specified, removes all handlers for the event.

Type parameters ​

NameType
Kextends keyof AgentEvents

Parameters ​

NameTypeDescription
eventKThe event name
handler?EventHandler<AgentEvents[K]>The specific handler to remove (optional)

Returns ​

this

this for method chaining

Example

typescript
const handler = (event) => console.log(event);
agent.on("message", handler);
agent.off("message", handler);

Example

typescript
agent.off("message");

Inherited from ​

EventEmitter.off

Defined in ​

core/events/EventEmitter.ts:117


removeAllListeners ​

▸ removeAllListeners<K>(event?): this

Remove all event handlers

Type parameters ​

NameType
Kextends keyof AgentEvents

Parameters ​

NameType
event?K

Returns ​

this

Inherited from ​

EventEmitter.removeAllListeners

Defined in ​

core/events/EventEmitter.ts:180


listenerCount ​

▸ listenerCount<K>(event): number

Get the number of listeners for an event

Type parameters ​

NameType
Kextends keyof AgentEvents

Parameters ​

NameType
eventK

Returns ​

number

Inherited from ​

EventEmitter.listenerCount

Defined in ​

core/events/EventEmitter.ts:194

Released under the MIT License.