@astermind/cybernetic-chatbot-client 2.2.34 → 2.2.44

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.
@@ -1014,6 +1014,603 @@ class CyberneticOfflineStorage {
1014
1014
  }
1015
1015
  }
1016
1016
 
1017
+ // src/WebSocketTransport.ts
1018
+ // WebSocket transport for streaming chat via SaaS WebSocket API (chatws.astermind.ai)
1019
+ /**
1020
+ * WebSocket transport for streaming chat.
1021
+ *
1022
+ * Maps the chat-handler Lambda WebSocket protocol to the client's StreamCallbacks:
1023
+ * Server typing → ignored (UI has its own indicator)
1024
+ * Server chunk → onToken(content)
1025
+ * Server done → onSources(sources) + onComplete(response)
1026
+ * Server error → onError(error)
1027
+ *
1028
+ * Connection is lazy — established on the first chatStream() call.
1029
+ * Reuses the same connection across multiple messages.
1030
+ * Reconnects with exponential backoff on close/error.
1031
+ */
1032
+ class WebSocketTransport {
1033
+ constructor(wsUrl, apiKey, options) {
1034
+ this.ws = null;
1035
+ this.state = 'disconnected';
1036
+ this.reconnectAttempts = 0;
1037
+ this.connectionPromise = null;
1038
+ // Active streaming request tracking
1039
+ this.activeCallbacks = null;
1040
+ this.activeFullText = '';
1041
+ // Cleanup handler reference
1042
+ this.beforeUnloadHandler = null;
1043
+ // Promise callbacks for the active stream
1044
+ this._resolveStream = null;
1045
+ this._rejectStream = null;
1046
+ this.wsUrl = wsUrl;
1047
+ this.apiKey = apiKey;
1048
+ this.maxReconnectAttempts = options?.maxReconnectAttempts ?? 3;
1049
+ this.reconnectDelay = options?.reconnectDelay ?? 1000;
1050
+ this.connectionTimeout = options?.connectionTimeout ?? 10000;
1051
+ }
1052
+ /**
1053
+ * Current transport state
1054
+ */
1055
+ getState() {
1056
+ return this.state;
1057
+ }
1058
+ /**
1059
+ * Whether the WebSocket is currently connected
1060
+ */
1061
+ isConnected() {
1062
+ return this.state === 'connected' && this.ws?.readyState === WebSocket.OPEN;
1063
+ }
1064
+ /**
1065
+ * Connect to the WebSocket endpoint.
1066
+ * Appends the API key as a query parameter for authentication.
1067
+ * Returns a promise that resolves when the connection is open.
1068
+ */
1069
+ connect() {
1070
+ // Already connected
1071
+ if (this.isConnected()) {
1072
+ return Promise.resolve();
1073
+ }
1074
+ // Connection already in progress
1075
+ if (this.connectionPromise) {
1076
+ return this.connectionPromise;
1077
+ }
1078
+ this.state = 'connecting';
1079
+ this.connectionPromise = new Promise((resolve, reject) => {
1080
+ try {
1081
+ // Build URL with API key
1082
+ const separator = this.wsUrl.includes('?') ? '&' : '?';
1083
+ const fullUrl = `${this.wsUrl}${separator}apiKey=${encodeURIComponent(this.apiKey)}`;
1084
+ const ws = new WebSocket(fullUrl);
1085
+ this.ws = ws;
1086
+ // Connection timeout
1087
+ const timeout = setTimeout(() => {
1088
+ if (ws.readyState !== WebSocket.OPEN) {
1089
+ ws.close();
1090
+ this.state = 'error';
1091
+ this.connectionPromise = null;
1092
+ reject(new Error('WebSocket connection timed out'));
1093
+ }
1094
+ }, this.connectionTimeout);
1095
+ ws.onopen = () => {
1096
+ clearTimeout(timeout);
1097
+ this.state = 'connected';
1098
+ this.reconnectAttempts = 0;
1099
+ this.connectionPromise = null;
1100
+ this.registerCleanup();
1101
+ resolve();
1102
+ };
1103
+ ws.onmessage = (event) => {
1104
+ this.handleMessage(event);
1105
+ };
1106
+ ws.onerror = () => {
1107
+ clearTimeout(timeout);
1108
+ this.state = 'error';
1109
+ this.connectionPromise = null;
1110
+ // The close event fires after error, which will trigger reconnect
1111
+ };
1112
+ ws.onclose = (event) => {
1113
+ clearTimeout(timeout);
1114
+ const wasConnected = this.state === 'connected';
1115
+ this.state = 'disconnected';
1116
+ this.connectionPromise = null;
1117
+ this.unregisterCleanup();
1118
+ // If we had an active request, report the error
1119
+ if (this.activeCallbacks) {
1120
+ this.activeCallbacks.onError?.({
1121
+ code: 'WS_ERROR',
1122
+ message: event.reason || `WebSocket closed (code: ${event.code})`
1123
+ });
1124
+ this.clearActiveRequest();
1125
+ }
1126
+ // Reject if we were trying to connect
1127
+ if (!wasConnected) {
1128
+ reject(new Error(event.reason || `WebSocket closed (code: ${event.code})`));
1129
+ }
1130
+ };
1131
+ }
1132
+ catch (error) {
1133
+ this.state = 'error';
1134
+ this.connectionPromise = null;
1135
+ reject(error);
1136
+ }
1137
+ });
1138
+ return this.connectionPromise;
1139
+ }
1140
+ /**
1141
+ * Stream a chat message over WebSocket.
1142
+ *
1143
+ * Sends: { type: "sendMessage", message, sessionId?, wordLimit?, context? }
1144
+ * Receives: typing → chunk × N → done (with sources and metadata)
1145
+ */
1146
+ async chatStream(message, options) {
1147
+ const { sessionId, context, wordLimit, onToken, onSources, onComplete, onError } = options;
1148
+ // Ensure connection is established (lazy connect)
1149
+ try {
1150
+ await this.connect();
1151
+ }
1152
+ catch (error) {
1153
+ onError?.({
1154
+ code: 'WS_ERROR',
1155
+ message: `Failed to connect: ${error instanceof Error ? error.message : String(error)}`
1156
+ });
1157
+ throw error;
1158
+ }
1159
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1160
+ const err = { code: 'WS_ERROR', message: 'WebSocket not connected' };
1161
+ onError?.(err);
1162
+ throw new Error(err.message);
1163
+ }
1164
+ // Set up active request tracking
1165
+ this.activeCallbacks = { onToken, onSources, onComplete, onError };
1166
+ this.activeFullText = '';
1167
+ this.activeSessionId = sessionId;
1168
+ // Build and send the message
1169
+ const payload = {
1170
+ type: 'sendMessage',
1171
+ message,
1172
+ };
1173
+ if (sessionId)
1174
+ payload.sessionId = sessionId;
1175
+ if (wordLimit)
1176
+ payload.wordLimit = wordLimit;
1177
+ if (context)
1178
+ payload.context = context;
1179
+ // Return a promise that resolves when done/error is received
1180
+ return new Promise((resolve, reject) => {
1181
+ // Store resolve/reject so handleMessage can call them
1182
+ this._resolveStream = resolve;
1183
+ this._rejectStream = reject;
1184
+ this.ws.send(JSON.stringify(payload));
1185
+ });
1186
+ }
1187
+ /**
1188
+ * Disconnect and clean up the WebSocket connection
1189
+ */
1190
+ disconnect() {
1191
+ this.unregisterCleanup();
1192
+ if (this.ws) {
1193
+ // Remove handlers to avoid triggering reconnect
1194
+ this.ws.onclose = null;
1195
+ this.ws.onerror = null;
1196
+ this.ws.onmessage = null;
1197
+ this.ws.close();
1198
+ this.ws = null;
1199
+ }
1200
+ this.state = 'disconnected';
1201
+ this.connectionPromise = null;
1202
+ this.clearActiveRequest();
1203
+ }
1204
+ /**
1205
+ * Attempt reconnection with exponential backoff.
1206
+ * Used internally after connection loss.
1207
+ */
1208
+ async reconnect() {
1209
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
1210
+ this.state = 'error';
1211
+ throw new Error(`Max reconnection attempts (${this.maxReconnectAttempts}) exceeded`);
1212
+ }
1213
+ const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts);
1214
+ this.reconnectAttempts++;
1215
+ console.log(`[Cybernetic WS] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
1216
+ await new Promise(resolve => setTimeout(resolve, delay));
1217
+ // Ensure old connection is cleaned up
1218
+ if (this.ws) {
1219
+ this.ws.onclose = null;
1220
+ this.ws.onerror = null;
1221
+ this.ws.close();
1222
+ this.ws = null;
1223
+ }
1224
+ return this.connect();
1225
+ }
1226
+ // ==================== INTERNAL ====================
1227
+ /**
1228
+ * Handle incoming WebSocket messages from the chat-handler Lambda.
1229
+ *
1230
+ * Protocol:
1231
+ * { type: 'typing', status: boolean } → ignored
1232
+ * { type: 'chunk', content: string } → onToken(content)
1233
+ * { type: 'done', sessionId, sources, metadata, messageId } → onSources + onComplete
1234
+ * { type: 'error', error: string } → onError
1235
+ */
1236
+ handleMessage(event) {
1237
+ if (!this.activeCallbacks)
1238
+ return;
1239
+ try {
1240
+ const data = JSON.parse(event.data);
1241
+ switch (data.type) {
1242
+ case 'typing':
1243
+ // Ignored — the chatbot-template manages its own typing indicator
1244
+ break;
1245
+ case 'chunk':
1246
+ if (data.content) {
1247
+ this.activeFullText += data.content;
1248
+ this.activeCallbacks.onToken?.(data.content);
1249
+ }
1250
+ break;
1251
+ case 'done': {
1252
+ // Map sources from chat-handler format to client Source format
1253
+ const sources = this.mapSources(data.sources || []);
1254
+ // Emit sources
1255
+ this.activeCallbacks.onSources?.(sources);
1256
+ // Build complete response
1257
+ const response = {
1258
+ reply: this.activeFullText,
1259
+ confidence: 'high',
1260
+ sources,
1261
+ offline: false,
1262
+ sessionId: data.sessionId || this.activeSessionId,
1263
+ };
1264
+ this.activeCallbacks.onComplete?.(response);
1265
+ this._resolveStream?.();
1266
+ this.clearActiveRequest();
1267
+ break;
1268
+ }
1269
+ case 'error': {
1270
+ const err = {
1271
+ code: 'WS_ERROR',
1272
+ message: data.error || 'Unknown WebSocket error'
1273
+ };
1274
+ this.activeCallbacks.onError?.(err);
1275
+ this._rejectStream?.(new Error(err.message));
1276
+ this.clearActiveRequest();
1277
+ break;
1278
+ }
1279
+ default:
1280
+ // Unknown message type — log and ignore
1281
+ console.warn('[Cybernetic WS] Unknown message type:', data.type);
1282
+ break;
1283
+ }
1284
+ }
1285
+ catch (error) {
1286
+ console.error('[Cybernetic WS] Failed to parse message:', error, event.data);
1287
+ }
1288
+ }
1289
+ /**
1290
+ * Map sources from the chat-handler WebSocket format to the client Source interface.
1291
+ *
1292
+ * Chat-handler sends: { heading, content, score, documentId, documentName }
1293
+ * Client expects: { title, snippet, relevance, documentId, documentName }
1294
+ */
1295
+ mapSources(wsSources) {
1296
+ if (!Array.isArray(wsSources))
1297
+ return [];
1298
+ return wsSources.map((s) => ({
1299
+ title: s.heading || s.documentName || 'Document',
1300
+ snippet: s.content || '',
1301
+ relevance: s.score ?? 0,
1302
+ documentId: s.documentId,
1303
+ documentName: s.documentName,
1304
+ sourceType: 'document',
1305
+ }));
1306
+ }
1307
+ /**
1308
+ * Clear active request state after completion or error
1309
+ */
1310
+ clearActiveRequest() {
1311
+ this.activeCallbacks = null;
1312
+ this.activeFullText = '';
1313
+ this._resolveStream = null;
1314
+ this._rejectStream = null;
1315
+ }
1316
+ /**
1317
+ * Register a beforeunload handler to close the WebSocket on page unload
1318
+ */
1319
+ registerCleanup() {
1320
+ if (typeof window !== 'undefined' && !this.beforeUnloadHandler) {
1321
+ this.beforeUnloadHandler = () => this.disconnect();
1322
+ window.addEventListener('beforeunload', this.beforeUnloadHandler);
1323
+ }
1324
+ }
1325
+ /**
1326
+ * Remove the beforeunload handler
1327
+ */
1328
+ unregisterCleanup() {
1329
+ if (typeof window !== 'undefined' && this.beforeUnloadHandler) {
1330
+ window.removeEventListener('beforeunload', this.beforeUnloadHandler);
1331
+ this.beforeUnloadHandler = null;
1332
+ }
1333
+ }
1334
+ }
1335
+
1336
+ // src/config.ts
1337
+ // Configuration loading and validation
1338
+ /** Default API URL when not specified */
1339
+ const DEFAULT_API_URL = 'https://api.astermind.ai';
1340
+ /**
1341
+ * Derive WebSocket URL from API URL for known SaaS domains.
1342
+ * Maps REST API domains to their WebSocket counterparts:
1343
+ * chatapi.astermind.ai → wss://chatws.astermind.ai
1344
+ * chatapi-dev.astermind.ai → wss://chatws-dev.astermind.ai
1345
+ * api.astermind.ai → wss://chatws.astermind.ai
1346
+ *
1347
+ * Returns undefined for non-SaaS (on-prem) URLs.
1348
+ */
1349
+ function deriveWsUrl(apiUrl) {
1350
+ try {
1351
+ const url = new URL(apiUrl);
1352
+ // chatapi[-env].astermind.ai → chatws[-env].astermind.ai
1353
+ const match = url.hostname.match(/^chatapi(-[\w]+)?\.astermind\.ai$/);
1354
+ if (match) {
1355
+ const envSuffix = match[1] || '';
1356
+ return `wss://chatws${envSuffix}.astermind.ai`;
1357
+ }
1358
+ // api.astermind.ai → chatws.astermind.ai (default SaaS)
1359
+ if (url.hostname === 'api.astermind.ai') {
1360
+ return 'wss://chatws.astermind.ai';
1361
+ }
1362
+ }
1363
+ catch {
1364
+ // Invalid URL, no WS derivation
1365
+ }
1366
+ return undefined;
1367
+ }
1368
+ /**
1369
+ * Try to load wsUrl from environment or globals.
1370
+ * Returns the first found wsUrl or undefined.
1371
+ */
1372
+ function loadWsUrl() {
1373
+ // Vite env var
1374
+ try {
1375
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1376
+ const importMeta = globalThis.import?.meta?.env;
1377
+ if (importMeta?.VITE_ASTERMIND_RAG_WS_URL) {
1378
+ return importMeta.VITE_ASTERMIND_RAG_WS_URL;
1379
+ }
1380
+ }
1381
+ catch { /* not available */ }
1382
+ // Node.js / CRA env var
1383
+ if (typeof process !== 'undefined' && process.env) {
1384
+ if (process.env.ASTERMIND_RAG_WS_URL)
1385
+ return process.env.ASTERMIND_RAG_WS_URL;
1386
+ if (process.env.REACT_APP_ASTERMIND_RAG_WS_URL)
1387
+ return process.env.REACT_APP_ASTERMIND_RAG_WS_URL;
1388
+ }
1389
+ // SSR-injected config
1390
+ if (typeof window !== 'undefined') {
1391
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1392
+ const injected = window.__ASTERMIND_CONFIG__;
1393
+ if (injected?.wsUrl)
1394
+ return injected.wsUrl;
1395
+ // Global config object
1396
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1397
+ const globalConfig = window.astermindConfig;
1398
+ if (globalConfig?.wsUrl)
1399
+ return globalConfig.wsUrl;
1400
+ }
1401
+ // Script data attribute
1402
+ if (typeof document !== 'undefined') {
1403
+ const script = document.querySelector('script[data-astermind-ws-url]');
1404
+ if (script) {
1405
+ const wsUrl = script.getAttribute('data-astermind-ws-url');
1406
+ if (wsUrl)
1407
+ return wsUrl;
1408
+ }
1409
+ }
1410
+ return undefined;
1411
+ }
1412
+ /**
1413
+ * Resolve the WebSocket URL for a given config.
1414
+ * Priority: explicit wsUrl → env var → auto-derived from apiUrl
1415
+ */
1416
+ function resolveWsUrl(config) {
1417
+ // Explicit wsUrl takes priority
1418
+ if (config.wsUrl)
1419
+ return config.wsUrl;
1420
+ // Don't auto-detect if transport is forced to REST
1421
+ if (config.transport === 'rest')
1422
+ return undefined;
1423
+ // Try environment / globals
1424
+ const envWsUrl = loadWsUrl();
1425
+ if (envWsUrl)
1426
+ return envWsUrl;
1427
+ // Auto-derive from apiUrl for known SaaS domains
1428
+ return deriveWsUrl(config.apiUrl);
1429
+ }
1430
+ /**
1431
+ * Validate configuration
1432
+ */
1433
+ function validateConfig(config) {
1434
+ if (!config || typeof config !== 'object') {
1435
+ throw new Error('Config must be an object');
1436
+ }
1437
+ const c = config;
1438
+ if (!c.apiUrl || typeof c.apiUrl !== 'string') {
1439
+ throw new Error('apiUrl is required and must be a string');
1440
+ }
1441
+ if (!c.apiKey || typeof c.apiKey !== 'string') {
1442
+ throw new Error('apiKey is required and must be a string');
1443
+ }
1444
+ if (!c.apiKey.startsWith('am_')) {
1445
+ throw new Error('apiKey must start with "am_"');
1446
+ }
1447
+ return true;
1448
+ }
1449
+ /**
1450
+ * Load config from Node.js process.env (for bundlers that replace process.env)
1451
+ */
1452
+ function loadFromProcessEnv() {
1453
+ // Check if process.env exists (Node.js or bundler-injected)
1454
+ if (typeof process === 'undefined' || !process.env) {
1455
+ return null;
1456
+ }
1457
+ // Check for ASTERMIND_RAG_* env vars (non-prefixed, for Node.js/server environments)
1458
+ const apiKey = process.env.ASTERMIND_RAG_API_KEY;
1459
+ const apiUrl = process.env.ASTERMIND_RAG_API_SERVER_URL;
1460
+ if (apiKey) {
1461
+ return {
1462
+ apiKey,
1463
+ apiUrl: apiUrl || DEFAULT_API_URL,
1464
+ _source: 'env'
1465
+ };
1466
+ }
1467
+ // Check for CRA-style REACT_APP_* env vars
1468
+ const craApiKey = process.env.REACT_APP_ASTERMIND_RAG_API_KEY;
1469
+ const craApiUrl = process.env.REACT_APP_ASTERMIND_RAG_API_SERVER_URL;
1470
+ if (craApiKey) {
1471
+ return {
1472
+ apiKey: craApiKey,
1473
+ apiUrl: craApiUrl || DEFAULT_API_URL,
1474
+ _source: 'env'
1475
+ };
1476
+ }
1477
+ return null;
1478
+ }
1479
+ /**
1480
+ * Load config from Vite's import.meta.env (browser environment)
1481
+ * Note: This only works at build time when Vite replaces the variables
1482
+ */
1483
+ function loadFromViteEnv() {
1484
+ // Check for window.__ASTERMIND_CONFIG__ (SSR-injected config)
1485
+ if (typeof window !== 'undefined') {
1486
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1487
+ const injected = window.__ASTERMIND_CONFIG__;
1488
+ if (injected && typeof injected === 'object' && injected.apiKey) {
1489
+ return {
1490
+ ...injected,
1491
+ apiUrl: injected.apiUrl || DEFAULT_API_URL,
1492
+ _source: 'vite'
1493
+ };
1494
+ }
1495
+ }
1496
+ // Check for Vite's import.meta.env (replaced at build time)
1497
+ // Note: TypeScript doesn't know about import.meta.env, so we use a try-catch
1498
+ try {
1499
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1500
+ const importMeta = globalThis.import?.meta?.env;
1501
+ if (importMeta) {
1502
+ const apiKey = importMeta.VITE_ASTERMIND_RAG_API_KEY;
1503
+ const apiUrl = importMeta.VITE_ASTERMIND_RAG_API_SERVER_URL;
1504
+ if (apiKey) {
1505
+ return {
1506
+ apiKey,
1507
+ apiUrl: apiUrl || DEFAULT_API_URL,
1508
+ _source: 'vite'
1509
+ };
1510
+ }
1511
+ }
1512
+ }
1513
+ catch {
1514
+ // import.meta not available in this environment
1515
+ }
1516
+ return null;
1517
+ }
1518
+ /**
1519
+ * Load config from window.astermindConfig global object
1520
+ */
1521
+ function loadFromGlobalObject() {
1522
+ if (typeof window === 'undefined') {
1523
+ return null;
1524
+ }
1525
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1526
+ const globalConfig = window.astermindConfig;
1527
+ if (globalConfig && typeof globalConfig === 'object' && globalConfig.apiKey) {
1528
+ return {
1529
+ ...globalConfig,
1530
+ apiUrl: globalConfig.apiUrl || DEFAULT_API_URL,
1531
+ _source: 'window'
1532
+ };
1533
+ }
1534
+ return null;
1535
+ }
1536
+ /**
1537
+ * Load config from script tag data attributes
1538
+ */
1539
+ function loadFromScriptAttributes() {
1540
+ if (typeof window === 'undefined' || typeof document === 'undefined') {
1541
+ return null;
1542
+ }
1543
+ const script = document.querySelector('script[data-astermind-key]');
1544
+ if (script) {
1545
+ const apiKey = script.getAttribute('data-astermind-key');
1546
+ if (apiKey) {
1547
+ return {
1548
+ apiKey,
1549
+ apiUrl: script.getAttribute('data-astermind-url') || DEFAULT_API_URL,
1550
+ _source: 'data-attr'
1551
+ };
1552
+ }
1553
+ }
1554
+ return null;
1555
+ }
1556
+ /**
1557
+ * Load config using priority-based fallback chain:
1558
+ * 1. Environment variables (process.env - for bundlers/Node.js)
1559
+ * 2. Vite environment variables (import.meta.env or window.__ASTERMIND_CONFIG__)
1560
+ * 3. Global object (window.astermindConfig)
1561
+ * 4. Script data attributes (data-astermind-key, data-astermind-url)
1562
+ *
1563
+ * @param options - Configuration options
1564
+ * @param options.throwOnMissingKey - If true (default), throws when no API key found. If false, returns null and logs a warning.
1565
+ * @returns Configuration object or null if not found and throwOnMissingKey is false
1566
+ */
1567
+ function loadConfig(options = {}) {
1568
+ const { throwOnMissingKey = true } = options;
1569
+ // Priority 1: Environment variables (Node.js/bundler)
1570
+ const envConfig = loadFromProcessEnv();
1571
+ if (envConfig) {
1572
+ return envConfig;
1573
+ }
1574
+ // Priority 2: Vite environment variables / SSR-injected config
1575
+ const viteConfig = loadFromViteEnv();
1576
+ if (viteConfig) {
1577
+ return viteConfig;
1578
+ }
1579
+ // Priority 3: Global object (window.astermindConfig)
1580
+ const globalConfig = loadFromGlobalObject();
1581
+ if (globalConfig) {
1582
+ validateConfig(globalConfig);
1583
+ return globalConfig;
1584
+ }
1585
+ // Priority 4: Script data attributes
1586
+ const scriptConfig = loadFromScriptAttributes();
1587
+ if (scriptConfig) {
1588
+ return scriptConfig;
1589
+ }
1590
+ // No config found
1591
+ if (throwOnMissingKey) {
1592
+ throw new Error('AsterMind API key is required. Configure using one of these methods:\n' +
1593
+ ' 1. Set VITE_ASTERMIND_RAG_API_KEY environment variable (Vite)\n' +
1594
+ ' 2. Set REACT_APP_ASTERMIND_RAG_API_KEY environment variable (CRA)\n' +
1595
+ ' 3. Set window.astermindConfig = { apiKey: "am_...", apiUrl: "..." }\n' +
1596
+ ' 4. Add data-astermind-key attribute to your script tag\n' +
1597
+ ' 5. Pass apiKey directly to createClient() or CyberneticClient constructor');
1598
+ }
1599
+ else {
1600
+ console.warn('[AsterMind] No API key found. Chatbot will not function until configured.');
1601
+ return null;
1602
+ }
1603
+ }
1604
+ /**
1605
+ * Export individual loaders for testing and advanced use cases
1606
+ */
1607
+ const configLoaders = {
1608
+ loadFromProcessEnv,
1609
+ loadFromViteEnv,
1610
+ loadFromGlobalObject,
1611
+ loadFromScriptAttributes
1612
+ };
1613
+
1017
1614
  // src/license/base64url.ts
