@egain/ai-agent-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +295 -0
- package/dist/browser.js +22739 -0
- package/dist/core/AiAgent.d.ts +1126 -0
- package/dist/core/AiAgent.d.ts.map +1 -0
- package/dist/core/AiAgent.js +2037 -0
- package/dist/core/AiAgent.js.map +1 -0
- package/dist/core/api/ApiHelper.d.ts +433 -0
- package/dist/core/api/ApiHelper.d.ts.map +1 -0
- package/dist/core/api/ApiHelper.js +689 -0
- package/dist/core/api/ApiHelper.js.map +1 -0
- package/dist/core/api/CacheAdapter.d.ts +295 -0
- package/dist/core/api/CacheAdapter.d.ts.map +1 -0
- package/dist/core/api/CacheAdapter.js +298 -0
- package/dist/core/api/CacheAdapter.js.map +1 -0
- package/dist/core/auth/AnonymousAuthStrategy.d.ts +87 -0
- package/dist/core/auth/AnonymousAuthStrategy.d.ts.map +1 -0
- package/dist/core/auth/AnonymousAuthStrategy.js +257 -0
- package/dist/core/auth/AnonymousAuthStrategy.js.map +1 -0
- package/dist/core/auth/AuthProvider.d.ts +13 -0
- package/dist/core/auth/AuthProvider.d.ts.map +1 -0
- package/dist/core/auth/AuthProvider.js +2 -0
- package/dist/core/auth/AuthProvider.js.map +1 -0
- package/dist/core/auth/AuthStrategy.d.ts +74 -0
- package/dist/core/auth/AuthStrategy.d.ts.map +1 -0
- package/dist/core/auth/AuthStrategy.js +2 -0
- package/dist/core/auth/AuthStrategy.js.map +1 -0
- package/dist/core/auth/AuthenticationService.d.ts +226 -0
- package/dist/core/auth/AuthenticationService.d.ts.map +1 -0
- package/dist/core/auth/AuthenticationService.js +344 -0
- package/dist/core/auth/AuthenticationService.js.map +1 -0
- package/dist/core/auth/ClientCredentialsAuthStrategy.d.ts +62 -0
- package/dist/core/auth/ClientCredentialsAuthStrategy.d.ts.map +1 -0
- package/dist/core/auth/ClientCredentialsAuthStrategy.js +78 -0
- package/dist/core/auth/ClientCredentialsAuthStrategy.js.map +1 -0
- package/dist/core/auth/PKCEAuthStrategy.d.ts +136 -0
- package/dist/core/auth/PKCEAuthStrategy.d.ts.map +1 -0
- package/dist/core/auth/PKCEAuthStrategy.js +409 -0
- package/dist/core/auth/PKCEAuthStrategy.js.map +1 -0
- package/dist/core/auth/PreAuthStrategy.d.ts +101 -0
- package/dist/core/auth/PreAuthStrategy.d.ts.map +1 -0
- package/dist/core/auth/PreAuthStrategy.js +216 -0
- package/dist/core/auth/PreAuthStrategy.js.map +1 -0
- package/dist/core/auth/msal-browser.js +19683 -0
- package/dist/core/auth/msal-loader.d.ts +14 -0
- package/dist/core/auth/msal-loader.d.ts.map +1 -0
- package/dist/core/auth/msal-loader.js +43 -0
- package/dist/core/auth/msal-loader.js.map +1 -0
- package/dist/core/connection/Connection.d.ts +168 -0
- package/dist/core/connection/Connection.d.ts.map +1 -0
- package/dist/core/connection/Connection.js +290 -0
- package/dist/core/connection/Connection.js.map +1 -0
- package/dist/core/connection/ConnectionState.d.ts +11 -0
- package/dist/core/connection/ConnectionState.d.ts.map +1 -0
- package/dist/core/connection/ConnectionState.js +12 -0
- package/dist/core/connection/ConnectionState.js.map +1 -0
- package/dist/core/connection/Transport.d.ts +98 -0
- package/dist/core/connection/Transport.d.ts.map +1 -0
- package/dist/core/connection/Transport.js +27 -0
- package/dist/core/connection/Transport.js.map +1 -0
- package/dist/core/connection/WebSocketTransport.d.ts +65 -0
- package/dist/core/connection/WebSocketTransport.d.ts.map +1 -0
- package/dist/core/connection/WebSocketTransport.js +177 -0
- package/dist/core/connection/WebSocketTransport.js.map +1 -0
- package/dist/core/errors/SDKError.d.ts +27 -0
- package/dist/core/errors/SDKError.d.ts.map +1 -0
- package/dist/core/errors/SDKError.js +43 -0
- package/dist/core/errors/SDKError.js.map +1 -0
- package/dist/core/events/EventEmitter.d.ts +120 -0
- package/dist/core/events/EventEmitter.d.ts.map +1 -0
- package/dist/core/events/EventEmitter.js +183 -0
- package/dist/core/events/EventEmitter.js.map +1 -0
- package/dist/core/logging/LogLevel.d.ts +33 -0
- package/dist/core/logging/LogLevel.d.ts.map +1 -0
- package/dist/core/logging/LogLevel.js +40 -0
- package/dist/core/logging/LogLevel.js.map +1 -0
- package/dist/core/logging/Logger.d.ts +120 -0
- package/dist/core/logging/Logger.d.ts.map +1 -0
- package/dist/core/logging/Logger.js +204 -0
- package/dist/core/logging/Logger.js.map +1 -0
- package/dist/core/logging/globalLogger.d.ts +8 -0
- package/dist/core/logging/globalLogger.d.ts.map +1 -0
- package/dist/core/logging/globalLogger.js +12 -0
- package/dist/core/logging/globalLogger.js.map +1 -0
- package/dist/core/logging/types.d.ts +45 -0
- package/dist/core/logging/types.d.ts.map +1 -0
- package/dist/core/logging/types.js +2 -0
- package/dist/core/logging/types.js.map +1 -0
- package/dist/core/message/BaseMessageHandler.d.ts +208 -0
- package/dist/core/message/BaseMessageHandler.d.ts.map +1 -0
- package/dist/core/message/BaseMessageHandler.js +155 -0
- package/dist/core/message/BaseMessageHandler.js.map +1 -0
- package/dist/core/message/Message.d.ts +69 -0
- package/dist/core/message/Message.d.ts.map +1 -0
- package/dist/core/message/Message.js +131 -0
- package/dist/core/message/Message.js.map +1 -0
- package/dist/core/message/MessageProcessor.d.ts +51 -0
- package/dist/core/message/MessageProcessor.d.ts.map +1 -0
- package/dist/core/message/MessageProcessor.js +123 -0
- package/dist/core/message/MessageProcessor.js.map +1 -0
- package/dist/core/message/MessageTypes.d.ts +123 -0
- package/dist/core/message/MessageTypes.d.ts.map +1 -0
- package/dist/core/message/MessageTypes.js +106 -0
- package/dist/core/message/MessageTypes.js.map +1 -0
- package/dist/core/message/Transcript.d.ts +373 -0
- package/dist/core/message/Transcript.d.ts.map +1 -0
- package/dist/core/message/Transcript.js +355 -0
- package/dist/core/message/Transcript.js.map +1 -0
- package/dist/core/message/handlers/AgentMessageHandler.d.ts +26 -0
- package/dist/core/message/handlers/AgentMessageHandler.d.ts.map +1 -0
- package/dist/core/message/handlers/AgentMessageHandler.js +130 -0
- package/dist/core/message/handlers/AgentMessageHandler.js.map +1 -0
- package/dist/core/message/handlers/ChatHistoryHandler.d.ts +12 -0
- package/dist/core/message/handlers/ChatHistoryHandler.d.ts.map +1 -0
- package/dist/core/message/handlers/ChatHistoryHandler.js +49 -0
- package/dist/core/message/handlers/ChatHistoryHandler.js.map +1 -0
- package/dist/core/message/handlers/ErrorMessageHandler.d.ts +12 -0
- package/dist/core/message/handlers/ErrorMessageHandler.d.ts.map +1 -0
- package/dist/core/message/handlers/ErrorMessageHandler.js +49 -0
- package/dist/core/message/handlers/ErrorMessageHandler.js.map +1 -0
- package/dist/core/message/handlers/HeartbeatHandler.d.ts +12 -0
- package/dist/core/message/handlers/HeartbeatHandler.d.ts.map +1 -0
- package/dist/core/message/handlers/HeartbeatHandler.js +46 -0
- package/dist/core/message/handlers/HeartbeatHandler.js.map +1 -0
- package/dist/core/message/handlers/TokenRefreshHandler.d.ts +30 -0
- package/dist/core/message/handlers/TokenRefreshHandler.d.ts.map +1 -0
- package/dist/core/message/handlers/TokenRefreshHandler.js +84 -0
- package/dist/core/message/handlers/TokenRefreshHandler.js.map +1 -0
- package/dist/core/message/types.d.ts +107 -0
- package/dist/core/message/types.d.ts.map +1 -0
- package/dist/core/message/types.js +30 -0
- package/dist/core/message/types.js.map +1 -0
- package/dist/core/platform/HookContract.d.ts +112 -0
- package/dist/core/platform/HookContract.d.ts.map +1 -0
- package/dist/core/platform/HookContract.js +13 -0
- package/dist/core/platform/HookContract.js.map +1 -0
- package/dist/core/platform/PlatformComponentService.d.ts +40 -0
- package/dist/core/platform/PlatformComponentService.d.ts.map +1 -0
- package/dist/core/platform/PlatformComponentService.js +12 -0
- package/dist/core/platform/PlatformComponentService.js.map +1 -0
- package/dist/core/platform/PlatformScriptLoader.d.ts +41 -0
- package/dist/core/platform/PlatformScriptLoader.d.ts.map +1 -0
- package/dist/core/platform/PlatformScriptLoader.js +110 -0
- package/dist/core/platform/PlatformScriptLoader.js.map +1 -0
- package/dist/core/polyfills.d.ts +16 -0
- package/dist/core/polyfills.d.ts.map +1 -0
- package/dist/core/polyfills.js +168 -0
- package/dist/core/polyfills.js.map +1 -0
- package/dist/core/portal-initializer/PortalInitializer.d.ts +234 -0
- package/dist/core/portal-initializer/PortalInitializer.d.ts.map +1 -0
- package/dist/core/portal-initializer/PortalInitializer.js +636 -0
- package/dist/core/portal-initializer/PortalInitializer.js.map +1 -0
- package/dist/core/queue/MessageQueue.d.ts +277 -0
- package/dist/core/queue/MessageQueue.d.ts.map +1 -0
- package/dist/core/queue/MessageQueue.js +291 -0
- package/dist/core/queue/MessageQueue.js.map +1 -0
- package/dist/core/types/PortalTypes.d.ts +51 -0
- package/dist/core/types/PortalTypes.d.ts.map +1 -0
- package/dist/core/types/PortalTypes.js +8 -0
- package/dist/core/types/PortalTypes.js.map +1 -0
- package/dist/index.d.ts +91 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +82 -0
- package/dist/index.js.map +1 -0
- package/package.json +84 -0
|
@@ -0,0 +1,1126 @@
|
|
|
1
|
+
import { ConnectionState } from './connection/ConnectionState.js';
|
|
2
|
+
import { AuthenticationInput } from './auth/AuthenticationService.js';
|
|
3
|
+
import { EventEmitter } from './events/EventEmitter.js';
|
|
4
|
+
import { CacheConfig, type UserDetails } from './api/ApiHelper.js';
|
|
5
|
+
import { MessageProcessor } from './message/MessageProcessor.js';
|
|
6
|
+
import { Message } from './message/Message.js';
|
|
7
|
+
import { MessageHandlerResult } from './message/types.js';
|
|
8
|
+
import { Logger } from './logging/Logger.js';
|
|
9
|
+
import { LogLevel } from './logging/LogLevel.js';
|
|
10
|
+
import { TranscriptConfig, TranscriptOptions, TranscriptEntry } from './message/Transcript.js';
|
|
11
|
+
import type { Portal, UserProfile, AgentListItem } from './types/PortalTypes.js';
|
|
12
|
+
import type { CallerInfo, CallTranscriptEntry } from './platform/HookContract.js';
|
|
13
|
+
export type { UserDetails } from './api/ApiHelper.js';
|
|
14
|
+
/**
|
|
15
|
+
* Configuration options for creating an AiAgent instance.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```typescript
|
|
19
|
+
* const config: AiAgentConfig = {
|
|
20
|
+
* id: "123-456-789",
|
|
21
|
+
* endpoint: "https://api.egain.com",
|
|
22
|
+
* auth: { type: "pre-auth", accessToken: "your-access-token" },
|
|
23
|
+
* autoConnect: true,
|
|
24
|
+
* logLevel: LogLevel.DEBUG
|
|
25
|
+
* };
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* @category Core
|
|
29
|
+
*/
|
|
30
|
+
export interface AiAgentConfig {
|
|
31
|
+
/**
|
|
32
|
+
* Agent ID
|
|
33
|
+
*/
|
|
34
|
+
id: string;
|
|
35
|
+
/**
|
|
36
|
+
* WebSocket endpoint URL
|
|
37
|
+
*/
|
|
38
|
+
endpoint: string;
|
|
39
|
+
/**
|
|
40
|
+
* Authentication configuration (optional)
|
|
41
|
+
* Can be:
|
|
42
|
+
* - AuthenticationServiceConfig: Configuration object (e.g., { type: 'pre-auth', accessToken: '...' })
|
|
43
|
+
* - AuthProvider: Custom auth provider implementing getToken()
|
|
44
|
+
* - AuthStrategy: Full authentication strategy with lifecycle
|
|
45
|
+
* - undefined: Falls back to anonymous authentication
|
|
46
|
+
*/
|
|
47
|
+
auth?: AuthenticationInput;
|
|
48
|
+
/**
|
|
49
|
+
* Automatically connect after initialize() completes
|
|
50
|
+
* @default false
|
|
51
|
+
*/
|
|
52
|
+
autoConnect?: boolean;
|
|
53
|
+
/**
|
|
54
|
+
* Maximum queue size
|
|
55
|
+
* @default 1000
|
|
56
|
+
*/
|
|
57
|
+
maxQueueSize?: number;
|
|
58
|
+
/**
|
|
59
|
+
* Maximum reconnection attempts
|
|
60
|
+
* @default Infinity
|
|
61
|
+
*/
|
|
62
|
+
maxReconnectAttempts?: number;
|
|
63
|
+
/**
|
|
64
|
+
* Base reconnection delay in milliseconds
|
|
65
|
+
* @default 1000
|
|
66
|
+
*/
|
|
67
|
+
baseReconnectDelay?: number;
|
|
68
|
+
/**
|
|
69
|
+
* Maximum reconnection delay in milliseconds
|
|
70
|
+
* @default 30000
|
|
71
|
+
*/
|
|
72
|
+
maxReconnectDelay?: number;
|
|
73
|
+
/**
|
|
74
|
+
* Logger instance (optional)
|
|
75
|
+
* If not provided, a new logger instance will be created
|
|
76
|
+
* @default undefined (creates new instance)
|
|
77
|
+
*/
|
|
78
|
+
logger?: Logger;
|
|
79
|
+
/**
|
|
80
|
+
* Logging level for the agent
|
|
81
|
+
* @default INFO
|
|
82
|
+
*/
|
|
83
|
+
logLevel?: LogLevel;
|
|
84
|
+
/**
|
|
85
|
+
* Enable console output for logs
|
|
86
|
+
* @default true
|
|
87
|
+
*/
|
|
88
|
+
enableLogging?: boolean;
|
|
89
|
+
/**
|
|
90
|
+
* Transcript configuration (optional)
|
|
91
|
+
* Controls whether and how messages are stored in the transcript
|
|
92
|
+
*/
|
|
93
|
+
transcriptConfig?: TranscriptConfig;
|
|
94
|
+
/**
|
|
95
|
+
* Cache configuration for API calls (optional)
|
|
96
|
+
* Controls caching of agent details, portal details, and other API responses
|
|
97
|
+
* @default { enabled: true, storageType: 'session', ttl: 300000 }
|
|
98
|
+
*/
|
|
99
|
+
cache?: CacheConfig;
|
|
100
|
+
/**
|
|
101
|
+
* Custom OAuth scopes to request during authentication (optional)
|
|
102
|
+
* If not provided, default scopes will be used:
|
|
103
|
+
* - ["knowledge.portalmgr.manage", "core.aiservices.read"] for agents
|
|
104
|
+
* - ["knowledge.portalmgr.manage", "core.aiservices.read", "core.customermgr.read"] for customers
|
|
105
|
+
*
|
|
106
|
+
* You can provide additional scopes to extend the default ones, or replace them entirely.
|
|
107
|
+
* @example
|
|
108
|
+
* ```typescript
|
|
109
|
+
* // Add additional scopes
|
|
110
|
+
* scopes: ["knowledge.portalmgr.manage", "core.aiservices.read", "custom.scope"]
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
scopes?: string[];
|
|
114
|
+
/**
|
|
115
|
+
* Pre-provided session ID (optional)
|
|
116
|
+
* If provided, the SDK will skip fetching sessionId from the network during initialization.
|
|
117
|
+
* Useful when you already have a session ID from a previous session or external source.
|
|
118
|
+
*
|
|
119
|
+
* @default undefined (fetches from network)
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```typescript
|
|
123
|
+
* // Use existing sessionId (skips network fetch)
|
|
124
|
+
* const agent = new AiAgent({
|
|
125
|
+
* id: "agent-id",
|
|
126
|
+
* endpoint: "https://api.egain.com",
|
|
127
|
+
* sessionId: "existing-session-id"
|
|
128
|
+
* });
|
|
129
|
+
* ```
|
|
130
|
+
*/
|
|
131
|
+
sessionId?: string | number;
|
|
132
|
+
/**
|
|
133
|
+
* Initialization parameters forwarded from the host application.
|
|
134
|
+
* SDK consumers pass them explicitly so the SDK remains URL-agnostic.
|
|
135
|
+
*
|
|
136
|
+
* The SDK uses specific well-known keys internally:
|
|
137
|
+
* - `agentid` — when set and Flow A (`isDefaultAgent` is not `"true"`), portals are intersected with `agentDetails.portals` (cc-widget parity)
|
|
138
|
+
* - `departmentId` — optional fallback in Flow B when `agentDetails.departmentId` is missing; prefer agent details from the default agent API (cc-widget parity)
|
|
139
|
+
* - `portalIds` — comma-separated portal IDs; when set, skips `getMyPortals` and uses minimal portal objects
|
|
140
|
+
* - `templateName` — alias for theme short URL template sent as `shortUrlTemplate` to portalmgr APIs
|
|
141
|
+
* - `authType` — signals the authentication mode ("user" | "customer")
|
|
142
|
+
* - `scopes` — comma-separated OAuth scopes to request; when non-empty after parsing, **overrides** `config.scopes` and default scopes for PKCE / token acquisition
|
|
143
|
+
* - `userid` — user identifier for portal cache keying
|
|
144
|
+
* - `isDefaultAgent` — when "true", enables Flow B (agent selection mode)
|
|
145
|
+
*
|
|
146
|
+
* All other keys are stored and accessible via `agent.getInitParams()`
|
|
147
|
+
* for use by the consuming application.
|
|
148
|
+
*
|
|
149
|
+
* @example
|
|
150
|
+
* ```typescript
|
|
151
|
+
* initParams: {
|
|
152
|
+
* agentid: "agent-123",
|
|
153
|
+
* userid: "user-456",
|
|
154
|
+
* authType: "user",
|
|
155
|
+
* isDefaultAgent: "true",
|
|
156
|
+
* scopes: "knowledge.portalmgr.manage,core.aiservices.read"
|
|
157
|
+
* }
|
|
158
|
+
* ```
|
|
159
|
+
*/
|
|
160
|
+
initParams?: Record<string, string>;
|
|
161
|
+
/**
|
|
162
|
+
* Override URL for the platform connector script.
|
|
163
|
+
* When provided, the SDK loads this URL instead of constructing one
|
|
164
|
+
* from the platform name and deployment environment.
|
|
165
|
+
* Useful for local development or custom connector deployments.
|
|
166
|
+
*/
|
|
167
|
+
platformScriptUrl?: string;
|
|
168
|
+
/**
|
|
169
|
+
* Authentication scheme for the PKCE flow.
|
|
170
|
+
* - 'popup': Opens a popup window for login (default)
|
|
171
|
+
* - 'redirect': Redirects the current page to the identity provider
|
|
172
|
+
*
|
|
173
|
+
* Only applies when the SDK auto-builds PKCE config from deployment info.
|
|
174
|
+
* Ignored when a full PKCEAuthConfig is supplied via `config.auth`.
|
|
175
|
+
* @default 'popup'
|
|
176
|
+
*/
|
|
177
|
+
authScheme?: 'popup' | 'redirect';
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Agent event type identifiers
|
|
181
|
+
*/
|
|
182
|
+
export type AgentEventType = 'connected' | 'message' | 'agentMessage' | 'errorMessage' | 'error' | 'closed' | 'stateChanged' | 'queueFlushed' | 'heartbeat' | 'tokenExpiring' | 'transcriptUpdate' | 'callTranscriptUpdate' | 'callerInfoUpdate' | 'conversationIdUpdate' | 'userContextUpdate' | 'filterTagsUpdate' | 'initialized' | 'portalsAvailable' | 'agentsAvailable' | 'profilesAvailable';
|
|
183
|
+
/**
|
|
184
|
+
* Payload map for agent events
|
|
185
|
+
*/
|
|
186
|
+
export interface AgentEventPayloadMap {
|
|
187
|
+
connected: Record<string, never>;
|
|
188
|
+
message: {
|
|
189
|
+
data: any;
|
|
190
|
+
};
|
|
191
|
+
agentMessage: Omit<MessageHandlerResult, 'timestamp' | 'sessionId' | 'agentId'>;
|
|
192
|
+
errorMessage: {
|
|
193
|
+
message: Message;
|
|
194
|
+
error: Error;
|
|
195
|
+
};
|
|
196
|
+
error: {
|
|
197
|
+
error: Error;
|
|
198
|
+
};
|
|
199
|
+
closed: {
|
|
200
|
+
code?: number;
|
|
201
|
+
reason?: string;
|
|
202
|
+
};
|
|
203
|
+
stateChanged: {
|
|
204
|
+
state: ConnectionState;
|
|
205
|
+
previousState: ConnectionState;
|
|
206
|
+
};
|
|
207
|
+
queueFlushed: {
|
|
208
|
+
count: number;
|
|
209
|
+
};
|
|
210
|
+
heartbeat: Omit<MessageHandlerResult, 'timestamp' | 'sessionId' | 'agentId'>;
|
|
211
|
+
tokenExpiring: {
|
|
212
|
+
reason: 'expiring' | 'transport_request';
|
|
213
|
+
expiresAt?: number;
|
|
214
|
+
};
|
|
215
|
+
transcriptUpdate: {
|
|
216
|
+
entry: TranscriptEntry;
|
|
217
|
+
};
|
|
218
|
+
callTranscriptUpdate: {
|
|
219
|
+
entry: CallTranscriptEntry;
|
|
220
|
+
};
|
|
221
|
+
callerInfoUpdate: {
|
|
222
|
+
callerInfo: CallerInfo;
|
|
223
|
+
};
|
|
224
|
+
conversationIdUpdate: {
|
|
225
|
+
conversationId: string;
|
|
226
|
+
};
|
|
227
|
+
userContextUpdate: {
|
|
228
|
+
userContext: Record<string, unknown>;
|
|
229
|
+
};
|
|
230
|
+
filterTagsUpdate: {
|
|
231
|
+
filterTags: Record<string, string[]>;
|
|
232
|
+
};
|
|
233
|
+
/** Always includes at least agent (agentId, name). When CC pipeline completes: portal, portalDetails?, agent?, profile, availableProfiles, availablePortals. */
|
|
234
|
+
initialized: {
|
|
235
|
+
portal?: Portal;
|
|
236
|
+
portalDetails?: any;
|
|
237
|
+
agent?: AgentListItem | Record<string, unknown>;
|
|
238
|
+
profile?: UserProfile;
|
|
239
|
+
availableProfiles?: UserProfile[];
|
|
240
|
+
availablePortals?: Portal[];
|
|
241
|
+
};
|
|
242
|
+
portalsAvailable: {
|
|
243
|
+
portals: Portal[];
|
|
244
|
+
};
|
|
245
|
+
agentsAvailable: {
|
|
246
|
+
agents: AgentListItem[];
|
|
247
|
+
};
|
|
248
|
+
profilesAvailable: {
|
|
249
|
+
profiles: UserProfile[];
|
|
250
|
+
selectedPortal: Portal;
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Wrapped agent event structure
|
|
255
|
+
*/
|
|
256
|
+
export interface AgentEvent<T extends AgentEventType = AgentEventType> {
|
|
257
|
+
/**
|
|
258
|
+
* Event type identifier
|
|
259
|
+
*/
|
|
260
|
+
type: T;
|
|
261
|
+
/**
|
|
262
|
+
* Timestamp when the event occurred (milliseconds since epoch)
|
|
263
|
+
*/
|
|
264
|
+
timestamp: number;
|
|
265
|
+
/**
|
|
266
|
+
* Session ID associated with the event
|
|
267
|
+
*/
|
|
268
|
+
sessionId?: string | number;
|
|
269
|
+
/**
|
|
270
|
+
* Agent ID associated with the event
|
|
271
|
+
*/
|
|
272
|
+
agentId?: string | number;
|
|
273
|
+
/**
|
|
274
|
+
* Event-specific payload data
|
|
275
|
+
* Type varies based on the event type
|
|
276
|
+
*/
|
|
277
|
+
payload: AgentEventPayloadMap[T];
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Agent event map
|
|
281
|
+
*/
|
|
282
|
+
export interface AgentEvents {
|
|
283
|
+
/**
|
|
284
|
+
* Emitted when connection is established
|
|
285
|
+
*/
|
|
286
|
+
connected: AgentEvent<'connected'>;
|
|
287
|
+
/**
|
|
288
|
+
* Emitted when a message is received
|
|
289
|
+
*/
|
|
290
|
+
message: AgentEvent<'message'>;
|
|
291
|
+
/**
|
|
292
|
+
* Emitted when an agent message is received
|
|
293
|
+
*/
|
|
294
|
+
agentMessage: AgentEvent<'agentMessage'>;
|
|
295
|
+
/**
|
|
296
|
+
* Emitted when an error message is received
|
|
297
|
+
*/
|
|
298
|
+
errorMessage: AgentEvent<'errorMessage'>;
|
|
299
|
+
/**
|
|
300
|
+
* Emitted when an error occurs
|
|
301
|
+
*/
|
|
302
|
+
error: AgentEvent<'error'>;
|
|
303
|
+
/**
|
|
304
|
+
* Emitted when connection is closed
|
|
305
|
+
*/
|
|
306
|
+
closed: AgentEvent<'closed'>;
|
|
307
|
+
/**
|
|
308
|
+
* Emitted when connection state changes
|
|
309
|
+
*/
|
|
310
|
+
stateChanged: AgentEvent<'stateChanged'>;
|
|
311
|
+
/**
|
|
312
|
+
* Emitted when queue is flushed
|
|
313
|
+
*/
|
|
314
|
+
queueFlushed: AgentEvent<'queueFlushed'>;
|
|
315
|
+
/**
|
|
316
|
+
* Emitted when a heartbeat message is received
|
|
317
|
+
* Indicates the agent is processing/typing - UI can show a loader
|
|
318
|
+
*/
|
|
319
|
+
heartbeat: AgentEvent<'heartbeat'>;
|
|
320
|
+
/**
|
|
321
|
+
* Emitted when the access token is about to expire or needs refresh
|
|
322
|
+
* Triggered by JWT expiration detection (with 3-min buffer) or transport layer request
|
|
323
|
+
*/
|
|
324
|
+
tokenExpiring: AgentEvent<'tokenExpiring'>;
|
|
325
|
+
/**
|
|
326
|
+
* Emitted when the transcript is updated (message sent or received)
|
|
327
|
+
* Contains the new transcript entry with message and direction
|
|
328
|
+
*/
|
|
329
|
+
transcriptUpdate: AgentEvent<'transcriptUpdate'>;
|
|
330
|
+
/**
|
|
331
|
+
* Emitted when the platform connector pushes a call transcript entry
|
|
332
|
+
* via HookContract.addToTranscript(). Entries arrive incrementally during a call.
|
|
333
|
+
*/
|
|
334
|
+
callTranscriptUpdate: AgentEvent<'callTranscriptUpdate'>;
|
|
335
|
+
/**
|
|
336
|
+
* Emitted when the platform connector sets caller information
|
|
337
|
+
* via HookContract.setCallerInfo().
|
|
338
|
+
*/
|
|
339
|
+
callerInfoUpdate: AgentEvent<'callerInfoUpdate'>;
|
|
340
|
+
/**
|
|
341
|
+
* Emitted when the platform connector sets the conversation/interaction ID
|
|
342
|
+
* via HookContract.setConversationId().
|
|
343
|
+
*/
|
|
344
|
+
conversationIdUpdate: AgentEvent<'conversationIdUpdate'>;
|
|
345
|
+
/**
|
|
346
|
+
* Emitted when the platform connector appends to user context
|
|
347
|
+
* via HookContract.setUserContext(). Payload contains the merged context.
|
|
348
|
+
*/
|
|
349
|
+
userContextUpdate: AgentEvent<'userContextUpdate'>;
|
|
350
|
+
/**
|
|
351
|
+
* Emitted when the platform connector sets filter tags
|
|
352
|
+
* via HookContract.setUserFilterTags().
|
|
353
|
+
*/
|
|
354
|
+
filterTagsUpdate: AgentEvent<'filterTagsUpdate'>;
|
|
355
|
+
/**
|
|
356
|
+
* Emitted when the pipeline (or direct flow) is fully complete.
|
|
357
|
+
* Safe to call connect(). Consumer is responsible for calling connect() after this.
|
|
358
|
+
* Payload is never empty in practice: always at least agent (agentId, name). When the CC pipeline
|
|
359
|
+
* completed, also includes portal, optional portalDetails, optional agent, profile, availableProfiles, availablePortals.
|
|
360
|
+
*/
|
|
361
|
+
initialized: AgentEvent<'initialized'>;
|
|
362
|
+
/**
|
|
363
|
+
* Emitted when multiple portals are available.
|
|
364
|
+
* Consumer must call selectPortal(portal) to continue.
|
|
365
|
+
*/
|
|
366
|
+
portalsAvailable: AgentEvent<'portalsAvailable'>;
|
|
367
|
+
/**
|
|
368
|
+
* Emitted when multiple agents are available (Flow B only).
|
|
369
|
+
* Consumer must call selectAgent(agent) to continue.
|
|
370
|
+
*/
|
|
371
|
+
agentsAvailable: AgentEvent<'agentsAvailable'>;
|
|
372
|
+
/**
|
|
373
|
+
* Emitted when multiple user profiles exist and neither last-used nor default profile is found.
|
|
374
|
+
* Payload includes profiles and selectedPortal. Consumer must call selectUserProfile(profile) to continue.
|
|
375
|
+
*/
|
|
376
|
+
profilesAvailable: AgentEvent<'profilesAvailable'>;
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Main class for interacting with the eGain AI Agent platform.
|
|
380
|
+
*
|
|
381
|
+
* The AiAgent class provides:
|
|
382
|
+
* - WebSocket connection management with automatic reconnection
|
|
383
|
+
* - Message queuing when offline
|
|
384
|
+
* - Event-driven communication
|
|
385
|
+
* - Transcript management
|
|
386
|
+
* - Context persistence
|
|
387
|
+
*
|
|
388
|
+
* **Initialization flows**
|
|
389
|
+
*
|
|
390
|
+
* After authentication, one of two paths runs:
|
|
391
|
+
*
|
|
392
|
+
* - **Direct flow** (non–contact-center agents): fetches session, creates the WebSocket connection,
|
|
393
|
+
* emits `initialized`. With {@link AiAgentConfig.autoConnect}, `connect()` runs automatically.
|
|
394
|
+
* - **Contact Center (CC) flow** (contact-center agents, per API `agentType` / authenticated agents
|
|
395
|
+
* with legacy empty type): runs a REST-only portal → (optional agent) → profile pipeline, then
|
|
396
|
+
* emits `initialized`. The WebSocket is created when you call `connect()` (or automatically if
|
|
397
|
+
* `autoConnect` is true after the pipeline completes).
|
|
398
|
+
*
|
|
399
|
+
* **Flow A (specific agent)** — Use the target agent ID in {@link AiAgentConfig.id}. CC pipeline:
|
|
400
|
+
* portal selection → profile selection.
|
|
401
|
+
*
|
|
402
|
+
* **Flow B (default agent / agent selection)** — Set `initParams: { isDefaultAgent: "true" }`.
|
|
403
|
+
* CC pipeline: portal → agent → profile. The selected agent becomes the chat identity
|
|
404
|
+
* (`resolvedAgentId`); subsequent session and chat use that ID, not the bootstrap `config.id`.
|
|
405
|
+
*
|
|
406
|
+
* When the CC pipeline has multiple options at a step, it emits `portalsAvailable`,
|
|
407
|
+
* `agentsAvailable`, or `profilesAvailable`. Call {@link AiAgent.selectPortal},
|
|
408
|
+
* {@link AiAgent.selectAgent}, or {@link AiAgent.selectUserProfile} to continue. After the
|
|
409
|
+
* `initialized` event, call {@link AiAgent.connect} unless `autoConnect` already connected you.
|
|
410
|
+
*
|
|
411
|
+
* @example Direct flow (typical non–Contact Center agent)
|
|
412
|
+
* ```typescript
|
|
413
|
+
* import { AiAgent } from "@eGain/ai-agent-sdk";
|
|
414
|
+
*
|
|
415
|
+
* const agent = new AiAgent({
|
|
416
|
+
* id: "agent-id",
|
|
417
|
+
* endpoint: "https://api.egain.com",
|
|
418
|
+
* auth: { type: "pre-auth", accessToken: "your-access-token" },
|
|
419
|
+
* autoConnect: true,
|
|
420
|
+
* });
|
|
421
|
+
*
|
|
422
|
+
* agent.on("agentMessage", (event) => {
|
|
423
|
+
* console.log("Agent:", event.payload.message?.content);
|
|
424
|
+
* });
|
|
425
|
+
*
|
|
426
|
+
* await agent.initialize();
|
|
427
|
+
* await agent.send("Hello!");
|
|
428
|
+
* ```
|
|
429
|
+
*
|
|
430
|
+
* @example Contact Center flow (register handlers before `initialize`)
|
|
431
|
+
* ```typescript
|
|
432
|
+
* const agent = new AiAgent({
|
|
433
|
+
* id: "agent-id",
|
|
434
|
+
* endpoint: "https://api.egain.com",
|
|
435
|
+
* auth: { type: "pkce", config: { ... } },
|
|
436
|
+
* initParams: { userid: "user-123" },
|
|
437
|
+
* });
|
|
438
|
+
*
|
|
439
|
+
* agent.on("portalsAvailable", (e) => agent.selectPortal(e.payload.portals[0]));
|
|
440
|
+
* agent.on("agentsAvailable", (e) => agent.selectAgent(e.payload.agents[0]));
|
|
441
|
+
* agent.on("profilesAvailable", (e) => agent.selectUserProfile(e.payload.profiles[0]));
|
|
442
|
+
* agent.on("initialized", async () => {
|
|
443
|
+
* await agent.connect();
|
|
444
|
+
* });
|
|
445
|
+
* await agent.initialize();
|
|
446
|
+
* ```
|
|
447
|
+
*
|
|
448
|
+
* @example With context
|
|
449
|
+
* ```typescript
|
|
450
|
+
* import { AiAgent, createContextMessage } from "@eGain/ai-agent-sdk";
|
|
451
|
+
*
|
|
452
|
+
* await agent.send(createContextMessage({
|
|
453
|
+
* context: { userId: "123", accountType: "premium" },
|
|
454
|
+
* }));
|
|
455
|
+
* ```
|
|
456
|
+
*
|
|
457
|
+
* @category Core
|
|
458
|
+
* @see {@link AiAgentConfig} for configuration options
|
|
459
|
+
* @see {@link AgentEvents} for available events
|
|
460
|
+
*/
|
|
461
|
+
export declare class AiAgent extends EventEmitter<AgentEvents> {
|
|
462
|
+
private connection?;
|
|
463
|
+
private messageQueue;
|
|
464
|
+
private messageProcessor;
|
|
465
|
+
private authService;
|
|
466
|
+
private config;
|
|
467
|
+
private isInitialized;
|
|
468
|
+
private isFlushingQueue;
|
|
469
|
+
private deploymentInfo;
|
|
470
|
+
private apiHelper?;
|
|
471
|
+
private agentDetails?;
|
|
472
|
+
private sessionId?;
|
|
473
|
+
private transcript;
|
|
474
|
+
private contextCacheAdapter;
|
|
475
|
+
logger: Logger;
|
|
476
|
+
private resolvedAgentId;
|
|
477
|
+
private portalInitializer?;
|
|
478
|
+
private isAgentSelectionMode;
|
|
479
|
+
private initParams;
|
|
480
|
+
/** Cached profiles for restart (user-associated; portal details and agents are not cached). */
|
|
481
|
+
private cachedProfiles?;
|
|
482
|
+
/** True when the agent completed the portal initialization pipeline (needed for restart guard). */
|
|
483
|
+
private completedPortalPipeline;
|
|
484
|
+
/** Last selected portal from pipeline (needed for updateUserProfile). */
|
|
485
|
+
private lastSelectedPortal?;
|
|
486
|
+
private callerInfo;
|
|
487
|
+
private userContext;
|
|
488
|
+
private platformToken;
|
|
489
|
+
private isPlatformAuthenticated;
|
|
490
|
+
private conversationId;
|
|
491
|
+
private filterTags;
|
|
492
|
+
private callTranscript;
|
|
493
|
+
private hookContract?;
|
|
494
|
+
private platformComponentService?;
|
|
495
|
+
private userDetails;
|
|
496
|
+
/** True after `addCustomAuthScopes` merged scopes into `config.scopes` (PKCE/hooks must use that list). */
|
|
497
|
+
private authScopesAugmentedByPlatform;
|
|
498
|
+
constructor(config: AiAgentConfig);
|
|
499
|
+
/**
|
|
500
|
+
* Setup TokenRefreshHandler with callbacks for automatic token refresh
|
|
501
|
+
* Replaces the default handler with one that can actually perform token refresh
|
|
502
|
+
*/
|
|
503
|
+
private setupTokenRefreshHandler;
|
|
504
|
+
private parseQueryScopes;
|
|
505
|
+
/**
|
|
506
|
+
* Base OAuth resource scopes before platform augmentation: comma-separated `initParams.scopes`
|
|
507
|
+
* overrides `config.scopes` and defaults. Used to seed `addCustomAuthScopes`. For PKCE and hooks
|
|
508
|
+
* after the platform merges scopes, use {@link getAuthScopesForFlow}.
|
|
509
|
+
*/
|
|
510
|
+
private resolveEffectiveAuthScopes;
|
|
511
|
+
/**
|
|
512
|
+
* Scopes used for PKCE, AuthenticationService.initialize, and HookContract.getAuthScopes.
|
|
513
|
+
* After the platform connector augments scopes into `config.scopes`, that merged list wins.
|
|
514
|
+
*/
|
|
515
|
+
private getAuthScopesForFlow;
|
|
516
|
+
/**
|
|
517
|
+
* Initialize the agent. Must be called after construction and awaited before use.
|
|
518
|
+
*
|
|
519
|
+
* Authenticates (falls back to {@link AnonymousAuthStrategy} if no auth is configured), then:
|
|
520
|
+
*
|
|
521
|
+
* - **Direct flow:** fetches session, creates the WebSocket connection, emits `initialized`.
|
|
522
|
+
* With `autoConnect`, opens the WebSocket automatically.
|
|
523
|
+
* - **Contact Center flow:** runs portal / agent / profile selection over REST only (no WebSocket
|
|
524
|
+
* yet). May emit `portalsAvailable`, `agentsAvailable`, or `profilesAvailable` — call the
|
|
525
|
+
* corresponding `select*` method. Then emits `initialized`. Call {@link AiAgent.connect}
|
|
526
|
+
* afterward (or rely on `autoConnect` after the pipeline completes).
|
|
527
|
+
*
|
|
528
|
+
* @example
|
|
529
|
+
* ```typescript
|
|
530
|
+
* const agent = new AiAgent({ id: 'agent-id', endpoint: 'https://...' });
|
|
531
|
+
* await agent.initialize();
|
|
532
|
+
* // Direct flow: often already connected if autoConnect. CC flow: connect after `initialized`.
|
|
533
|
+
* await agent.connect();
|
|
534
|
+
* ```
|
|
535
|
+
*/
|
|
536
|
+
initialize(): Promise<void>;
|
|
537
|
+
/**
|
|
538
|
+
* Build the HookContract by closing over `this`.
|
|
539
|
+
* All getters return live state (not stale snapshots).
|
|
540
|
+
*/
|
|
541
|
+
private buildHookContract;
|
|
542
|
+
/**
|
|
543
|
+
* Load the platform connector script and wire up the HookContract.
|
|
544
|
+
* Called from initialize() when a non-standalone platform is detected.
|
|
545
|
+
*/
|
|
546
|
+
private loadAndInitializePlatform;
|
|
547
|
+
/**
|
|
548
|
+
* Whether to run the portal-based initializer (portals → optional agents → profiles) vs direct session setup.
|
|
549
|
+
* True when portal-related init params or agent configuration indicate a portal-trained / contact-center flow.
|
|
550
|
+
*/
|
|
551
|
+
private shouldRunPortalInitializationPipeline;
|
|
552
|
+
/**
|
|
553
|
+
* Session + connection + `initialized` for the non-portal path after auth.
|
|
554
|
+
*/
|
|
555
|
+
private runDirectInitializationAfterAuth;
|
|
556
|
+
private runPortalInitializerPipeline;
|
|
557
|
+
/**
|
|
558
|
+
* Post-authentication callback. Runs the portal initializer when
|
|
559
|
+
* {@link shouldRunPortalInitializationPipeline} is true; otherwise session + connection (direct flow).
|
|
560
|
+
* @param accessToken - The access token to use for authentication
|
|
561
|
+
*/
|
|
562
|
+
private readonly onAuthComplete;
|
|
563
|
+
/**
|
|
564
|
+
* Fetch user or customer details after authentication.
|
|
565
|
+
* Determination: if userType is 'customer', fetches customer details; otherwise fetches user details.
|
|
566
|
+
* Best-effort — logs a warning on failure but does not throw.
|
|
567
|
+
*/
|
|
568
|
+
private fetchUserOrCustomerDetails;
|
|
569
|
+
/**
|
|
570
|
+
* Fetch agent details from API
|
|
571
|
+
* @param accessToken - The access token to use for authentication
|
|
572
|
+
* @returns The agent details
|
|
573
|
+
*/
|
|
574
|
+
private fetchAgentDetails;
|
|
575
|
+
/**
|
|
576
|
+
* Ensures agent details have agentId from the request context when API omits it.
|
|
577
|
+
*
|
|
578
|
+
* @param details - The agent details to backfill the agentId for
|
|
579
|
+
* @returns The agent details with the agentId backfilled
|
|
580
|
+
*/
|
|
581
|
+
private backfillAgentDetailsId;
|
|
582
|
+
/**
|
|
583
|
+
* Get the agent details
|
|
584
|
+
* Returns cached agent details if available, otherwise fetches from network.
|
|
585
|
+
* If called before initialize(), performs minimal initialization to fetch agent details only
|
|
586
|
+
* (gets deployment info, fetches anonymous token, fetches agent details - without getting session ID or creating connection).
|
|
587
|
+
* @returns Promise resolving to the agent details
|
|
588
|
+
*/
|
|
589
|
+
getAgentDetails(): Promise<any>;
|
|
590
|
+
/**
|
|
591
|
+
* Get the deployment information
|
|
592
|
+
* Returns cached deployment info if available, otherwise fetches from network.
|
|
593
|
+
* Does not require initialization - only needs the endpoint URL.
|
|
594
|
+
* @returns Promise resolving to the deployment information
|
|
595
|
+
*/
|
|
596
|
+
getDeploymentInfo(): Promise<any>;
|
|
597
|
+
/**
|
|
598
|
+
* Get the agent name from cached agent details
|
|
599
|
+
* @returns The agent name
|
|
600
|
+
*/
|
|
601
|
+
private getAgentName;
|
|
602
|
+
/**
|
|
603
|
+
* Get session ID
|
|
604
|
+
* @param accessToken - The access token to use for authentication
|
|
605
|
+
* @returns The session ID
|
|
606
|
+
*/
|
|
607
|
+
private getSessionId;
|
|
608
|
+
/**
|
|
609
|
+
* Get WebSocket endpoint
|
|
610
|
+
* @param sessionId - The session ID
|
|
611
|
+
* @returns The WebSocket endpoint
|
|
612
|
+
*/
|
|
613
|
+
private getWsEndpoint;
|
|
614
|
+
/**
|
|
615
|
+
* Create the connection after authentication is complete
|
|
616
|
+
* This is called by the postAuthentication callback
|
|
617
|
+
*/
|
|
618
|
+
private createConnection;
|
|
619
|
+
/**
|
|
620
|
+
* Whether the agent has completed initialization.
|
|
621
|
+
* Becomes `true` after the init pipeline completes (e.g. after the `initialized` event).
|
|
622
|
+
*
|
|
623
|
+
* @returns `true` if initialized, `false` otherwise
|
|
624
|
+
*
|
|
625
|
+
* @example
|
|
626
|
+
* ```typescript
|
|
627
|
+
* if (agent.getIsInitialized()) {
|
|
628
|
+
* await agent.connect();
|
|
629
|
+
* } else {
|
|
630
|
+
* agent.once('initialized', () => agent.connect());
|
|
631
|
+
* }
|
|
632
|
+
* ```
|
|
633
|
+
*/
|
|
634
|
+
getIsInitialized(): boolean;
|
|
635
|
+
/**
|
|
636
|
+
* Get current connection state.
|
|
637
|
+
*
|
|
638
|
+
* @returns The current connection state
|
|
639
|
+
* @throws Error if agent is not initialized
|
|
640
|
+
*
|
|
641
|
+
* @example
|
|
642
|
+
* ```typescript
|
|
643
|
+
* const state = agent.getState();
|
|
644
|
+
* if (state === ConnectionState.CONNECTED) {
|
|
645
|
+
* console.log("Ready to send messages");
|
|
646
|
+
* }
|
|
647
|
+
* ```
|
|
648
|
+
*
|
|
649
|
+
* @see {@link ConnectionState} for available states
|
|
650
|
+
*/
|
|
651
|
+
getState(): ConnectionState;
|
|
652
|
+
/**
|
|
653
|
+
* Check if the agent is currently connected.
|
|
654
|
+
*
|
|
655
|
+
* @returns `true` if connected, `false` otherwise
|
|
656
|
+
*
|
|
657
|
+
* @example
|
|
658
|
+
* ```typescript
|
|
659
|
+
* if (agent.isConnected()) {
|
|
660
|
+
* await agent.send("Hello!");
|
|
661
|
+
* } else {
|
|
662
|
+
* console.log("Waiting for connection...");
|
|
663
|
+
* }
|
|
664
|
+
* ```
|
|
665
|
+
*/
|
|
666
|
+
isConnected(): boolean;
|
|
667
|
+
/**
|
|
668
|
+
* Connect to the agent endpoint.
|
|
669
|
+
*
|
|
670
|
+
* Establishes a WebSocket connection to the AI Agent server. Must call {@link initialize} first.
|
|
671
|
+
*
|
|
672
|
+
* For Contact Center agents, the connection object is created lazily on this call (session fetch
|
|
673
|
+
* uses the resolved agent ID, including Flow B after agent selection).
|
|
674
|
+
*
|
|
675
|
+
* @throws Error if agent is not initialized
|
|
676
|
+
*
|
|
677
|
+
* @example
|
|
678
|
+
* ```typescript
|
|
679
|
+
* await agent.initialize();
|
|
680
|
+
* await agent.connect();
|
|
681
|
+
* console.log("Connected!");
|
|
682
|
+
* ```
|
|
683
|
+
*/
|
|
684
|
+
connect(): Promise<void>;
|
|
685
|
+
/**
|
|
686
|
+
* Disconnect from the agent endpoint.
|
|
687
|
+
*
|
|
688
|
+
* By default, sends a graceful disconnect message before closing the connection.
|
|
689
|
+
* Use `skipGracefulDisconnect: true` for immediate disconnection.
|
|
690
|
+
*
|
|
691
|
+
* @param options - Disconnect options
|
|
692
|
+
* @param options.skipGracefulDisconnect - If true, skip sending graceful disconnect message
|
|
693
|
+
*
|
|
694
|
+
* @example Graceful disconnect
|
|
695
|
+
* ```typescript
|
|
696
|
+
* await agent.disconnect();
|
|
697
|
+
* ```
|
|
698
|
+
*
|
|
699
|
+
* @example Immediate disconnect
|
|
700
|
+
* ```typescript
|
|
701
|
+
* await agent.disconnect({ skipGracefulDisconnect: true });
|
|
702
|
+
* ```
|
|
703
|
+
*/
|
|
704
|
+
disconnect(options?: {
|
|
705
|
+
skipGracefulDisconnect?: boolean;
|
|
706
|
+
}): Promise<void>;
|
|
707
|
+
/**
|
|
708
|
+
* Select a portal (CC flow). Call when portalsAvailable event is emitted and user has chosen.
|
|
709
|
+
*
|
|
710
|
+
* @param portal - The selected portal
|
|
711
|
+
* @throws Error if portal initializer is not active
|
|
712
|
+
*
|
|
713
|
+
* @example
|
|
714
|
+
* ```typescript
|
|
715
|
+
* agent.on('portalsAvailable', (e) => {
|
|
716
|
+
* const portal = showPortalPicker(e.payload.portals);
|
|
717
|
+
* agent.selectPortal(portal);
|
|
718
|
+
* });
|
|
719
|
+
* ```
|
|
720
|
+
*/
|
|
721
|
+
selectPortal(portal: Portal): void;
|
|
722
|
+
/**
|
|
723
|
+
* Select an agent (Flow B only — `initParams.isDefaultAgent === "true"`).
|
|
724
|
+
* Call when `agentsAvailable` is emitted and the user has chosen.
|
|
725
|
+
*
|
|
726
|
+
* @param agent - The selected agent
|
|
727
|
+
* @throws Error if portal initializer is not active
|
|
728
|
+
*
|
|
729
|
+
* @example
|
|
730
|
+
* ```typescript
|
|
731
|
+
* agent.on('agentsAvailable', (e) => {
|
|
732
|
+
* const selected = showAgentPicker(e.payload.agents);
|
|
733
|
+
* agent.selectAgent(selected);
|
|
734
|
+
* });
|
|
735
|
+
* ```
|
|
736
|
+
*/
|
|
737
|
+
selectAgent(agent: AgentListItem): void;
|
|
738
|
+
/**
|
|
739
|
+
* Select a user profile (CC flow). Call when profilesAvailable event is emitted and user has chosen.
|
|
740
|
+
*
|
|
741
|
+
* @param profile - The selected profile
|
|
742
|
+
* @throws Error if portal initializer is not active
|
|
743
|
+
*
|
|
744
|
+
* @example
|
|
745
|
+
* ```typescript
|
|
746
|
+
* agent.on('profilesAvailable', (e) => {
|
|
747
|
+
* const profile = showProfilePicker(e.payload.profiles);
|
|
748
|
+
* agent.selectUserProfile(profile);
|
|
749
|
+
* });
|
|
750
|
+
* ```
|
|
751
|
+
*/
|
|
752
|
+
selectUserProfile(profile: UserProfile): void;
|
|
753
|
+
/**
|
|
754
|
+
* Get the stored initialization parameters from config.
|
|
755
|
+
*
|
|
756
|
+
* @returns The init params object (empty object if none provided)
|
|
757
|
+
*
|
|
758
|
+
* @example
|
|
759
|
+
* ```typescript
|
|
760
|
+
* const initParams = agent.getInitParams();
|
|
761
|
+
* const userId = initParams.userid;
|
|
762
|
+
* ```
|
|
763
|
+
*/
|
|
764
|
+
getInitParams(): Record<string, string>;
|
|
765
|
+
/**
|
|
766
|
+
* Restart the CC widget initialization pipeline from scratch.
|
|
767
|
+
*
|
|
768
|
+
* This method tears down the current initialization state and re-runs the
|
|
769
|
+
* full pipeline (portal selection → agent selection → profile selection),
|
|
770
|
+
* allowing the consumer to make new selections. After completion, the
|
|
771
|
+
* `initialized` event fires again and the consumer should call `connect()`.
|
|
772
|
+
*
|
|
773
|
+
* **What it does:**
|
|
774
|
+
* 1. Checks `completedPortalPipeline`: if false (non-CC agent), delegates to `restartConnection()` and returns
|
|
775
|
+
* 2. Destroys the current `PortalInitializer` instance (rejects any pending gating promises)
|
|
776
|
+
* 3. Disconnects the current WebSocket connection (if any) and clears session, queue, transcript
|
|
777
|
+
* 4. Resets `resolvedAgentId` to `config.id` and `isInitialized` to false
|
|
778
|
+
* 5. Re-obtains an auth token and calls `onAuthComplete` to restart the pipeline (or direct flow)
|
|
779
|
+
*
|
|
780
|
+
* **Important:** For agents that completed the CC initialization pipeline
|
|
781
|
+
* (portal → agent → profile selection), this re-runs the full pipeline.
|
|
782
|
+
* For agents that did not complete it (e.g. direct flow from the start, or
|
|
783
|
+
* contact-center agents that fell back to direct flow because they have no
|
|
784
|
+
* portals), this method delegates to `restartConnection()` so the consumer
|
|
785
|
+
* can call it for any restart without branching. The consumer must
|
|
786
|
+
* re-register or still have active event listeners for `portalsAvailable`,
|
|
787
|
+
* `agentsAvailable`, `profilesAvailable`, and `initialized` before calling
|
|
788
|
+
* this method (CC pipeline path only).
|
|
789
|
+
*
|
|
790
|
+
* @throws Error if authentication token cannot be obtained (CC path) or for restart (direct path)
|
|
791
|
+
*
|
|
792
|
+
* @example
|
|
793
|
+
* ```typescript
|
|
794
|
+
* // User wants to switch portals — restart the pipeline
|
|
795
|
+
* agent.on('portalsAvailable', (e) => {
|
|
796
|
+
* showPortalPicker(e.payload.portals, (p) => agent.selectPortal(p));
|
|
797
|
+
* });
|
|
798
|
+
*
|
|
799
|
+
* agent.on('initialized', async () => {
|
|
800
|
+
* await agent.connect();
|
|
801
|
+
* });
|
|
802
|
+
*
|
|
803
|
+
* await agent.restartPortalInitializer();
|
|
804
|
+
* ```
|
|
805
|
+
*/
|
|
806
|
+
restartPortalInitializer(): Promise<void>;
|
|
807
|
+
/**
|
|
808
|
+
* @deprecated Use {@link restartPortalInitializer} instead.
|
|
809
|
+
*/
|
|
810
|
+
restartCcWidgetInitializer(): Promise<void>;
|
|
811
|
+
/**
|
|
812
|
+
* Update the active user profile after initialization.
|
|
813
|
+
*
|
|
814
|
+
* Use this when the consumer wants to switch profiles without re-running the
|
|
815
|
+
* full portal/agent selection pipeline. This method:
|
|
816
|
+
* 1. Persists the new profile selection via the `selectUserProfile` API
|
|
817
|
+
* (if the profile is not already the last-used profile)
|
|
818
|
+
* 2. Disconnects the current WebSocket connection (if any)
|
|
819
|
+
* 3. Clears the message queue and transcript
|
|
820
|
+
* 4. Fetches a new session ID and reconnects
|
|
821
|
+
* 5. Emits `initialized` with the updated profile in the payload
|
|
822
|
+
*
|
|
823
|
+
* This is the equivalent of the cc-widget's profile dropdown behavior:
|
|
824
|
+
* change the profile → restart session → re-send user context.
|
|
825
|
+
*
|
|
826
|
+
* **Important:** This method is only valid after the CC initialization
|
|
827
|
+
* pipeline has completed. Calling it on a non-CC agent or before
|
|
828
|
+
* initialization throws an error.
|
|
829
|
+
*
|
|
830
|
+
* @param profile - The new user profile to activate
|
|
831
|
+
* @throws Error if agent is not initialized
|
|
832
|
+
* @throws Error if agent did not go through the CC initialization flow
|
|
833
|
+
* @throws Error if no portal is currently selected
|
|
834
|
+
*
|
|
835
|
+
* @example
|
|
836
|
+
* ```typescript
|
|
837
|
+
* // User picks a different profile from a dropdown
|
|
838
|
+
* const profiles = cachedProfiles; // from the profilesAvailable event
|
|
839
|
+
* agent.on("initialized", async () => {
|
|
840
|
+
* await agent.connect();
|
|
841
|
+
* });
|
|
842
|
+
* await agent.updateUserProfile(profiles[2]);
|
|
843
|
+
* ```
|
|
844
|
+
*/
|
|
845
|
+
updateUserProfile(profile: UserProfile): Promise<void>;
|
|
846
|
+
/**
|
|
847
|
+
* Restart the connection with a fresh session.
|
|
848
|
+
*
|
|
849
|
+
* This method:
|
|
850
|
+
* 1. Gracefully disconnects from the current session
|
|
851
|
+
* 2. Clears all queued messages and transcript
|
|
852
|
+
* 3. Obtains a new session ID (or uses provided one)
|
|
853
|
+
* 4. Reconnects to the new session
|
|
854
|
+
* 5. Sends any stored context to the new session
|
|
855
|
+
*
|
|
856
|
+
* **Note:** All queued messages will be lost during restart.
|
|
857
|
+
*
|
|
858
|
+
* @param options - Optional restart options
|
|
859
|
+
* @param options.sessionId - Optional session ID to use for restart. If provided, skips fetching from network.
|
|
860
|
+
* @throws Error if agent is not initialized
|
|
861
|
+
*
|
|
862
|
+
* @example
|
|
863
|
+
* ```typescript
|
|
864
|
+
* // Start a fresh conversation (fetches new sessionId)
|
|
865
|
+
* await agent.restartConnection();
|
|
866
|
+
*
|
|
867
|
+
* // Restart with a specific sessionId
|
|
868
|
+
* await agent.restartConnection({ sessionId: 'existing-session-id' });
|
|
869
|
+
*
|
|
870
|
+
* // Context is automatically restored
|
|
871
|
+
* await agent.send("Hello again!");
|
|
872
|
+
* ```
|
|
873
|
+
*/
|
|
874
|
+
restartConnection(options?: {
|
|
875
|
+
sessionId?: string | number;
|
|
876
|
+
}): Promise<void>;
|
|
877
|
+
/**
|
|
878
|
+
* Normalize input data to a Message instance
|
|
879
|
+
* @private
|
|
880
|
+
*/
|
|
881
|
+
private normalizeToMessage;
|
|
882
|
+
/**
|
|
883
|
+
* Send a message to the agent
|
|
884
|
+
* Messages are queued if offline and automatically sent when connected
|
|
885
|
+
* Context messages are automatically stored in cache for use on reconnection
|
|
886
|
+
* @param data - Message data (can be a Message instance, plain object, or string)
|
|
887
|
+
* @param options - Optional message options
|
|
888
|
+
* @param options.id - Optional message ID
|
|
889
|
+
* @param options.from - Optional sender identifier (agent ID, customer ID, etc.)
|
|
890
|
+
* @param options.to - Optional recipient identifier (agent ID, etc.)
|
|
891
|
+
* @returns Message ID
|
|
892
|
+
*/
|
|
893
|
+
send(data: any, options?: {
|
|
894
|
+
id?: string;
|
|
895
|
+
from?: string;
|
|
896
|
+
to?: string;
|
|
897
|
+
}): Promise<string>;
|
|
898
|
+
/**
|
|
899
|
+
* Get the current queue size
|
|
900
|
+
*/
|
|
901
|
+
getQueueSize(): number;
|
|
902
|
+
/**
|
|
903
|
+
* Clear the message queue
|
|
904
|
+
*/
|
|
905
|
+
clearQueue(): void;
|
|
906
|
+
/**
|
|
907
|
+
* Get transcript entries
|
|
908
|
+
* @param options - Optional filtering options
|
|
909
|
+
* @returns Array of transcript entries with Message objects
|
|
910
|
+
*/
|
|
911
|
+
getTranscript(options?: TranscriptOptions): TranscriptEntry[];
|
|
912
|
+
/**
|
|
913
|
+
* Get transcript entries as plain objects (JSON-serializable)
|
|
914
|
+
* @param options - Optional filtering options
|
|
915
|
+
* @returns Array of plain objects representing transcript entries
|
|
916
|
+
*/
|
|
917
|
+
getTranscriptAsJSON(options?: TranscriptOptions): any[];
|
|
918
|
+
/**
|
|
919
|
+
* Get the number of entries in the transcript
|
|
920
|
+
* @returns Number of transcript entries
|
|
921
|
+
*/
|
|
922
|
+
getTranscriptSize(): number;
|
|
923
|
+
/**
|
|
924
|
+
* Clear all transcript entries
|
|
925
|
+
*/
|
|
926
|
+
clearTranscript(): void;
|
|
927
|
+
/**
|
|
928
|
+
* Get the call transcript — the live customer-agent conversation from the
|
|
929
|
+
* telephony platform (Genesys, Amazon Connect, etc.), pushed by the platform
|
|
930
|
+
* connector via the HookContract.
|
|
931
|
+
*
|
|
932
|
+
* This is distinct from {@link getTranscript}, which returns the AI Agent
|
|
933
|
+
* chat transcript (WebSocket messages).
|
|
934
|
+
*
|
|
935
|
+
* @returns A shallow copy of the call transcript entries
|
|
936
|
+
*/
|
|
937
|
+
getCallTranscript(): CallTranscriptEntry[];
|
|
938
|
+
/**
|
|
939
|
+
* Get the caller information set by the platform connector via
|
|
940
|
+
* HookContract.setCallerInfo(). Available after the platform connector
|
|
941
|
+
* has initialized (typically before the `initialized` event fires).
|
|
942
|
+
*
|
|
943
|
+
* @returns The caller info object, or null if not yet set
|
|
944
|
+
*/
|
|
945
|
+
getCallerInfo(): CallerInfo | null;
|
|
946
|
+
/**
|
|
947
|
+
* Returns the authenticated user's or customer's details fetched after authentication.
|
|
948
|
+
* Available after the `initialized` event fires. Returns null if details could not be fetched.
|
|
949
|
+
*/
|
|
950
|
+
getUserDetails(): UserDetails | null;
|
|
951
|
+
getConversationId(): string | null;
|
|
952
|
+
/**
|
|
953
|
+
* Clear all call transcript entries.
|
|
954
|
+
*/
|
|
955
|
+
clearCallTranscript(): void;
|
|
956
|
+
/**
|
|
957
|
+
* Get the context cache key for this agent
|
|
958
|
+
* @returns The cache key for storing context
|
|
959
|
+
*/
|
|
960
|
+
private getContextCacheKey;
|
|
961
|
+
/**
|
|
962
|
+
* Cache key for persisted profile list (pipeline restart).
|
|
963
|
+
* Includes portalId so switching portals doesn't serve stale profiles.
|
|
964
|
+
*/
|
|
965
|
+
private getPipelineProfilesCacheKey;
|
|
966
|
+
/**
|
|
967
|
+
* Check if a message is a context message
|
|
968
|
+
* @param data - The message data to check
|
|
969
|
+
* @returns True if this is a context message
|
|
970
|
+
*/
|
|
971
|
+
private isContextMessage;
|
|
972
|
+
/**
|
|
973
|
+
* Extract context data from a context message
|
|
974
|
+
* @param data - The message data to extract context from
|
|
975
|
+
* @returns The context object or null if not a context message
|
|
976
|
+
*/
|
|
977
|
+
private extractContextFromMessage;
|
|
978
|
+
/**
|
|
979
|
+
* Store context in cache
|
|
980
|
+
* @param context - The context object to store
|
|
981
|
+
*/
|
|
982
|
+
private storeContext;
|
|
983
|
+
/**
|
|
984
|
+
* Get the stored context for this agent
|
|
985
|
+
* Returns the context object that was previously sent via a context message
|
|
986
|
+
* @returns The stored context object or null if no context is stored
|
|
987
|
+
*/
|
|
988
|
+
getContext(): object | null;
|
|
989
|
+
/**
|
|
990
|
+
* Remove the stored context for this agent
|
|
991
|
+
* Clears any previously stored context from the cache
|
|
992
|
+
*/
|
|
993
|
+
removeContext(): void;
|
|
994
|
+
/**
|
|
995
|
+
* Set context for this agent
|
|
996
|
+
* Stores the context in cache and optionally sends it to the agent immediately
|
|
997
|
+
* @param context - The context object to set
|
|
998
|
+
* @param options - Optional settings
|
|
999
|
+
* @param options.sendImmediately - If true, sends the context to the agent right away (default: false)
|
|
1000
|
+
* @returns Promise that resolves when context is set (and sent if sendImmediately is true)
|
|
1001
|
+
*
|
|
1002
|
+
* @example Set context without sending
|
|
1003
|
+
* ```typescript
|
|
1004
|
+
* agent.setContext({ userId: "123", plan: "premium" });
|
|
1005
|
+
* ```
|
|
1006
|
+
*
|
|
1007
|
+
* @example Set and send context immediately
|
|
1008
|
+
* ```typescript
|
|
1009
|
+
* await agent.setContext({ userId: "123", plan: "premium" }, { sendImmediately: true });
|
|
1010
|
+
* ```
|
|
1011
|
+
*/
|
|
1012
|
+
setContext(context: object, options?: {
|
|
1013
|
+
sendImmediately?: boolean;
|
|
1014
|
+
}): Promise<void>;
|
|
1015
|
+
/**
|
|
1016
|
+
* Reset (clear) the context for this agent
|
|
1017
|
+
* Removes any stored context from the cache
|
|
1018
|
+
* This is an alias for removeContext() with additional logging
|
|
1019
|
+
*
|
|
1020
|
+
* @example
|
|
1021
|
+
* ```typescript
|
|
1022
|
+
* agent.resetContext();
|
|
1023
|
+
* ```
|
|
1024
|
+
*/
|
|
1025
|
+
resetContext(): void;
|
|
1026
|
+
/**
|
|
1027
|
+
* Send stored context to the agent
|
|
1028
|
+
* This is called internally after reconnection to restore context
|
|
1029
|
+
* @returns Promise that resolves when context is sent (or immediately if no context)
|
|
1030
|
+
*/
|
|
1031
|
+
private sendStoredContext;
|
|
1032
|
+
/**
|
|
1033
|
+
* Setup connection event forwarding
|
|
1034
|
+
*/
|
|
1035
|
+
private setupConnectionEvents;
|
|
1036
|
+
/**
|
|
1037
|
+
* Send authentication token to agent if authentication is required
|
|
1038
|
+
* This is called immediately after connection is established
|
|
1039
|
+
*/
|
|
1040
|
+
private sendAuthTokenIfRequired;
|
|
1041
|
+
/**
|
|
1042
|
+
* Queue a message for later sending
|
|
1043
|
+
*/
|
|
1044
|
+
private queueMessage;
|
|
1045
|
+
/**
|
|
1046
|
+
* Flush queued messages when connected
|
|
1047
|
+
*/
|
|
1048
|
+
private flushQueue;
|
|
1049
|
+
/**
|
|
1050
|
+
* Create an AgentEvent object with automatic timestamp, sessionId, and agentId
|
|
1051
|
+
* @param type - The event type
|
|
1052
|
+
* @param payload - The event-specific payload data
|
|
1053
|
+
* @param options - Optional overrides for timestamp, sessionId, or agentId
|
|
1054
|
+
* @returns A properly formatted AgentEvent object
|
|
1055
|
+
*/
|
|
1056
|
+
private createAgentEventResponse;
|
|
1057
|
+
/**
|
|
1058
|
+
* Generate a unique message ID
|
|
1059
|
+
*/
|
|
1060
|
+
private generateMessageId;
|
|
1061
|
+
/**
|
|
1062
|
+
* Delay utility
|
|
1063
|
+
*/
|
|
1064
|
+
private delay;
|
|
1065
|
+
/**
|
|
1066
|
+
* Get the message processor instance
|
|
1067
|
+
* Allows adding custom handlers
|
|
1068
|
+
*/
|
|
1069
|
+
getMessageProcessor(): MessageProcessor;
|
|
1070
|
+
/**
|
|
1071
|
+
* Get the current access token from the authentication strategy
|
|
1072
|
+
* Returns the access token that the agent is currently using for authentication
|
|
1073
|
+
* @returns Promise resolving to the access token string, or null if no token is available
|
|
1074
|
+
*
|
|
1075
|
+
* @example
|
|
1076
|
+
* ```typescript
|
|
1077
|
+
* const token = await agent.getAccessToken();
|
|
1078
|
+
* if (token) {
|
|
1079
|
+
* // Use the token for external API calls
|
|
1080
|
+
* fetch('https://api.example.com/data', {
|
|
1081
|
+
* headers: { Authorization: `Bearer ${token}` }
|
|
1082
|
+
* });
|
|
1083
|
+
* }
|
|
1084
|
+
* ```
|
|
1085
|
+
*/
|
|
1086
|
+
getAccessToken(): Promise<string | null>;
|
|
1087
|
+
/**
|
|
1088
|
+
* Update the access token at runtime
|
|
1089
|
+
* Use this method when you receive a tokenExpiring event to provide a new token
|
|
1090
|
+
* @param token - The new access token
|
|
1091
|
+
* @throws Error if the authentication strategy doesn't support token updates
|
|
1092
|
+
*
|
|
1093
|
+
* @example
|
|
1094
|
+
* ```typescript
|
|
1095
|
+
* agent.on('tokenExpiring', async (event) => {
|
|
1096
|
+
* const newToken = await fetchNewTokenFromServer();
|
|
1097
|
+
* await agent.updateAccessToken(newToken);
|
|
1098
|
+
* });
|
|
1099
|
+
* ```
|
|
1100
|
+
*/
|
|
1101
|
+
updateAccessToken(token: string): Promise<void>;
|
|
1102
|
+
/**
|
|
1103
|
+
* Set or update the session ID at runtime
|
|
1104
|
+
* Updates the sessionId property, which will be used for future connections and logging.
|
|
1105
|
+
*
|
|
1106
|
+
* **Note:** If the agent is currently connected, changing the sessionId will not automatically
|
|
1107
|
+
* switch the connection to the new session. You should either:
|
|
1108
|
+
* - Disconnect and reconnect with the new sessionId
|
|
1109
|
+
* - Use `restartConnection({ sessionId: newSessionId })` to restart with the new session
|
|
1110
|
+
*
|
|
1111
|
+
* @param sessionId - The new session ID to set
|
|
1112
|
+
*
|
|
1113
|
+
* @example
|
|
1114
|
+
* ```typescript
|
|
1115
|
+
* // Update sessionId after initialization
|
|
1116
|
+
* agent.setSessionId('new-session-id');
|
|
1117
|
+
*
|
|
1118
|
+
* // If connected, restart with the new sessionId
|
|
1119
|
+
* if (agent.isConnected()) {
|
|
1120
|
+
* await agent.restartConnection({ sessionId: 'new-session-id' });
|
|
1121
|
+
* }
|
|
1122
|
+
* ```
|
|
1123
|
+
*/
|
|
1124
|
+
setSessionId(sessionId: string | number): void;
|
|
1125
|
+
}
|
|
1126
|
+
//# sourceMappingURL=AiAgent.d.ts.map
|