@astermind/cybernetic-chatbot-client 2.2.36 → 2.2.48
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 +102 -5
- package/dist/ApiClient.d.ts +4 -3
- package/dist/ApiClient.d.ts.map +1 -1
- package/dist/CyberneticClient.d.ts +11 -0
- package/dist/CyberneticClient.d.ts.map +1 -1
- package/dist/WebSocketTransport.d.ts +104 -0
- package/dist/WebSocketTransport.d.ts.map +1 -0
- package/dist/config.d.ts +15 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/cybernetic-chatbot-client-full.esm.js +713 -188
- package/dist/cybernetic-chatbot-client-full.esm.js.map +1 -1
- package/dist/cybernetic-chatbot-client-full.min.js +1 -1
- package/dist/cybernetic-chatbot-client-full.min.js.map +1 -1
- package/dist/cybernetic-chatbot-client-full.umd.js +713 -188
- package/dist/cybernetic-chatbot-client-full.umd.js.map +1 -1
- package/dist/cybernetic-chatbot-client.esm.js +740 -215
- package/dist/cybernetic-chatbot-client.esm.js.map +1 -1
- package/dist/cybernetic-chatbot-client.min.js +1 -1
- package/dist/cybernetic-chatbot-client.min.js.map +1 -1
- package/dist/cybernetic-chatbot-client.umd.js +742 -214
- package/dist/cybernetic-chatbot-client.umd.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/types.d.ts +36 -3
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
|
@@ -4,13 +4,14 @@ import 'path';
|
|
|
4
4
|
// src/ApiClient.ts
|
|
5
5
|
// HTTP client for AsterMind backend API
|
|
6
6
|
/**
|
|
7
|
-
* Map backend source format to client Source interface
|
|
7
|
+
* Map backend source format to client Source interface.
|
|
8
|
+
* Handles both canonical (title/score) and legacy (heading/no-score) field names.
|
|
8
9
|
*/
|
|
9
10
|
function mapSource(raw) {
|
|
10
11
|
return {
|
|
11
|
-
title: raw.title,
|
|
12
|
-
snippet: raw.content,
|
|
13
|
-
relevance: raw.score,
|
|
12
|
+
title: raw.title || raw.heading || 'Document',
|
|
13
|
+
snippet: raw.content || '',
|
|
14
|
+
relevance: raw.score ?? 0,
|
|
14
15
|
documentId: raw.documentId,
|
|
15
16
|
fullContent: raw.fullContent,
|
|
16
17
|
downloadUrl: raw.downloadUrl,
|
|
@@ -48,9 +49,10 @@ class ApiClient {
|
|
|
48
49
|
throw new Error(error.message || `HTTP ${response.status}: ${response.statusText}`);
|
|
49
50
|
}
|
|
50
51
|
const data = await response.json();
|
|
51
|
-
//
|
|
52
|
+
// Normalize response: accept both 'reply' (canonical) and 'answer' (legacy)
|
|
52
53
|
return {
|
|
53
54
|
...data,
|
|
55
|
+
reply: data.reply || data.answer || '',
|
|
54
56
|
sources: (data.sources || []).map(mapSource)
|
|
55
57
|
};
|
|
56
58
|
}
|
|
@@ -126,7 +128,8 @@ class ApiClient {
|
|
|
126
128
|
}
|
|
127
129
|
}
|
|
128
130
|
/**
|
|
129
|
-
* Get general documents for caching
|
|
131
|
+
* Get general documents for caching.
|
|
132
|
+
* Normalizes field names from both canonical (title) and legacy (name) formats.
|
|
130
133
|
*/
|
|
131
134
|
async getGeneralDocs(since) {
|
|
132
135
|
const params = new URLSearchParams();
|
|
@@ -143,10 +146,16 @@ class ApiClient {
|
|
|
143
146
|
throw new Error(`HTTP ${response.status}`);
|
|
144
147
|
}
|
|
145
148
|
const data = await response.json();
|
|
146
|
-
|
|
149
|
+
// Normalize: accept both 'title' (canonical) and 'name' (legacy on-prem)
|
|
150
|
+
return (data.documents || []).map((doc) => ({
|
|
151
|
+
id: doc.id,
|
|
152
|
+
title: doc.title || doc.name || 'Untitled',
|
|
153
|
+
updatedAt: doc.updatedAt || doc.updated_at || new Date().toISOString(),
|
|
154
|
+
}));
|
|
147
155
|
}
|
|
148
156
|
/**
|
|
149
|
-
* Get API status, quota, and system settings
|
|
157
|
+
* Get API status, quota, and system settings.
|
|
158
|
+
* Normalizes response from both canonical and legacy backend formats.
|
|
150
159
|
*/
|
|
151
160
|
async getStatus() {
|
|
152
161
|
const response = await fetch(`${this.baseUrl}/api/external/status`, {
|
|
@@ -157,7 +166,38 @@ class ApiClient {
|
|
|
157
166
|
if (!response.ok) {
|
|
158
167
|
throw new Error(`HTTP ${response.status}`);
|
|
159
168
|
}
|
|
160
|
-
|
|
169
|
+
const data = await response.json();
|
|
170
|
+
// Normalize: accept both canonical (apiKey) and legacy (key) structures
|
|
171
|
+
const apiKeyData = data.apiKey || data.key || {};
|
|
172
|
+
const scopes = apiKeyData.scopes || apiKeyData.permissions || ['chat'];
|
|
173
|
+
// Normalize quota: accept both canonical (perMinute/perDay) and legacy structures
|
|
174
|
+
const quota = data.quota || {};
|
|
175
|
+
const perMinute = quota.perMinute || {
|
|
176
|
+
limit: apiKeyData.rateLimit?.limit || quota.rateLimitPerMinute || 30,
|
|
177
|
+
remaining: apiKeyData.rateLimit?.remaining ?? quota.rateLimitPerMinute ?? 30,
|
|
178
|
+
};
|
|
179
|
+
const perDay = quota.perDay || {
|
|
180
|
+
limit: quota.rateLimitPerDay || perMinute.limit * 60 * 24,
|
|
181
|
+
remaining: quota.rateLimitPerDay || perMinute.limit * 60 * 24,
|
|
182
|
+
};
|
|
183
|
+
// Normalize systemSettings: accept both canonical and legacy (system) structures
|
|
184
|
+
const settings = data.systemSettings || data.system || {};
|
|
185
|
+
const cacheRetentionHours = settings.cacheRetentionHours ??
|
|
186
|
+
(settings.cacheRetentionDays ? settings.cacheRetentionDays * 24 : undefined);
|
|
187
|
+
return {
|
|
188
|
+
status: data.status || 'active',
|
|
189
|
+
apiKey: {
|
|
190
|
+
id: apiKeyData.id || '',
|
|
191
|
+
scopes,
|
|
192
|
+
},
|
|
193
|
+
quota: { perMinute, perDay },
|
|
194
|
+
systemSettings: {
|
|
195
|
+
cacheRetentionHours: cacheRetentionHours ?? 720,
|
|
196
|
+
maintenanceMode: settings.maintenanceMode ?? false,
|
|
197
|
+
maintenanceMessage: settings.maintenanceMessage,
|
|
198
|
+
forceOfflineClients: settings.forceOfflineClients ?? false,
|
|
199
|
+
},
|
|
200
|
+
};
|
|
161
201
|
}
|
|
162
202
|
/**
|
|
163
203
|
* Health check (no auth required)
|
|
@@ -1013,6 +1053,595 @@ class CyberneticOfflineStorage {
|
|
|
1013
1053
|
}
|
|
1014
1054
|
}
|
|
1015
1055
|
|
|
1056
|
+
// src/WebSocketTransport.ts
|
|
1057
|
+
// WebSocket transport for streaming chat via SaaS WebSocket API (chatws.astermind.ai)
|
|
1058
|
+
/**
|
|
1059
|
+
* WebSocket transport for streaming chat.
|
|
1060
|
+
*
|
|
1061
|
+
* Maps the chat-handler Lambda WebSocket protocol to the client's StreamCallbacks:
|
|
1062
|
+
* Server typing → ignored (UI has its own indicator)
|
|
1063
|
+
* Server chunk → onToken(content)
|
|
1064
|
+
* Server done → onSources(sources) + onComplete(response)
|
|
1065
|
+
* Server error → onError(error)
|
|
1066
|
+
*
|
|
1067
|
+
* Connection is lazy — established on the first chatStream() call.
|
|
1068
|
+
* Reuses the same connection across multiple messages.
|
|
1069
|
+
* Reconnects with exponential backoff on close/error.
|
|
1070
|
+
*/
|
|
1071
|
+
class WebSocketTransport {
|
|
1072
|
+
constructor(wsUrl, apiKey, options) {
|
|
1073
|
+
this.ws = null;
|
|
1074
|
+
this.state = 'disconnected';
|
|
1075
|
+
this.reconnectAttempts = 0;
|
|
1076
|
+
this.connectionPromise = null;
|
|
1077
|
+
// Active streaming request tracking
|
|
1078
|
+
this.activeCallbacks = null;
|
|
1079
|
+
this.activeFullText = '';
|
|
1080
|
+
// Cleanup handler reference
|
|
1081
|
+
this.beforeUnloadHandler = null;
|
|
1082
|
+
// Promise callbacks for the active stream
|
|
1083
|
+
this._resolveStream = null;
|
|
1084
|
+
this._rejectStream = null;
|
|
1085
|
+
this.wsUrl = wsUrl;
|
|
1086
|
+
this.apiKey = apiKey;
|
|
1087
|
+
this.maxReconnectAttempts = options?.maxReconnectAttempts ?? 3;
|
|
1088
|
+
this.reconnectDelay = options?.reconnectDelay ?? 1000;
|
|
1089
|
+
this.connectionTimeout = options?.connectionTimeout ?? 10000;
|
|
1090
|
+
}
|
|
1091
|
+
/**
|
|
1092
|
+
* Current transport state
|
|
1093
|
+
*/
|
|
1094
|
+
getState() {
|
|
1095
|
+
return this.state;
|
|
1096
|
+
}
|
|
1097
|
+
/**
|
|
1098
|
+
* Whether the WebSocket is currently connected
|
|
1099
|
+
*/
|
|
1100
|
+
isConnected() {
|
|
1101
|
+
return this.state === 'connected' && this.ws?.readyState === WebSocket.OPEN;
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* Connect to the WebSocket endpoint.
|
|
1105
|
+
* Appends the API key as a query parameter for authentication.
|
|
1106
|
+
* Returns a promise that resolves when the connection is open.
|
|
1107
|
+
*/
|
|
1108
|
+
connect() {
|
|
1109
|
+
// Already connected
|
|
1110
|
+
if (this.isConnected()) {
|
|
1111
|
+
return Promise.resolve();
|
|
1112
|
+
}
|
|
1113
|
+
// Connection already in progress
|
|
1114
|
+
if (this.connectionPromise) {
|
|
1115
|
+
return this.connectionPromise;
|
|
1116
|
+
}
|
|
1117
|
+
this.state = 'connecting';
|
|
1118
|
+
this.connectionPromise = new Promise((resolve, reject) => {
|
|
1119
|
+
try {
|
|
1120
|
+
// Build URL with API key
|
|
1121
|
+
const separator = this.wsUrl.includes('?') ? '&' : '?';
|
|
1122
|
+
const fullUrl = `${this.wsUrl}${separator}apiKey=${encodeURIComponent(this.apiKey)}`;
|
|
1123
|
+
const ws = new WebSocket(fullUrl);
|
|
1124
|
+
this.ws = ws;
|
|
1125
|
+
// Connection timeout
|
|
1126
|
+
const timeout = setTimeout(() => {
|
|
1127
|
+
if (ws.readyState !== WebSocket.OPEN) {
|
|
1128
|
+
ws.close();
|
|
1129
|
+
this.state = 'error';
|
|
1130
|
+
this.connectionPromise = null;
|
|
1131
|
+
reject(new Error('WebSocket connection timed out'));
|
|
1132
|
+
}
|
|
1133
|
+
}, this.connectionTimeout);
|
|
1134
|
+
ws.onopen = () => {
|
|
1135
|
+
clearTimeout(timeout);
|
|
1136
|
+
this.state = 'connected';
|
|
1137
|
+
this.reconnectAttempts = 0;
|
|
1138
|
+
this.connectionPromise = null;
|
|
1139
|
+
this.registerCleanup();
|
|
1140
|
+
resolve();
|
|
1141
|
+
};
|
|
1142
|
+
ws.onmessage = (event) => {
|
|
1143
|
+
this.handleMessage(event);
|
|
1144
|
+
};
|
|
1145
|
+
ws.onerror = () => {
|
|
1146
|
+
clearTimeout(timeout);
|
|
1147
|
+
this.state = 'error';
|
|
1148
|
+
this.connectionPromise = null;
|
|
1149
|
+
// The close event fires after error, which will trigger reconnect
|
|
1150
|
+
};
|
|
1151
|
+
ws.onclose = (event) => {
|
|
1152
|
+
clearTimeout(timeout);
|
|
1153
|
+
const wasConnected = this.state === 'connected';
|
|
1154
|
+
this.state = 'disconnected';
|
|
1155
|
+
this.connectionPromise = null;
|
|
1156
|
+
this.unregisterCleanup();
|
|
1157
|
+
// If we had an active request, report the error
|
|
1158
|
+
if (this.activeCallbacks) {
|
|
1159
|
+
this.activeCallbacks.onError?.({
|
|
1160
|
+
code: 'WS_ERROR',
|
|
1161
|
+
message: event.reason || `WebSocket closed (code: ${event.code})`
|
|
1162
|
+
});
|
|
1163
|
+
this.clearActiveRequest();
|
|
1164
|
+
}
|
|
1165
|
+
// Reject if we were trying to connect
|
|
1166
|
+
if (!wasConnected) {
|
|
1167
|
+
reject(new Error(event.reason || `WebSocket closed (code: ${event.code})`));
|
|
1168
|
+
}
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
catch (error) {
|
|
1172
|
+
this.state = 'error';
|
|
1173
|
+
this.connectionPromise = null;
|
|
1174
|
+
reject(error);
|
|
1175
|
+
}
|
|
1176
|
+
});
|
|
1177
|
+
return this.connectionPromise;
|
|
1178
|
+
}
|
|
1179
|
+
/**
|
|
1180
|
+
* Stream a chat message over WebSocket.
|
|
1181
|
+
*
|
|
1182
|
+
* Sends: { type: "sendMessage", message, sessionId?, wordLimit?, context? }
|
|
1183
|
+
* Receives: typing → chunk × N → done (with sources and metadata)
|
|
1184
|
+
*/
|
|
1185
|
+
async chatStream(message, options) {
|
|
1186
|
+
const { sessionId, context, wordLimit, onToken, onSources, onComplete, onError } = options;
|
|
1187
|
+
// Ensure connection is established (lazy connect)
|
|
1188
|
+
try {
|
|
1189
|
+
await this.connect();
|
|
1190
|
+
}
|
|
1191
|
+
catch (error) {
|
|
1192
|
+
onError?.({
|
|
1193
|
+
code: 'WS_ERROR',
|
|
1194
|
+
message: `Failed to connect: ${error instanceof Error ? error.message : String(error)}`
|
|
1195
|
+
});
|
|
1196
|
+
throw error;
|
|
1197
|
+
}
|
|
1198
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
1199
|
+
const err = { code: 'WS_ERROR', message: 'WebSocket not connected' };
|
|
1200
|
+
onError?.(err);
|
|
1201
|
+
throw new Error(err.message);
|
|
1202
|
+
}
|
|
1203
|
+
// Set up active request tracking
|
|
1204
|
+
this.activeCallbacks = { onToken, onSources, onComplete, onError };
|
|
1205
|
+
this.activeFullText = '';
|
|
1206
|
+
this.activeSessionId = sessionId;
|
|
1207
|
+
// Build and send the message
|
|
1208
|
+
const payload = {
|
|
1209
|
+
type: 'sendMessage',
|
|
1210
|
+
message,
|
|
1211
|
+
};
|
|
1212
|
+
if (sessionId)
|
|
1213
|
+
payload.sessionId = sessionId;
|
|
1214
|
+
if (wordLimit)
|
|
1215
|
+
payload.wordLimit = wordLimit;
|
|
1216
|
+
if (context)
|
|
1217
|
+
payload.context = context;
|
|
1218
|
+
// Return a promise that resolves when done/error is received
|
|
1219
|
+
return new Promise((resolve, reject) => {
|
|
1220
|
+
// Store resolve/reject so handleMessage can call them
|
|
1221
|
+
this._resolveStream = resolve;
|
|
1222
|
+
this._rejectStream = reject;
|
|
1223
|
+
this.ws.send(JSON.stringify(payload));
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
/**
|
|
1227
|
+
* Disconnect and clean up the WebSocket connection
|
|
1228
|
+
*/
|
|
1229
|
+
disconnect() {
|
|
1230
|
+
this.unregisterCleanup();
|
|
1231
|
+
if (this.ws) {
|
|
1232
|
+
// Remove handlers to avoid triggering reconnect
|
|
1233
|
+
this.ws.onclose = null;
|
|
1234
|
+
this.ws.onerror = null;
|
|
1235
|
+
this.ws.onmessage = null;
|
|
1236
|
+
this.ws.close();
|
|
1237
|
+
this.ws = null;
|
|
1238
|
+
}
|
|
1239
|
+
this.state = 'disconnected';
|
|
1240
|
+
this.connectionPromise = null;
|
|
1241
|
+
this.clearActiveRequest();
|
|
1242
|
+
}
|
|
1243
|
+
/**
|
|
1244
|
+
* Attempt reconnection with exponential backoff.
|
|
1245
|
+
* Used internally after connection loss.
|
|
1246
|
+
*/
|
|
1247
|
+
async reconnect() {
|
|
1248
|
+
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
1249
|
+
this.state = 'error';
|
|
1250
|
+
throw new Error(`Max reconnection attempts (${this.maxReconnectAttempts}) exceeded`);
|
|
1251
|
+
}
|
|
1252
|
+
const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts);
|
|
1253
|
+
this.reconnectAttempts++;
|
|
1254
|
+
console.log(`[Cybernetic WS] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
|
|
1255
|
+
await new Promise(resolve => setTimeout(resolve, delay));
|
|
1256
|
+
// Ensure old connection is cleaned up
|
|
1257
|
+
if (this.ws) {
|
|
1258
|
+
this.ws.onclose = null;
|
|
1259
|
+
this.ws.onerror = null;
|
|
1260
|
+
this.ws.close();
|
|
1261
|
+
this.ws = null;
|
|
1262
|
+
}
|
|
1263
|
+
return this.connect();
|
|
1264
|
+
}
|
|
1265
|
+
// ==================== INTERNAL ====================
|
|
1266
|
+
/**
|
|
1267
|
+
* Handle incoming WebSocket messages from the chat-handler Lambda.
|
|
1268
|
+
*
|
|
1269
|
+
* Protocol:
|
|
1270
|
+
* { type: 'typing', status: boolean } → ignored
|
|
1271
|
+
* { type: 'chunk', content: string } → onToken(content)
|
|
1272
|
+
* { type: 'done', sessionId, sources, metadata, messageId } → onSources + onComplete
|
|
1273
|
+
* { type: 'error', error: string } → onError
|
|
1274
|
+
*/
|
|
1275
|
+
handleMessage(event) {
|
|
1276
|
+
if (!this.activeCallbacks)
|
|
1277
|
+
return;
|
|
1278
|
+
try {
|
|
1279
|
+
const data = JSON.parse(event.data);
|
|
1280
|
+
switch (data.type) {
|
|
1281
|
+
case 'typing':
|
|
1282
|
+
// Ignored — the chatbot-template manages its own typing indicator
|
|
1283
|
+
break;
|
|
1284
|
+
case 'chunk':
|
|
1285
|
+
if (data.content) {
|
|
1286
|
+
this.activeFullText += data.content;
|
|
1287
|
+
this.activeCallbacks.onToken?.(data.content);
|
|
1288
|
+
}
|
|
1289
|
+
break;
|
|
1290
|
+
case 'done': {
|
|
1291
|
+
// Map sources from chat-handler format to client Source format
|
|
1292
|
+
const sources = this.mapSources(data.sources || []);
|
|
1293
|
+
// Emit sources
|
|
1294
|
+
this.activeCallbacks.onSources?.(sources);
|
|
1295
|
+
// Build complete response
|
|
1296
|
+
const response = {
|
|
1297
|
+
reply: this.activeFullText,
|
|
1298
|
+
confidence: 'high',
|
|
1299
|
+
sources,
|
|
1300
|
+
offline: false,
|
|
1301
|
+
sessionId: data.sessionId || this.activeSessionId,
|
|
1302
|
+
};
|
|
1303
|
+
this.activeCallbacks.onComplete?.(response);
|
|
1304
|
+
this._resolveStream?.();
|
|
1305
|
+
this.clearActiveRequest();
|
|
1306
|
+
break;
|
|
1307
|
+
}
|
|
1308
|
+
case 'error': {
|
|
1309
|
+
const err = {
|
|
1310
|
+
code: 'WS_ERROR',
|
|
1311
|
+
message: data.error || 'Unknown WebSocket error'
|
|
1312
|
+
};
|
|
1313
|
+
this.activeCallbacks.onError?.(err);
|
|
1314
|
+
this._rejectStream?.(new Error(err.message));
|
|
1315
|
+
this.clearActiveRequest();
|
|
1316
|
+
break;
|
|
1317
|
+
}
|
|
1318
|
+
default:
|
|
1319
|
+
// Unknown message type — log and ignore
|
|
1320
|
+
console.warn('[Cybernetic WS] Unknown message type:', data.type);
|
|
1321
|
+
break;
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
catch (error) {
|
|
1325
|
+
console.error('[Cybernetic WS] Failed to parse message:', error, event.data);
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
/**
|
|
1329
|
+
* Map sources from the chat-handler WebSocket format to the client Source interface.
|
|
1330
|
+
*
|
|
1331
|
+
* Chat-handler sends: { heading, content, score, documentId, documentName }
|
|
1332
|
+
* Client expects: { title, snippet, relevance, documentId, documentName }
|
|
1333
|
+
*/
|
|
1334
|
+
mapSources(wsSources) {
|
|
1335
|
+
if (!Array.isArray(wsSources))
|
|
1336
|
+
return [];
|
|
1337
|
+
return wsSources.map((s) => ({
|
|
1338
|
+
title: s.title || s.heading || s.documentName || 'Document',
|
|
1339
|
+
snippet: s.content || '',
|
|
1340
|
+
relevance: s.score ?? 0,
|
|
1341
|
+
documentId: s.documentId,
|
|
1342
|
+
documentName: s.documentName,
|
|
1343
|
+
sourceType: s.sourceType || 'document',
|
|
1344
|
+
chunkId: s.chunkId,
|
|
1345
|
+
}));
|
|
1346
|
+
}
|
|
1347
|
+
/**
|
|
1348
|
+
* Clear active request state after completion or error
|
|
1349
|
+
*/
|
|
1350
|
+
clearActiveRequest() {
|
|
1351
|
+
this.activeCallbacks = null;
|
|
1352
|
+
this.activeFullText = '';
|
|
1353
|
+
this._resolveStream = null;
|
|
1354
|
+
this._rejectStream = null;
|
|
1355
|
+
}
|
|
1356
|
+
/**
|
|
1357
|
+
* Register a beforeunload handler to close the WebSocket on page unload
|
|
1358
|
+
*/
|
|
1359
|
+
registerCleanup() {
|
|
1360
|
+
if (typeof window !== 'undefined' && !this.beforeUnloadHandler) {
|
|
1361
|
+
this.beforeUnloadHandler = () => this.disconnect();
|
|
1362
|
+
window.addEventListener('beforeunload', this.beforeUnloadHandler);
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
/**
|
|
1366
|
+
* Remove the beforeunload handler
|
|
1367
|
+
*/
|
|
1368
|
+
unregisterCleanup() {
|
|
1369
|
+
if (typeof window !== 'undefined' && this.beforeUnloadHandler) {
|
|
1370
|
+
window.removeEventListener('beforeunload', this.beforeUnloadHandler);
|
|
1371
|
+
this.beforeUnloadHandler = null;
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
// src/config.ts
|
|
1377
|
+
// Configuration loading and validation
|
|
1378
|
+
/** Default API URL when not specified */
|
|
1379
|
+
const DEFAULT_API_URL = 'https://api.astermind.ai';
|
|
1380
|
+
/**
|
|
1381
|
+
* Derive WebSocket URL from API URL for known SaaS domains.
|
|
1382
|
+
* Maps REST API domains to their WebSocket counterparts:
|
|
1383
|
+
* chatapi.astermind.ai → wss://chatws.astermind.ai
|
|
1384
|
+
* chatapi-dev.astermind.ai → wss://chatws-dev.astermind.ai
|
|
1385
|
+
* api.astermind.ai → wss://chatws.astermind.ai
|
|
1386
|
+
*
|
|
1387
|
+
* Returns undefined for non-SaaS (on-prem) URLs.
|
|
1388
|
+
*/
|
|
1389
|
+
function deriveWsUrl(apiUrl) {
|
|
1390
|
+
try {
|
|
1391
|
+
const url = new URL(apiUrl);
|
|
1392
|
+
// chatapi[-env].astermind.ai → chatws[-env].astermind.ai
|
|
1393
|
+
const match = url.hostname.match(/^chatapi(-[\w]+)?\.astermind\.ai$/);
|
|
1394
|
+
if (match) {
|
|
1395
|
+
const envSuffix = match[1] || '';
|
|
1396
|
+
return `wss://chatws${envSuffix}.astermind.ai`;
|
|
1397
|
+
}
|
|
1398
|
+
// api.astermind.ai → chatws.astermind.ai (default SaaS)
|
|
1399
|
+
if (url.hostname === 'api.astermind.ai') {
|
|
1400
|
+
return 'wss://chatws.astermind.ai';
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
catch {
|
|
1404
|
+
// Invalid URL, no WS derivation
|
|
1405
|
+
}
|
|
1406
|
+
return undefined;
|
|
1407
|
+
}
|
|
1408
|
+
/**
|
|
1409
|
+
* Try to load wsUrl from environment or globals.
|
|
1410
|
+
* Returns the first found wsUrl or undefined.
|
|
1411
|
+
*/
|
|
1412
|
+
function loadWsUrl() {
|
|
1413
|
+
// Vite env var
|
|
1414
|
+
try {
|
|
1415
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1416
|
+
const importMeta = globalThis.import?.meta?.env;
|
|
1417
|
+
if (importMeta?.VITE_ASTERMIND_RAG_WS_URL) {
|
|
1418
|
+
return importMeta.VITE_ASTERMIND_RAG_WS_URL;
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
catch { /* not available */ }
|
|
1422
|
+
// Node.js / CRA env var
|
|
1423
|
+
if (typeof process !== 'undefined' && process.env) {
|
|
1424
|
+
if (process.env.ASTERMIND_RAG_WS_URL)
|
|
1425
|
+
return process.env.ASTERMIND_RAG_WS_URL;
|
|
1426
|
+
if (process.env.REACT_APP_ASTERMIND_RAG_WS_URL)
|
|
1427
|
+
return process.env.REACT_APP_ASTERMIND_RAG_WS_URL;
|
|
1428
|
+
}
|
|
1429
|
+
// SSR-injected config
|
|
1430
|
+
if (typeof window !== 'undefined') {
|
|
1431
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1432
|
+
const injected = window.__ASTERMIND_CONFIG__;
|
|
1433
|
+
if (injected?.wsUrl)
|
|
1434
|
+
return injected.wsUrl;
|
|
1435
|
+
// Global config object
|
|
1436
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1437
|
+
const globalConfig = window.astermindConfig;
|
|
1438
|
+
if (globalConfig?.wsUrl)
|
|
1439
|
+
return globalConfig.wsUrl;
|
|
1440
|
+
}
|
|
1441
|
+
// Script data attribute
|
|
1442
|
+
if (typeof document !== 'undefined') {
|
|
1443
|
+
const script = document.querySelector('script[data-astermind-ws-url]');
|
|
1444
|
+
if (script) {
|
|
1445
|
+
const wsUrl = script.getAttribute('data-astermind-ws-url');
|
|
1446
|
+
if (wsUrl)
|
|
1447
|
+
return wsUrl;
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
return undefined;
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* Resolve the WebSocket URL for a given config.
|
|
1454
|
+
* Priority: explicit wsUrl → env var → auto-derived from apiUrl
|
|
1455
|
+
*/
|
|
1456
|
+
function resolveWsUrl(config) {
|
|
1457
|
+
// Explicit wsUrl takes priority
|
|
1458
|
+
if (config.wsUrl)
|
|
1459
|
+
return config.wsUrl;
|
|
1460
|
+
// Don't auto-detect if transport is forced to REST
|
|
1461
|
+
if (config.transport === 'rest')
|
|
1462
|
+
return undefined;
|
|
1463
|
+
// Try environment / globals
|
|
1464
|
+
const envWsUrl = loadWsUrl();
|
|
1465
|
+
if (envWsUrl)
|
|
1466
|
+
return envWsUrl;
|
|
1467
|
+
// Auto-derive from apiUrl for known SaaS domains
|
|
1468
|
+
return deriveWsUrl(config.apiUrl);
|
|
1469
|
+
}
|
|
1470
|
+
/**
|
|
1471
|
+
* Validate configuration
|
|
1472
|
+
*/
|
|
1473
|
+
function validateConfig(config) {
|
|
1474
|
+
if (!config || typeof config !== 'object') {
|
|
1475
|
+
throw new Error('Config must be an object');
|
|
1476
|
+
}
|
|
1477
|
+
const c = config;
|
|
1478
|
+
if (!c.apiUrl || typeof c.apiUrl !== 'string') {
|
|
1479
|
+
throw new Error('apiUrl is required and must be a string');
|
|
1480
|
+
}
|
|
1481
|
+
if (!c.apiKey || typeof c.apiKey !== 'string') {
|
|
1482
|
+
throw new Error('apiKey is required and must be a string');
|
|
1483
|
+
}
|
|
1484
|
+
if (!c.apiKey.startsWith('am_')) {
|
|
1485
|
+
throw new Error('apiKey must start with "am_"');
|
|
1486
|
+
}
|
|
1487
|
+
return true;
|
|
1488
|
+
}
|
|
1489
|
+
/**
|
|
1490
|
+
* Load config from Node.js process.env (for bundlers that replace process.env)
|
|
1491
|
+
*/
|
|
1492
|
+
function loadFromProcessEnv() {
|
|
1493
|
+
// Check if process.env exists (Node.js or bundler-injected)
|
|
1494
|
+
if (typeof process === 'undefined' || !process.env) {
|
|
1495
|
+
return null;
|
|
1496
|
+
}
|
|
1497
|
+
// Check for ASTERMIND_RAG_* env vars (non-prefixed, for Node.js/server environments)
|
|
1498
|
+
const apiKey = process.env.ASTERMIND_RAG_API_KEY;
|
|
1499
|
+
const apiUrl = process.env.ASTERMIND_RAG_API_SERVER_URL;
|
|
1500
|
+
if (apiKey) {
|
|
1501
|
+
return {
|
|
1502
|
+
apiKey,
|
|
1503
|
+
apiUrl: apiUrl || DEFAULT_API_URL,
|
|
1504
|
+
_source: 'env'
|
|
1505
|
+
};
|
|
1506
|
+
}
|
|
1507
|
+
// Check for CRA-style REACT_APP_* env vars
|
|
1508
|
+
const craApiKey = process.env.REACT_APP_ASTERMIND_RAG_API_KEY;
|
|
1509
|
+
const craApiUrl = process.env.REACT_APP_ASTERMIND_RAG_API_SERVER_URL;
|
|
1510
|
+
if (craApiKey) {
|
|
1511
|
+
return {
|
|
1512
|
+
apiKey: craApiKey,
|
|
1513
|
+
apiUrl: craApiUrl || DEFAULT_API_URL,
|
|
1514
|
+
_source: 'env'
|
|
1515
|
+
};
|
|
1516
|
+
}
|
|
1517
|
+
return null;
|
|
1518
|
+
}
|
|
1519
|
+
/**
|
|
1520
|
+
* Load config from Vite's import.meta.env (browser environment)
|
|
1521
|
+
* Note: This only works at build time when Vite replaces the variables
|
|
1522
|
+
*/
|
|
1523
|
+
function loadFromViteEnv() {
|
|
1524
|
+
// Check for window.__ASTERMIND_CONFIG__ (SSR-injected config)
|
|
1525
|
+
if (typeof window !== 'undefined') {
|
|
1526
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1527
|
+
const injected = window.__ASTERMIND_CONFIG__;
|
|
1528
|
+
if (injected && typeof injected === 'object' && injected.apiKey) {
|
|
1529
|
+
return {
|
|
1530
|
+
...injected,
|
|
1531
|
+
apiUrl: injected.apiUrl || DEFAULT_API_URL,
|
|
1532
|
+
_source: 'vite'
|
|
1533
|
+
};
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
// Check for Vite's import.meta.env (replaced at build time)
|
|
1537
|
+
// Note: TypeScript doesn't know about import.meta.env, so we use a try-catch
|
|
1538
|
+
try {
|
|
1539
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1540
|
+
const importMeta = globalThis.import?.meta?.env;
|
|
1541
|
+
if (importMeta) {
|
|
1542
|
+
const apiKey = importMeta.VITE_ASTERMIND_RAG_API_KEY;
|
|
1543
|
+
const apiUrl = importMeta.VITE_ASTERMIND_RAG_API_SERVER_URL;
|
|
1544
|
+
if (apiKey) {
|
|
1545
|
+
return {
|
|
1546
|
+
apiKey,
|
|
1547
|
+
apiUrl: apiUrl || DEFAULT_API_URL,
|
|
1548
|
+
_source: 'vite'
|
|
1549
|
+
};
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
catch {
|
|
1554
|
+
// import.meta not available in this environment
|
|
1555
|
+
}
|
|
1556
|
+
return null;
|
|
1557
|
+
}
|
|
1558
|
+
/**
|
|
1559
|
+
* Load config from window.astermindConfig global object
|
|
1560
|
+
*/
|
|
1561
|
+
function loadFromGlobalObject() {
|
|
1562
|
+
if (typeof window === 'undefined') {
|
|
1563
|
+
return null;
|
|
1564
|
+
}
|
|
1565
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1566
|
+
const globalConfig = window.astermindConfig;
|
|
1567
|
+
if (globalConfig && typeof globalConfig === 'object' && globalConfig.apiKey) {
|
|
1568
|
+
return {
|
|
1569
|
+
...globalConfig,
|
|
1570
|
+
apiUrl: globalConfig.apiUrl || DEFAULT_API_URL,
|
|
1571
|
+
_source: 'window'
|
|
1572
|
+
};
|
|
1573
|
+
}
|
|
1574
|
+
return null;
|
|
1575
|
+
}
|
|
1576
|
+
/**
|
|
1577
|
+
* Load config from script tag data attributes
|
|
1578
|
+
*/
|
|
1579
|
+
function loadFromScriptAttributes() {
|
|
1580
|
+
if (typeof window === 'undefined' || typeof document === 'undefined') {
|
|
1581
|
+
return null;
|
|
1582
|
+
}
|
|
1583
|
+
const script = document.querySelector('script[data-astermind-key]');
|
|
1584
|
+
if (script) {
|
|
1585
|
+
const apiKey = script.getAttribute('data-astermind-key');
|
|
1586
|
+
if (apiKey) {
|
|
1587
|
+
return {
|
|
1588
|
+
apiKey,
|
|
1589
|
+
apiUrl: script.getAttribute('data-astermind-url') || DEFAULT_API_URL,
|
|
1590
|
+
_source: 'data-attr'
|
|
1591
|
+
};
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
return null;
|
|
1595
|
+
}
|
|
1596
|
+
/**
|
|
1597
|
+
* Load config using priority-based fallback chain:
|
|
1598
|
+
* 1. Environment variables (process.env - for bundlers/Node.js)
|
|
1599
|
+
* 2. Vite environment variables (import.meta.env or window.__ASTERMIND_CONFIG__)
|
|
1600
|
+
* 3. Global object (window.astermindConfig)
|
|
1601
|
+
* 4. Script data attributes (data-astermind-key, data-astermind-url)
|
|
1602
|
+
*
|
|
1603
|
+
* @param options - Configuration options
|
|
1604
|
+
* @param options.throwOnMissingKey - If true (default), throws when no API key found. If false, returns null and logs a warning.
|
|
1605
|
+
* @returns Configuration object or null if not found and throwOnMissingKey is false
|
|
1606
|
+
*/
|
|
1607
|
+
function loadConfig(options = {}) {
|
|
1608
|
+
const { throwOnMissingKey = true } = options;
|
|
1609
|
+
// Priority 1: Environment variables (Node.js/bundler)
|
|
1610
|
+
const envConfig = loadFromProcessEnv();
|
|
1611
|
+
if (envConfig) {
|
|
1612
|
+
return envConfig;
|
|
1613
|
+
}
|
|
1614
|
+
// Priority 2: Vite environment variables / SSR-injected config
|
|
1615
|
+
const viteConfig = loadFromViteEnv();
|
|
1616
|
+
if (viteConfig) {
|
|
1617
|
+
return viteConfig;
|
|
1618
|
+
}
|
|
1619
|
+
// Priority 3: Global object (window.astermindConfig)
|
|
1620
|
+
const globalConfig = loadFromGlobalObject();
|
|
1621
|
+
if (globalConfig) {
|
|
1622
|
+
validateConfig(globalConfig);
|
|
1623
|
+
return globalConfig;
|
|
1624
|
+
}
|
|
1625
|
+
// Priority 4: Script data attributes
|
|
1626
|
+
const scriptConfig = loadFromScriptAttributes();
|
|
1627
|
+
if (scriptConfig) {
|
|
1628
|
+
return scriptConfig;
|
|
1629
|
+
}
|
|
1630
|
+
// No config found
|
|
1631
|
+
if (throwOnMissingKey) {
|
|
1632
|
+
throw new Error('AsterMind API key is required. Configure using one of these methods:\n' +
|
|
1633
|
+
' 1. Set VITE_ASTERMIND_RAG_API_KEY environment variable (Vite)\n' +
|
|
1634
|
+
' 2. Set REACT_APP_ASTERMIND_RAG_API_KEY environment variable (CRA)\n' +
|
|
1635
|
+
' 3. Set window.astermindConfig = { apiKey: "am_...", apiUrl: "..." }\n' +
|
|
1636
|
+
' 4. Add data-astermind-key attribute to your script tag\n' +
|
|
1637
|
+
' 5. Pass apiKey directly to createClient() or CyberneticClient constructor');
|
|
1638
|
+
}
|
|
1639
|
+
else {
|
|
1640
|
+
console.warn('[AsterMind] No API key found. Chatbot will not function until configured.');
|
|
1641
|
+
return null;
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1016
1645
|
// src/license/base64url.ts
|
|
1017
1646
|
// Base64URL encoding/decoding utilities for JWT handling
|
|
1018
1647
|
/**
|
|
@@ -1648,6 +2277,7 @@ async function createLicenseManager(config) {
|
|
|
1648
2277
|
*/
|
|
1649
2278
|
class CyberneticClient {
|
|
1650
2279
|
constructor(config) {
|
|
2280
|
+
this.wsTransport = null;
|
|
1651
2281
|
this.status = 'connecting';
|
|
1652
2282
|
this.lastError = null;
|
|
1653
2283
|
// Maintenance mode tracking (ADR-200)
|
|
@@ -1662,10 +2292,15 @@ class CyberneticClient {
|
|
|
1662
2292
|
this.omegaRAG = null;
|
|
1663
2293
|
// Track if offline warning has been shown
|
|
1664
2294
|
this.offlineWarningShown = false;
|
|
2295
|
+
// Resolve WebSocket URL (explicit → env → auto-derived from apiUrl)
|
|
2296
|
+
const wsUrl = resolveWsUrl(config);
|
|
2297
|
+
const transport = config.transport ?? 'auto';
|
|
1665
2298
|
// Apply defaults
|
|
1666
2299
|
this.config = {
|
|
1667
2300
|
apiUrl: config.apiUrl,
|
|
1668
2301
|
apiKey: config.apiKey,
|
|
2302
|
+
wsUrl,
|
|
2303
|
+
transport,
|
|
1669
2304
|
fallback: {
|
|
1670
2305
|
enabled: config.fallback?.enabled ?? true,
|
|
1671
2306
|
cacheMaxAge: config.fallback?.cacheMaxAge ?? 86400000, // 24 hours
|
|
@@ -1708,6 +2343,11 @@ class CyberneticClient {
|
|
|
1708
2343
|
}).catch(() => {
|
|
1709
2344
|
// License verification errors are handled internally
|
|
1710
2345
|
});
|
|
2346
|
+
// Initialize WebSocket transport if configured and not forced to REST
|
|
2347
|
+
if (wsUrl && transport !== 'rest' && typeof WebSocket !== 'undefined') {
|
|
2348
|
+
this.wsTransport = new WebSocketTransport(wsUrl, config.apiKey, config.websocket);
|
|
2349
|
+
console.log(`[Cybernetic] WebSocket transport enabled: ${wsUrl}`);
|
|
2350
|
+
}
|
|
1711
2351
|
// Monitor connection status
|
|
1712
2352
|
this.monitorConnection();
|
|
1713
2353
|
// Pre-cache documents on init if enabled
|
|
@@ -2086,6 +2726,60 @@ class CyberneticClient {
|
|
|
2086
2726
|
callbacks.onComplete?.(response);
|
|
2087
2727
|
return;
|
|
2088
2728
|
}
|
|
2729
|
+
// Try WebSocket transport first (if available and not forced to REST)
|
|
2730
|
+
if (this.wsTransport && this.config.transport !== 'rest') {
|
|
2731
|
+
try {
|
|
2732
|
+
await this.wsTransport.chatStream(message, {
|
|
2733
|
+
sessionId: options?.sessionId,
|
|
2734
|
+
context: options?.context,
|
|
2735
|
+
onToken: callbacks.onToken,
|
|
2736
|
+
onSources: callbacks.onSources,
|
|
2737
|
+
onComplete: (response) => {
|
|
2738
|
+
this.setStatus('online');
|
|
2739
|
+
// Process through license manager
|
|
2740
|
+
const processedReply = this.licenseManager.processResponse(response.reply);
|
|
2741
|
+
callbacks.onComplete?.({
|
|
2742
|
+
...response,
|
|
2743
|
+
reply: processedReply
|
|
2744
|
+
});
|
|
2745
|
+
},
|
|
2746
|
+
onError: (error) => {
|
|
2747
|
+
// In 'auto' mode, fall back to SSE on WS error
|
|
2748
|
+
if (this.config.transport === 'auto') {
|
|
2749
|
+
console.warn('[Cybernetic] WebSocket error, falling back to SSE:', error.message);
|
|
2750
|
+
this.streamViaSSE(message, callbacks, options);
|
|
2751
|
+
}
|
|
2752
|
+
else {
|
|
2753
|
+
// 'websocket' mode — no fallback
|
|
2754
|
+
const normalizedError = this.normalizeError(error);
|
|
2755
|
+
this.config.onError(normalizedError);
|
|
2756
|
+
callbacks.onError?.(normalizedError);
|
|
2757
|
+
}
|
|
2758
|
+
}
|
|
2759
|
+
});
|
|
2760
|
+
return;
|
|
2761
|
+
}
|
|
2762
|
+
catch (error) {
|
|
2763
|
+
if (this.config.transport === 'websocket') {
|
|
2764
|
+
// Forced WebSocket mode — don't fall back
|
|
2765
|
+
const normalizedError = this.normalizeError(error);
|
|
2766
|
+
this.lastError = normalizedError;
|
|
2767
|
+
this.config.onError(normalizedError);
|
|
2768
|
+
callbacks.onError?.(normalizedError);
|
|
2769
|
+
return;
|
|
2770
|
+
}
|
|
2771
|
+
// 'auto' mode: fall through to SSE
|
|
2772
|
+
console.warn('[Cybernetic] WebSocket connect failed, using SSE fallback');
|
|
2773
|
+
}
|
|
2774
|
+
}
|
|
2775
|
+
// REST+SSE path (on-prem, or fallback from WebSocket)
|
|
2776
|
+
await this.streamViaSSE(message, callbacks, options);
|
|
2777
|
+
}
|
|
2778
|
+
/**
|
|
2779
|
+
* Stream chat via REST+SSE (original transport).
|
|
2780
|
+
* Used as the primary transport for on-prem, or as fallback for SaaS WebSocket failures.
|
|
2781
|
+
*/
|
|
2782
|
+
async streamViaSSE(message, callbacks, options) {
|
|
2089
2783
|
try {
|
|
2090
2784
|
await this.apiClient.chatStream(message, {
|
|
2091
2785
|
sessionId: options?.sessionId,
|
|
@@ -2169,6 +2863,16 @@ class CyberneticClient {
|
|
|
2169
2863
|
await this.cache.clear();
|
|
2170
2864
|
this.localRAG.reset();
|
|
2171
2865
|
}
|
|
2866
|
+
/**
|
|
2867
|
+
* Clean up all resources (WebSocket connection, caches, event listeners).
|
|
2868
|
+
* Call this when the client is no longer needed to prevent memory leaks.
|
|
2869
|
+
*/
|
|
2870
|
+
destroy() {
|
|
2871
|
+
if (this.wsTransport) {
|
|
2872
|
+
this.wsTransport.disconnect();
|
|
2873
|
+
this.wsTransport = null;
|
|
2874
|
+
}
|
|
2875
|
+
}
|
|
2172
2876
|
/**
|
|
2173
2877
|
* Manually check if backend is reachable
|
|
2174
2878
|
*/
|
|
@@ -2479,185 +3183,6 @@ class CyberneticClient {
|
|
|
2479
3183
|
}
|
|
2480
3184
|
}
|
|
2481
3185
|
|
|
2482
|
-
// src/config.ts
|
|
2483
|
-
// Configuration loading and validation
|
|
2484
|
-
/** Default API URL when not specified */
|
|
2485
|
-
const DEFAULT_API_URL = 'https://api.astermind.ai';
|
|
2486
|
-
/**
|
|
2487
|
-
* Validate configuration
|
|
2488
|
-
*/
|
|
2489
|
-
function validateConfig(config) {
|
|
2490
|
-
if (!config || typeof config !== 'object') {
|
|
2491
|
-
throw new Error('Config must be an object');
|
|
2492
|
-
}
|
|
2493
|
-
const c = config;
|
|
2494
|
-
if (!c.apiUrl || typeof c.apiUrl !== 'string') {
|
|
2495
|
-
throw new Error('apiUrl is required and must be a string');
|
|
2496
|
-
}
|
|
2497
|
-
if (!c.apiKey || typeof c.apiKey !== 'string') {
|
|
2498
|
-
throw new Error('apiKey is required and must be a string');
|
|
2499
|
-
}
|
|
2500
|
-
if (!c.apiKey.startsWith('am_')) {
|
|
2501
|
-
throw new Error('apiKey must start with "am_"');
|
|
2502
|
-
}
|
|
2503
|
-
return true;
|
|
2504
|
-
}
|
|
2505
|
-
/**
|
|
2506
|
-
* Load config from Node.js process.env (for bundlers that replace process.env)
|
|
2507
|
-
*/
|
|
2508
|
-
function loadFromProcessEnv() {
|
|
2509
|
-
// Check if process.env exists (Node.js or bundler-injected)
|
|
2510
|
-
if (typeof process === 'undefined' || !process.env) {
|
|
2511
|
-
return null;
|
|
2512
|
-
}
|
|
2513
|
-
// Check for ASTERMIND_RAG_* env vars (non-prefixed, for Node.js/server environments)
|
|
2514
|
-
const apiKey = process.env.ASTERMIND_RAG_API_KEY;
|
|
2515
|
-
const apiUrl = process.env.ASTERMIND_RAG_API_SERVER_URL;
|
|
2516
|
-
if (apiKey) {
|
|
2517
|
-
return {
|
|
2518
|
-
apiKey,
|
|
2519
|
-
apiUrl: apiUrl || DEFAULT_API_URL,
|
|
2520
|
-
_source: 'env'
|
|
2521
|
-
};
|
|
2522
|
-
}
|
|
2523
|
-
// Check for CRA-style REACT_APP_* env vars
|
|
2524
|
-
const craApiKey = process.env.REACT_APP_ASTERMIND_RAG_API_KEY;
|
|
2525
|
-
const craApiUrl = process.env.REACT_APP_ASTERMIND_RAG_API_SERVER_URL;
|
|
2526
|
-
if (craApiKey) {
|
|
2527
|
-
return {
|
|
2528
|
-
apiKey: craApiKey,
|
|
2529
|
-
apiUrl: craApiUrl || DEFAULT_API_URL,
|
|
2530
|
-
_source: 'env'
|
|
2531
|
-
};
|
|
2532
|
-
}
|
|
2533
|
-
return null;
|
|
2534
|
-
}
|
|
2535
|
-
/**
|
|
2536
|
-
* Load config from Vite's import.meta.env (browser environment)
|
|
2537
|
-
* Note: This only works at build time when Vite replaces the variables
|
|
2538
|
-
*/
|
|
2539
|
-
function loadFromViteEnv() {
|
|
2540
|
-
// Check for window.__ASTERMIND_CONFIG__ (SSR-injected config)
|
|
2541
|
-
if (typeof window !== 'undefined') {
|
|
2542
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2543
|
-
const injected = window.__ASTERMIND_CONFIG__;
|
|
2544
|
-
if (injected && typeof injected === 'object' && injected.apiKey) {
|
|
2545
|
-
return {
|
|
2546
|
-
...injected,
|
|
2547
|
-
apiUrl: injected.apiUrl || DEFAULT_API_URL,
|
|
2548
|
-
_source: 'vite'
|
|
2549
|
-
};
|
|
2550
|
-
}
|
|
2551
|
-
}
|
|
2552
|
-
// Check for Vite's import.meta.env (replaced at build time)
|
|
2553
|
-
// Note: TypeScript doesn't know about import.meta.env, so we use a try-catch
|
|
2554
|
-
try {
|
|
2555
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2556
|
-
const importMeta = globalThis.import?.meta?.env;
|
|
2557
|
-
if (importMeta) {
|
|
2558
|
-
const apiKey = importMeta.VITE_ASTERMIND_RAG_API_KEY;
|
|
2559
|
-
const apiUrl = importMeta.VITE_ASTERMIND_RAG_API_SERVER_URL;
|
|
2560
|
-
if (apiKey) {
|
|
2561
|
-
return {
|
|
2562
|
-
apiKey,
|
|
2563
|
-
apiUrl: apiUrl || DEFAULT_API_URL,
|
|
2564
|
-
_source: 'vite'
|
|
2565
|
-
};
|
|
2566
|
-
}
|
|
2567
|
-
}
|
|
2568
|
-
}
|
|
2569
|
-
catch {
|
|
2570
|
-
// import.meta not available in this environment
|
|
2571
|
-
}
|
|
2572
|
-
return null;
|
|
2573
|
-
}
|
|
2574
|
-
/**
|
|
2575
|
-
* Load config from window.astermindConfig global object
|
|
2576
|
-
*/
|
|
2577
|
-
function loadFromGlobalObject() {
|
|
2578
|
-
if (typeof window === 'undefined') {
|
|
2579
|
-
return null;
|
|
2580
|
-
}
|
|
2581
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2582
|
-
const globalConfig = window.astermindConfig;
|
|
2583
|
-
if (globalConfig && typeof globalConfig === 'object' && globalConfig.apiKey) {
|
|
2584
|
-
return {
|
|
2585
|
-
...globalConfig,
|
|
2586
|
-
apiUrl: globalConfig.apiUrl || DEFAULT_API_URL,
|
|
2587
|
-
_source: 'window'
|
|
2588
|
-
};
|
|
2589
|
-
}
|
|
2590
|
-
return null;
|
|
2591
|
-
}
|
|
2592
|
-
/**
|
|
2593
|
-
* Load config from script tag data attributes
|
|
2594
|
-
*/
|
|
2595
|
-
function loadFromScriptAttributes() {
|
|
2596
|
-
if (typeof window === 'undefined' || typeof document === 'undefined') {
|
|
2597
|
-
return null;
|
|
2598
|
-
}
|
|
2599
|
-
const script = document.querySelector('script[data-astermind-key]');
|
|
2600
|
-
if (script) {
|
|
2601
|
-
const apiKey = script.getAttribute('data-astermind-key');
|
|
2602
|
-
if (apiKey) {
|
|
2603
|
-
return {
|
|
2604
|
-
apiKey,
|
|
2605
|
-
apiUrl: script.getAttribute('data-astermind-url') || DEFAULT_API_URL,
|
|
2606
|
-
_source: 'data-attr'
|
|
2607
|
-
};
|
|
2608
|
-
}
|
|
2609
|
-
}
|
|
2610
|
-
return null;
|
|
2611
|
-
}
|
|
2612
|
-
/**
|
|
2613
|
-
* Load config using priority-based fallback chain:
|
|
2614
|
-
* 1. Environment variables (process.env - for bundlers/Node.js)
|
|
2615
|
-
* 2. Vite environment variables (import.meta.env or window.__ASTERMIND_CONFIG__)
|
|
2616
|
-
* 3. Global object (window.astermindConfig)
|
|
2617
|
-
* 4. Script data attributes (data-astermind-key, data-astermind-url)
|
|
2618
|
-
*
|
|
2619
|
-
* @param options - Configuration options
|
|
2620
|
-
* @param options.throwOnMissingKey - If true (default), throws when no API key found. If false, returns null and logs a warning.
|
|
2621
|
-
* @returns Configuration object or null if not found and throwOnMissingKey is false
|
|
2622
|
-
*/
|
|
2623
|
-
function loadConfig(options = {}) {
|
|
2624
|
-
const { throwOnMissingKey = true } = options;
|
|
2625
|
-
// Priority 1: Environment variables (Node.js/bundler)
|
|
2626
|
-
const envConfig = loadFromProcessEnv();
|
|
2627
|
-
if (envConfig) {
|
|
2628
|
-
return envConfig;
|
|
2629
|
-
}
|
|
2630
|
-
// Priority 2: Vite environment variables / SSR-injected config
|
|
2631
|
-
const viteConfig = loadFromViteEnv();
|
|
2632
|
-
if (viteConfig) {
|
|
2633
|
-
return viteConfig;
|
|
2634
|
-
}
|
|
2635
|
-
// Priority 3: Global object (window.astermindConfig)
|
|
2636
|
-
const globalConfig = loadFromGlobalObject();
|
|
2637
|
-
if (globalConfig) {
|
|
2638
|
-
validateConfig(globalConfig);
|
|
2639
|
-
return globalConfig;
|
|
2640
|
-
}
|
|
2641
|
-
// Priority 4: Script data attributes
|
|
2642
|
-
const scriptConfig = loadFromScriptAttributes();
|
|
2643
|
-
if (scriptConfig) {
|
|
2644
|
-
return scriptConfig;
|
|
2645
|
-
}
|
|
2646
|
-
// No config found
|
|
2647
|
-
if (throwOnMissingKey) {
|
|
2648
|
-
throw new Error('AsterMind API key is required. Configure using one of these methods:\n' +
|
|
2649
|
-
' 1. Set VITE_ASTERMIND_RAG_API_KEY environment variable (Vite)\n' +
|
|
2650
|
-
' 2. Set REACT_APP_ASTERMIND_RAG_API_KEY environment variable (CRA)\n' +
|
|
2651
|
-
' 3. Set window.astermindConfig = { apiKey: "am_...", apiUrl: "..." }\n' +
|
|
2652
|
-
' 4. Add data-astermind-key attribute to your script tag\n' +
|
|
2653
|
-
' 5. Pass apiKey directly to createClient() or CyberneticClient constructor');
|
|
2654
|
-
}
|
|
2655
|
-
else {
|
|
2656
|
-
console.warn('[AsterMind] No API key found. Chatbot will not function until configured.');
|
|
2657
|
-
return null;
|
|
2658
|
-
}
|
|
2659
|
-
}
|
|
2660
|
-
|
|
2661
3186
|
// src/agentic/SiteMapDiscovery.ts
|
|
2662
3187
|
// Multi-source sitemap discovery and merging for agentic navigation
|
|
2663
3188
|
// Zero-config mode: automatically discovers routes on any site
|