1018
1615
  // Base64URL encoding/decoding utilities for JWT handling
1019
1616
  /**
@@ -1649,6 +2246,7 @@ async function createLicenseManager(config) {
1649
2246
  */
1650
2247
  class CyberneticClient {
1651
2248
  constructor(config) {
2249
+ this.wsTransport = null;
1652
2250
  this.status = 'connecting';
1653
2251
  this.lastError = null;
1654
2252
  // Maintenance mode tracking (ADR-200)
@@ -1663,10 +2261,15 @@ class CyberneticClient {
1663
2261
  this.omegaRAG = null;
1664
2262
  // Track if offline warning has been shown
1665
2263
  this.offlineWarningShown = false;
2264
+ // Resolve WebSocket URL (explicit → env → auto-derived from apiUrl)
2265
+ const wsUrl = resolveWsUrl(config);
2266
+ const transport = config.transport ?? 'auto';
1666
2267
  // Apply defaults
1667
2268
  this.config = {
1668
2269
  apiUrl: config.apiUrl,
1669
2270
  apiKey: config.apiKey,
2271
+ wsUrl,
2272
+ transport,
1670
2273
  fallback: {
1671
2274
  enabled: config.fallback?.enabled ?? true,
1672
2275
  cacheMaxAge: config.fallback?.cacheMaxAge ?? 86400000, // 24 hours
@@ -1709,6 +2312,11 @@ class CyberneticClient {
1709
2312
  }).catch(() => {
1710
2313
  // License verification errors are handled internally
1711
2314
  });
2315
+ // Initialize WebSocket transport if configured and not forced to REST
2316
+ if (wsUrl && transport !== 'rest' && typeof WebSocket !== 'undefined') {
2317
+ this.wsTransport = new WebSocketTransport(wsUrl, config.apiKey, config.websocket);
2318
+ console.log(`[Cybernetic] WebSocket transport enabled: ${wsUrl}`);
2319
+ }
1712
2320
  // Monitor connection status
1713
2321
  this.monitorConnection();
1714
2322
  // Pre-cache documents on init if enabled
@@ -2087,6 +2695,60 @@ class CyberneticClient {
2087
2695
  callbacks.onComplete?.(response);
2088
2696
  return;
2089
2697
  }
2698
+ // Try WebSocket transport first (if available and not forced to REST)
2699
+ if (this.wsTransport && this.config.transport !== 'rest') {
2700
+ try {
2701
+ await this.wsTransport.chatStream(message, {
2702
+ sessionId: options?.sessionId,
2703
+ context: options?.context,
2704
+ onToken: callbacks.onToken,
2705
+ onSources: callbacks.onSources,
2706
+ onComplete: (response) => {
2707
+ this.setStatus('online');
2708
+ // Process through license manager
2709
+ const processedReply = this.licenseManager.processResponse(response.reply);
2710
+ callbacks.onComplete?.({
2711
+ ...response,
2712
+ reply: processedReply
2713
+ });
2714
+ },
2715
+ onError: (error) => {
2716
+ // In 'auto' mode, fall back to SSE on WS error
2717
+ if (this.config.transport === 'auto') {
2718
+ console.warn('[Cybernetic] WebSocket error, falling back to SSE:', error.message);
2719
+ this.streamViaSSE(message, callbacks, options);
2720
+ }
2721
+ else {
2722
+ // 'websocket' mode — no fallback
2723
+ const normalizedError = this.normalizeError(error);
2724
+ this.config.onError(normalizedError);
2725
+ callbacks.onError?.(normalizedError);
2726
+ }
2727
+ }
2728
+ });
2729
+ return;
2730
+ }
2731
+ catch (error) {
2732
+ if (this.config.transport === 'websocket') {
2733
+ // Forced WebSocket mode — don't fall back
2734
+ const normalizedError = this.normalizeError(error);
2735
+ this.lastError = normalizedError;
2736
+ this.config.onError(normalizedError);
2737
+ callbacks.onError?.(normalizedError);
2738
+ return;
2739
+ }
2740
+ // 'auto' mode: fall through to SSE
2741
+ console.warn('[Cybernetic] WebSocket connect failed, using SSE fallback');
2742
+ }
2743
+ }
2744
+ // REST+SSE path (on-prem, or fallback from WebSocket)
2745
+ await this.streamViaSSE(message, callbacks, options);
2746
+ }
2747
+ /**
2748
+ * Stream chat via REST+SSE (original transport).
2749
+ * Used as the primary transport for on-prem, or as fallback for SaaS WebSocket failures.
2750
+ */
2751
+ async streamViaSSE(message, callbacks, options) {
2090
2752
  try {
2091
2753
  await this.apiClient.chatStream(message, {
2092
2754
  sessionId: options?.sessionId,
@@ -2170,6 +2832,16 @@ class CyberneticClient {
2170
2832
  await this.cache.clear();
2171
2833
  this.localRAG.reset();
2172
2834
  }
2835
+ /**
2836
+ * Clean up all resources (WebSocket connection, caches, event listeners).
2837
+ * Call this when the client is no longer needed to prevent memory leaks.
2838
+ */
2839
+ destroy() {
2840
+ if (this.wsTransport) {
2841
+ this.wsTransport.disconnect();
2842
+ this.wsTransport = null;
2843
+ }
2844
+ }
2173
2845
  /**
2174
2846
  * Manually check if backend is reachable
2175
2847
  */
@@ -2480,194 +3152,6 @@ class CyberneticClient {
2480
3152
  }
2481
3153
  }
2482
3154
 
2483
- // src/config.ts
2484
- // Configuration loading and validation
2485
- /** Default API URL when not specified */
2486
- const DEFAULT_API_URL = 'https://api.astermind.ai';
2487
- /**
2488
- * Validate configuration
2489
- */
2490
- function validateConfig(config) {
2491
- if (!config || typeof config !== 'object') {
2492
- throw new Error('Config must be an object');
2493
- }
2494
- const c = config;
2495
- if (!c.apiUrl || typeof c.apiUrl !== 'string') {
2496
- throw new Error('apiUrl is required and must be a string');
2497
- }
2498
- if (!c.apiKey || typeof c.apiKey !== 'string') {
2499
- throw new Error('apiKey is required and must be a string');
2500
- }
2501
- if (!c.apiKey.startsWith('am_')) {
2502
- throw new Error('apiKey must start with "am_"');
2503
- }
2504
- return true;
2505
- }
2506
- /**
2507
- * Load config from Node.js process.env (for bundlers that replace process.env)
2508
- */
2509
- function loadFromProcessEnv() {
2510
- // Check if process.env exists (Node.js or bundler-injected)
2511
- if (typeof process === 'undefined' || !process.env) {
2512
- return null;
2513
- }
2514
- // Check for ASTERMIND_RAG_* env vars (non-prefixed, for Node.js/server environments)
2515
- const apiKey = process.env.ASTERMIND_RAG_API_KEY;
2516
- const apiUrl = process.env.ASTERMIND_RAG_API_SERVER_URL;
2517
- if (apiKey) {
2518
- return {
2519
- apiKey,
2520
- apiUrl: apiUrl || DEFAULT_API_URL,
2521
- _source: 'env'
2522
- };
2523
- }
2524
- // Check for CRA-style REACT_APP_* env vars
2525
- const craApiKey = process.env.REACT_APP_ASTERMIND_RAG_API_KEY;
2526
- const craApiUrl = process.env.REACT_APP_ASTERMIND_RAG_API_SERVER_URL;
2527
- if (craApiKey) {
2528
- return {
2529
- apiKey: craApiKey,
2530
- apiUrl: craApiUrl || DEFAULT_API_URL,
2531
- _source: 'env'
2532
- };
2533
- }
2534
- return null;
2535
- }
2536
- /**
2537
- * Load config from Vite's import.meta.env (browser environment)
2538
- * Note: This only works at build time when Vite replaces the variables
2539
- */
2540
- function loadFromViteEnv() {
2541
- // Check for window.__ASTERMIND_CONFIG__ (SSR-injected config)
2542
- if (typeof window !== 'undefined') {
2543
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2544
- const injected = window.__ASTERMIND_CONFIG__;
2545
- if (injected && typeof injected === 'object' && injected.apiKey) {
2546
- return {
2547
- ...injected,
2548
- apiUrl: injected.apiUrl || DEFAULT_API_URL,
2549
- _source: 'vite'
2550
- };
2551
- }
2552
- }
2553
- // Check for Vite's import.meta.env (replaced at build time)
2554
- // Note: TypeScript doesn't know about import.meta.env, so we use a try-catch
2555
- try {
2556
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2557
- const importMeta = globalThis.import?.meta?.env;
2558
- if (importMeta) {
2559
- const apiKey = importMeta.VITE_ASTERMIND_RAG_API_KEY;
2560
- const apiUrl = importMeta.VITE_ASTERMIND_RAG_API_SERVER_URL;
2561
- if (apiKey) {
2562
- return {
2563
- apiKey,
2564
- apiUrl: apiUrl || DEFAULT_API_URL,
2565
- _source: 'vite'
2566
- };
2567
- }
2568
- }
2569
- }
2570
- catch {
2571
- // import.meta not available in this environment
2572
- }
2573
- return null;
2574
- }
2575
- /**
2576
- * Load config from window.astermindConfig global object
2577
- */
2578
- function loadFromGlobalObject() {
2579
- if (typeof window === 'undefined') {
2580
- return null;
2581
- }
2582
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2583
- const globalConfig = window.astermindConfig;
2584
- if (globalConfig && typeof globalConfig === 'object' && globalConfig.apiKey) {
2585
- return {
2586
- ...globalConfig,
2587
- apiUrl: globalConfig.apiUrl || DEFAULT_API_URL,
2588
- _source: 'window'
2589
- };
2590
- }
2591
- return null;
2592
- }
2593
- /**
2594
- * Load config from script tag data attributes
2595
- */
2596
- function loadFromScriptAttributes() {
2597
- if (typeof window === 'undefined' || typeof document === 'undefined') {
2598
- return null;
2599
- }
2600
- const script = document.querySelector('script[data-astermind-key]');
2601
- if (script) {
2602
- const apiKey = script.getAttribute('data-astermind-key');
2603
- if (apiKey) {
2604
- return {
2605
- apiKey,
2606
- apiUrl: script.getAttribute('data-astermind-url') || DEFAULT_API_URL,
2607
- _source: 'data-attr'
2608
- };
2609
- }
2610
- }
2611
- return null;
2612
- }
2613
- /**
2614
- * Load config using priority-based fallback chain:
2615
- * 1. Environment variables (process.env - for bundlers/Node.js)
2616
- * 2. Vite environment variables (import.meta.env or window.__ASTERMIND_CONFIG__)
2617
- * 3. Global object (window.astermindConfig)
2618
- * 4. Script data attributes (data-astermind-key, data-astermind-url)
2619
- *
2620
- * @param options - Configuration options
2621
- * @param options.throwOnMissingKey - If true (default), throws when no API key found. If false, returns null and logs a warning.
2622
- * @returns Configuration object or null if not found and throwOnMissingKey is false
2623
- */
2624
- function loadConfig(options = {}) {
2625
- const { throwOnMissingKey = true } = options;
2626
- // Priority 1: Environment variables (Node.js/bundler)
2627
- const envConfig = loadFromProcessEnv();
2628
- if (envConfig) {
2629
- return envConfig;
2630
- }
2631
- // Priority 2: Vite environment variables / SSR-injected config
2632
- const viteConfig = loadFromViteEnv();
2633
- if (viteConfig) {
2634
- return viteConfig;
2635
- }
2636
- // Priority 3: Global object (window.astermindConfig)
2637
- const globalConfig = loadFromGlobalObject();
2638
- if (globalConfig) {
2639
- validateConfig(globalConfig);
2640
- return globalConfig;
2641
- }
2642
- // Priority 4: Script data attributes
2643
- const scriptConfig = loadFromScriptAttributes();
2644
- if (scriptConfig) {
2645
- return scriptConfig;
2646
- }
2647
- // No config found
2648
- if (throwOnMissingKey) {
2649
- throw new Error('AsterMind API key is required. Configure using one of these methods:\n' +
2650
- ' 1. Set VITE_ASTERMIND_RAG_API_KEY environment variable (Vite)\n' +
2651
- ' 2. Set REACT_APP_ASTERMIND_RAG_API_KEY environment variable (CRA)\n' +
2652
- ' 3. Set window.astermindConfig = { apiKey: "am_...", apiUrl: "..." }\n' +
2653
- ' 4. Add data-astermind-key attribute to your script tag\n' +
2654
- ' 5. Pass apiKey directly to createClient() or CyberneticClient constructor');
2655
- }
2656
- else {
2657
- console.warn('[AsterMind] No API key found. Chatbot will not function until configured.');
2658
- return null;
2659
- }
2660
- }
2661
- /**
2662
- * Export individual loaders for testing and advanced use cases
2663
- */
2664
- const configLoaders = {
2665
- loadFromProcessEnv,
2666
- loadFromViteEnv,
2667
- loadFromGlobalObject,
2668
- loadFromScriptAttributes
2669
- };
2670
-
2671
3155
  // src/agentic/SiteMapDiscovery.ts
2672
3156
  // Multi-source sitemap discovery and merging for agentic navigation
2673
3157
  // Zero-config mode: automatically discovers routes on any site
@@ -6652,5 +7136,5 @@ function createClient(config) {
6652
7136
  return new CyberneticClient(config);
6653
7137
  }
6654
7138
 
6655
- export { ApiClient, CyberneticAgent, CyberneticCache, CyberneticClient, CyberneticIntentClassifier, CyberneticLocalRAG, CyberneticOfflineStorage, LicenseManager, OmegaOfflineRAG, REQUIRED_FEATURES, SiteMapDiscovery, configLoaders, createClient, createDiscoveryConfig, createLicenseManager, detectEnvironment, getEnforcementMode, getTokenExpiration, isValidJWTFormat, loadConfig, registerAgenticCapabilities, useSiteMapDiscovery, validateConfig, verifyLicenseToken };
7139
+ export { ApiClient, CyberneticAgent, CyberneticCache, CyberneticClient, CyberneticIntentClassifier, CyberneticLocalRAG, CyberneticOfflineStorage, LicenseManager, OmegaOfflineRAG, REQUIRED_FEATURES, SiteMapDiscovery, WebSocketTransport, configLoaders, createClient, createDiscoveryConfig, createLicenseManager, deriveWsUrl, detectEnvironment, getEnforcementMode, getTokenExpiration, isValidJWTFormat, loadConfig, registerAgenticCapabilities, resolveWsUrl, useSiteMapDiscovery, validateConfig, verifyLicenseToken };
6656
7140
  //# sourceMappingURL=cybernetic-chatbot-client.esm.js.map