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