@schmitech/chatbot-api 2.1.2 → 2.1.4

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/dist/api.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"api.mjs","sources":["../api.ts"],"sourcesContent":["// For Node.js environments, we can use http.Agent for connection pooling\nlet httpAgent: any = null;\nlet httpsAgent: any = null;\n\n// Initialize agents for connection pooling in Node.js environments\nif (typeof window === 'undefined') {\n // Lazy load to avoid including 'http' in browser bundles\n Promise.all([\n // @ts-expect-error - Dynamic import of Node.js built-in module (only available in Node.js runtime)\n import('http').catch(() => null),\n // @ts-expect-error - Dynamic import of Node.js built-in module (only available in Node.js runtime)\n import('https').catch(() => null)\n ]).then(([http, https]) => {\n if (http?.default?.Agent) {\n httpAgent = new http.default.Agent({ keepAlive: true });\n } else if (http?.Agent) {\n httpAgent = new http.Agent({ keepAlive: true });\n }\n \n if (https?.default?.Agent) {\n httpsAgent = new https.default.Agent({ keepAlive: true });\n } else if (https?.Agent) {\n httpsAgent = new https.Agent({ keepAlive: true });\n }\n }).catch(err => {\n // Silently fail - connection pooling is optional\n console.warn('Failed to initialize HTTP agents:', err.message);\n });\n}\n\n// Define the StreamResponse interface\nexport interface StreamResponse {\n text: string;\n done: boolean;\n audio?: string; // Optional base64-encoded audio data (TTS response) - full audio\n audioFormat?: string; // Audio format (mp3, wav, etc.)\n audio_chunk?: string; // Optional streaming audio chunk (base64-encoded)\n chunk_index?: number; // Index of the audio chunk for ordering\n threading?: { // Optional threading metadata\n supports_threading: boolean;\n message_id: string;\n session_id: string;\n };\n}\n\n// The server now returns this directly for non-streaming chat\nexport interface ChatResponse {\n response: string;\n sources?: any[];\n audio?: string; // Optional base64-encoded audio data (TTS response)\n audio_format?: string; // Audio format (mp3, wav, etc.)\n}\n\n// Thread-related interfaces\nexport interface ThreadInfo {\n thread_id: string;\n thread_session_id: string;\n parent_message_id: string;\n parent_session_id: string;\n adapter_name: string;\n created_at: string;\n expires_at: string;\n}\n\n// The request body for the /v1/chat endpoint\ninterface ChatRequest {\n messages: Array<{ role: string; content: string; }>;\n stream: boolean;\n file_ids?: string[]; // Optional list of file IDs for file context\n thread_id?: string; // Optional thread ID for follow-up questions\n audio_input?: string; // Optional base64-encoded audio data for STT\n audio_format?: string; // Optional audio format (mp3, wav, etc.)\n language?: string; // Optional language code for STT (e.g., \"en-US\")\n return_audio?: boolean; // Whether to return audio response (TTS)\n tts_voice?: string; // Voice for TTS (e.g., \"alloy\", \"echo\" for OpenAI)\n source_language?: string; // Source language for translation\n target_language?: string; // Target language for translation\n}\n\n// File-related interfaces\nexport interface FileUploadResponse {\n file_id: string;\n filename: string;\n mime_type: string;\n file_size: number;\n status: string;\n chunk_count: number;\n message: string;\n}\n\nexport interface FileInfo {\n file_id: string;\n filename: string;\n mime_type: string;\n file_size: number;\n upload_timestamp: string;\n processing_status: string;\n chunk_count: number;\n storage_type: string;\n}\n\nexport interface FileQueryRequest {\n query: string;\n max_results?: number;\n}\n\nexport interface FileQueryResponse {\n file_id: string;\n filename: string;\n results: Array<{\n content: string;\n metadata: {\n chunk_id: string;\n file_id: string;\n chunk_index: number;\n confidence: number;\n };\n }>;\n}\n\n// API key status interface\nexport interface ApiKeyStatus {\n exists: boolean;\n active: boolean;\n adapter_name?: string | null;\n client_name?: string | null;\n created_at?: string | number | null;\n system_prompt?: {\n id: string;\n exists: boolean;\n } | null;\n message?: string;\n}\n\n// Adapter information interface\nexport interface AdapterInfo {\n client_name: string;\n adapter_name: string;\n model: string | null;\n isFileSupported?: boolean;\n notes?: string | null;\n}\n\nexport class ApiClient {\n private readonly apiUrl: string;\n private readonly apiKey: string | null;\n private sessionId: string | null; // Session ID can be mutable\n\n constructor(config: { apiUrl: string; apiKey?: string | null; sessionId?: string | null }) {\n if (!config.apiUrl || typeof config.apiUrl !== 'string') {\n throw new Error('API URL must be a valid string');\n }\n if (config.apiKey !== undefined && config.apiKey !== null && typeof config.apiKey !== 'string') {\n throw new Error('API key must be a valid string or null');\n }\n if (config.sessionId !== undefined && config.sessionId !== null && typeof config.sessionId !== 'string') {\n throw new Error('Session ID must be a valid string or null');\n }\n \n this.apiUrl = config.apiUrl;\n this.apiKey = config.apiKey ?? null;\n this.sessionId = config.sessionId ?? null;\n }\n\n public setSessionId(sessionId: string | null): void {\n if (sessionId !== null && typeof sessionId !== 'string') {\n throw new Error('Session ID must be a valid string or null');\n }\n this.sessionId = sessionId;\n }\n\n public getSessionId(): string | null {\n return this.sessionId;\n }\n\n /**\n * Validate that the API key exists and is active.\n *\n * @returns Promise resolving to API key status information\n * @throws Error if API key is not provided, invalid, inactive, or validation fails\n */\n public async validateApiKey(): Promise<ApiKeyStatus> {\n if (!this.apiKey) {\n throw new Error('API key is required for validation');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/admin/api-keys/${this.apiKey}/status`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n }).catch((fetchError: any) => {\n // Catch network errors before they bubble up\n if (fetchError.name === 'TypeError' && fetchError.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n }\n throw fetchError;\n });\n\n if (!response.ok) {\n // Read error response body\n let errorText = '';\n try {\n errorText = await response.text();\n } catch {\n // If we can't read the body, fall back to status code\n errorText = `HTTP ${response.status}`;\n }\n\n let errorDetail: string;\n let friendlyMessage: string;\n\n try {\n const errorJson = JSON.parse(errorText);\n errorDetail = errorJson.detail || errorJson.message || errorText;\n } catch {\n // If parsing fails, use the error text or status code\n errorDetail = errorText || `HTTP ${response.status}`;\n }\n\n // Generate user-friendly error messages based on HTTP status code\n switch (response.status) {\n case 401:\n friendlyMessage = 'API key is invalid or expired';\n break;\n case 403:\n friendlyMessage = 'Access denied: API key does not have required permissions';\n break;\n case 404:\n friendlyMessage = 'API key not found';\n break;\n case 503:\n friendlyMessage = 'API key management is not available in inference-only mode';\n break;\n default:\n friendlyMessage = `Failed to validate API key: ${errorDetail}`;\n break;\n }\n\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n const status: ApiKeyStatus = await response.json();\n\n // Check if the key exists\n if (!status.exists) {\n const friendlyMessage = 'API key does not exist';\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n // Check if the key is active\n if (!status.active) {\n const friendlyMessage = 'API key is inactive';\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n return status;\n } catch (error: any) {\n // Extract user-friendly error message\n let friendlyMessage: string;\n\n if (error instanceof Error && error.message) {\n // If it's already a user-friendly Error from above, use it directly\n if (error.message.includes('API key') ||\n error.message.includes('Access denied') ||\n error.message.includes('invalid') ||\n error.message.includes('expired') ||\n error.message.includes('inactive') ||\n error.message.includes('not found') ||\n error.message.includes('Could not connect')) {\n friendlyMessage = error.message;\n } else {\n friendlyMessage = `API key validation failed: ${error.message}`;\n }\n } else if (error.name === 'TypeError' && error.message?.includes('Failed to fetch')) {\n friendlyMessage = 'Could not connect to the server. Please check if the server is running.';\n } else {\n friendlyMessage = 'API key validation failed. Please check your API key and try again.';\n }\n\n // Only log warning if it's not a network error (those are already logged by browser)\n // For validation errors, we log once with a friendly message\n // Note: Browser will still log HTTP errors (401, 404, etc.) - this is unavoidable\n console.warn(`[ApiClient] ${friendlyMessage}`);\n\n // Throw the friendly error message\n throw new Error(friendlyMessage);\n }\n }\n\n /**\n * Get adapter information for the current API key.\n *\n * Returns information about the adapter and model being used by the API key.\n * This is useful for displaying configuration details to users.\n *\n * @returns Promise resolving to adapter information\n * @throws Error if API key is not provided, invalid, disabled, or request fails\n */\n public async getAdapterInfo(): Promise<AdapterInfo> {\n if (!this.apiKey) {\n throw new Error('API key is required to get adapter information');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/admin/api-keys/info`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n }).catch((fetchError: any) => {\n // Catch network errors before they bubble up\n if (fetchError.name === 'TypeError' && fetchError.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n }\n throw fetchError;\n });\n\n if (!response.ok) {\n // Read error response body\n let errorText = '';\n try {\n errorText = await response.text();\n } catch {\n // If we can't read the body, fall back to status code\n errorText = `HTTP ${response.status}`;\n }\n\n let errorDetail: string;\n let friendlyMessage: string;\n\n try {\n const errorJson = JSON.parse(errorText);\n errorDetail = errorJson.detail || errorJson.message || errorText;\n } catch {\n // If parsing fails, use the error text or status code\n errorDetail = errorText || `HTTP ${response.status}`;\n }\n\n // Generate user-friendly error messages based on HTTP status code\n switch (response.status) {\n case 401:\n friendlyMessage = 'API key is invalid, disabled, or has no associated adapter';\n break;\n case 404:\n friendlyMessage = 'Adapter configuration not found';\n break;\n case 503:\n friendlyMessage = 'Service is not available';\n break;\n default:\n friendlyMessage = `Failed to get adapter info: ${errorDetail}`;\n break;\n }\n\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n const adapterInfo: AdapterInfo = await response.json();\n return adapterInfo;\n } catch (error: any) {\n // Extract user-friendly error message\n let friendlyMessage: string;\n\n if (error instanceof Error && error.message) {\n // If it's already a user-friendly Error from above, use it directly\n if (error.message.includes('API key') ||\n error.message.includes('Adapter') ||\n error.message.includes('invalid') ||\n error.message.includes('disabled') ||\n error.message.includes('not found') ||\n error.message.includes('Could not connect')) {\n friendlyMessage = error.message;\n } else {\n friendlyMessage = `Failed to get adapter info: ${error.message}`;\n }\n } else if (error.name === 'TypeError' && error.message?.includes('Failed to fetch')) {\n friendlyMessage = 'Could not connect to the server. Please check if the server is running.';\n } else {\n friendlyMessage = 'Failed to get adapter information. Please try again.';\n }\n\n console.warn(`[ApiClient] ${friendlyMessage}`);\n\n // Throw the friendly error message\n throw new Error(friendlyMessage);\n }\n }\n\n // Helper to get fetch options with connection pooling if available\n private getFetchOptions(options: RequestInit = {}): RequestInit {\n const baseOptions: RequestInit = {};\n \n // Environment-specific options\n if (typeof window === 'undefined') {\n // Node.js: Use connection pooling agent\n const isHttps = this.apiUrl.startsWith('https:');\n const agent = isHttps ? httpsAgent : httpAgent;\n if (agent) {\n (baseOptions as any).agent = agent;\n }\n } else {\n // Browser: Use keep-alive header\n baseOptions.headers = { 'Connection': 'keep-alive' };\n }\n\n // Common headers\n const headers: Record<string, string> = {\n 'X-Request-ID': Date.now().toString(36) + Math.random().toString(36).substring(2),\n };\n\n // Merge base options headers (for browser keep-alive)\n if (baseOptions.headers) {\n Object.assign(headers, baseOptions.headers);\n }\n\n // Merge original request headers (but don't overwrite API key)\n if (options.headers) {\n const incomingHeaders = options.headers as Record<string, string>;\n for (const [key, value] of Object.entries(incomingHeaders)) {\n // Don't overwrite X-API-Key if we have one\n if (key.toLowerCase() !== 'x-api-key' || !this.apiKey) {\n headers[key] = value;\n }\n }\n }\n\n if (this.apiKey) {\n headers['X-API-Key'] = this.apiKey;\n }\n\n if (this.sessionId) {\n headers['X-Session-ID'] = this.sessionId;\n }\n\n return {\n ...options,\n ...baseOptions,\n headers,\n };\n }\n\n // Create Chat request\n private createChatRequest(\n message: string, \n stream: boolean = true, \n fileIds?: string[],\n threadId?: string,\n audioInput?: string,\n audioFormat?: string,\n language?: string,\n returnAudio?: boolean,\n ttsVoice?: string,\n sourceLanguage?: string,\n targetLanguage?: string\n ): ChatRequest {\n const request: ChatRequest = {\n messages: [\n { role: \"user\", content: message }\n ],\n stream\n };\n if (fileIds && fileIds.length > 0) {\n request.file_ids = fileIds;\n }\n if (threadId) {\n request.thread_id = threadId;\n }\n if (audioInput) {\n request.audio_input = audioInput;\n }\n if (audioFormat) {\n request.audio_format = audioFormat;\n }\n if (language) {\n request.language = language;\n }\n if (returnAudio !== undefined) {\n request.return_audio = returnAudio;\n }\n if (ttsVoice) {\n request.tts_voice = ttsVoice;\n }\n if (sourceLanguage) {\n request.source_language = sourceLanguage;\n }\n if (targetLanguage) {\n request.target_language = targetLanguage;\n }\n return request;\n }\n\n public async *streamChat(\n message: string,\n stream: boolean = true,\n fileIds?: string[],\n threadId?: string,\n audioInput?: string,\n audioFormat?: string,\n language?: string,\n returnAudio?: boolean,\n ttsVoice?: string,\n sourceLanguage?: string,\n targetLanguage?: string\n ): AsyncGenerator<StreamResponse> {\n try {\n // Add timeout to the fetch request\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 60000); // 60 second timeout\n\n const response = await fetch(`${this.apiUrl}/v1/chat`, {\n ...this.getFetchOptions({\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': stream ? 'text/event-stream' : 'application/json'\n },\n body: JSON.stringify(this.createChatRequest(\n message, \n stream, \n fileIds,\n threadId,\n audioInput,\n audioFormat,\n language,\n returnAudio,\n ttsVoice,\n sourceLanguage,\n targetLanguage\n )),\n }),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Network response was not ok: ${response.status} ${errorText}`);\n }\n\n if (!stream) {\n // Handle non-streaming response\n const data = await response.json() as ChatResponse;\n if (data.response) {\n yield {\n text: data.response,\n done: true,\n audio: data.audio,\n audioFormat: data.audio_format\n } as StreamResponse & { audio?: string; audioFormat?: string };\n }\n return;\n }\n \n const reader = response.body?.getReader();\n if (!reader) throw new Error('No reader available');\n\n const decoder = new TextDecoder();\n let buffer = '';\n let hasReceivedContent = false;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n \n // Process complete lines immediately as they arrive\n let lineStartIndex = 0;\n let newlineIndex;\n \n while ((newlineIndex = buffer.indexOf('\\n', lineStartIndex)) !== -1) {\n const line = buffer.slice(lineStartIndex, newlineIndex).trim();\n lineStartIndex = newlineIndex + 1;\n \n if (line && line.startsWith('data: ')) {\n const jsonText = line.slice(6).trim();\n \n if (!jsonText || jsonText === '[DONE]') {\n yield { text: '', done: true };\n return;\n }\n\n try {\n const data = JSON.parse(jsonText);\n\n if (data.error) {\n const errorMessage = data.error?.message || data.error || 'Unknown server error';\n const friendlyMessage = `Server error: ${errorMessage}`;\n console.warn(`[ApiClient] ${friendlyMessage}`);\n throw new Error(friendlyMessage);\n }\n\n // Check for done chunk first - it may not have a response field\n // This handles the final done chunk that contains threading metadata\n if (data.done === true) {\n hasReceivedContent = true;\n yield {\n text: '',\n done: true,\n audio: data.audio,\n audioFormat: data.audio_format || data.audioFormat,\n threading: data.threading // Pass through threading metadata\n };\n return;\n }\n\n // Note: Base64 audio filtering is handled by chatStore's sanitizeMessageContent\n // We keep response text as-is here and let the application layer decide\n const responseText = data.response || '';\n\n // Handle streaming audio chunks\n if (data.audio_chunk !== undefined) {\n yield {\n text: '',\n done: false,\n audio_chunk: data.audio_chunk,\n audioFormat: data.audioFormat || data.audio_format || 'opus',\n chunk_index: data.chunk_index ?? 0\n };\n }\n\n if (responseText || data.audio) {\n hasReceivedContent = true;\n yield {\n text: responseText,\n done: data.done || false,\n audio: data.audio,\n audioFormat: data.audio_format || data.audioFormat,\n threading: data.threading // Include threading if present\n };\n }\n\n } catch (parseError: any) {\n // Log more details for debugging\n console.warn('[ApiClient] Unable to parse server response. This may be a temporary issue.');\n console.warn('[ApiClient] Parse error details:', parseError?.message);\n console.warn('[ApiClient] JSON text length:', jsonText?.length);\n console.warn('[ApiClient] JSON text preview (first 200 chars):', jsonText?.substring(0, 200));\n console.warn('[ApiClient] JSON text preview (last 200 chars):', jsonText?.substring(jsonText.length - 200));\n }\n } else if (line) {\n // Handle raw text chunks that are not in SSE format\n hasReceivedContent = true;\n yield { text: line, done: false };\n }\n }\n \n buffer = buffer.slice(lineStartIndex);\n\n if (buffer.length > 1000000) { // 1MB limit\n console.warn('[ApiClient] Buffer too large, truncating...');\n buffer = buffer.slice(-500000); // Keep last 500KB\n }\n }\n \n if (hasReceivedContent) {\n yield { text: '', done: true };\n }\n \n } finally {\n reader.releaseLock();\n }\n \n } catch (error: any) {\n if (error.name === 'AbortError') {\n throw new Error('Connection timed out. Please check if the server is running.');\n } else if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n public async clearConversationHistory(sessionId?: string): Promise<{\n status: string;\n message: string;\n session_id: string;\n deleted_count: number;\n timestamp: string;\n }> {\n /**\n * Clear conversation history for a session.\n *\n * @param sessionId - Optional session ID to clear. If not provided, uses current session.\n * @returns Promise resolving to operation result\n * @throws Error if the operation fails\n */\n const targetSessionId = sessionId || this.sessionId;\n\n if (!targetSessionId) {\n throw new Error('No session ID provided and no current session available');\n }\n\n if (!this.apiKey) {\n throw new Error('API key is required for clearing conversation history');\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Session-ID': targetSessionId,\n 'X-API-Key': this.apiKey\n };\n\n try {\n const response = await fetch(`${this.apiUrl}/admin/chat-history/${targetSessionId}`, {\n ...this.getFetchOptions({\n method: 'DELETE',\n headers\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to clear conversation history: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n return result;\n\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n public async deleteConversationWithFiles(sessionId?: string, fileIds?: string[]): Promise<{\n status: string;\n message: string;\n session_id: string;\n deleted_messages: number;\n deleted_files: number;\n file_deletion_errors: string[] | null;\n timestamp: string;\n }> {\n /**\n * Delete a conversation and all associated files.\n *\n * This method performs a complete conversation deletion:\n * - Deletes each file provided in fileIds (metadata, content, and vector store chunks)\n * - Clears conversation history\n *\n * File tracking is managed by the frontend (localStorage). The backend is stateless\n * and requires fileIds to be provided explicitly.\n *\n * @param sessionId - Optional session ID to delete. If not provided, uses current session.\n * @param fileIds - Optional list of file IDs to delete (from conversation's attachedFiles)\n * @returns Promise resolving to deletion result with counts\n * @throws Error if the operation fails\n */\n const targetSessionId = sessionId || this.sessionId;\n\n if (!targetSessionId) {\n throw new Error('No session ID provided and no current session available');\n }\n\n if (!this.apiKey) {\n throw new Error('API key is required for deleting conversation');\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Session-ID': targetSessionId,\n 'X-API-Key': this.apiKey\n };\n\n // Build URL with file_ids query parameter\n const fileIdsParam = fileIds && fileIds.length > 0 ? `?file_ids=${fileIds.join(',')}` : '';\n const url = `${this.apiUrl}/admin/conversations/${targetSessionId}${fileIdsParam}`;\n\n try {\n const response = await fetch(url, {\n ...this.getFetchOptions({\n method: 'DELETE',\n headers\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to delete conversation: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n return result;\n\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Create a conversation thread from a parent message.\n *\n * @param messageId - ID of the parent message\n * @param sessionId - Session ID of the parent conversation\n * @returns Promise resolving to thread information\n * @throws Error if the operation fails\n */\n public async createThread(messageId: string, sessionId: string): Promise<ThreadInfo> {\n if (!this.apiKey) {\n throw new Error('API key is required for creating threads');\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-API-Key': this.apiKey\n };\n\n try {\n const response = await fetch(`${this.apiUrl}/api/threads`, {\n ...this.getFetchOptions({\n method: 'POST',\n headers,\n body: JSON.stringify({\n message_id: messageId,\n session_id: sessionId\n })\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to create thread: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n return result;\n\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Get thread information by thread ID.\n *\n * @param threadId - Thread identifier\n * @returns Promise resolving to thread information\n * @throws Error if the operation fails\n */\n public async getThreadInfo(threadId: string): Promise<ThreadInfo> {\n if (!this.apiKey) {\n throw new Error('API key is required for getting thread info');\n }\n\n const headers: Record<string, string> = {\n 'X-API-Key': this.apiKey\n };\n\n try {\n const response = await fetch(`${this.apiUrl}/api/threads/${threadId}`, {\n ...this.getFetchOptions({\n method: 'GET',\n headers\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to get thread info: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n return result;\n\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Delete a thread and its associated dataset.\n *\n * @param threadId - Thread identifier\n * @returns Promise resolving to deletion result\n * @throws Error if the operation fails\n */\n public async deleteThread(threadId: string): Promise<{ status: string; message: string; thread_id: string }> {\n if (!this.apiKey) {\n throw new Error('API key is required for deleting threads');\n }\n\n const headers: Record<string, string> = {\n 'X-API-Key': this.apiKey\n };\n\n try {\n const response = await fetch(`${this.apiUrl}/api/threads/${threadId}`, {\n ...this.getFetchOptions({\n method: 'DELETE',\n headers\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to delete thread: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n return result;\n\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Upload a file for processing and indexing.\n *\n * @param file - The file to upload\n * @returns Promise resolving to upload response with file_id\n * @throws Error if upload fails\n */\n public async uploadFile(file: File): Promise<FileUploadResponse> {\n if (!this.apiKey) {\n throw new Error('API key is required for file upload');\n }\n\n const formData = new FormData();\n formData.append('file', file);\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files/upload`, {\n ...this.getFetchOptions({\n method: 'POST',\n body: formData\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to upload file: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * List all files for the current API key.\n * \n * @returns Promise resolving to list of file information\n * @throws Error if request fails\n */\n public async listFiles(): Promise<FileInfo[]> {\n if (!this.apiKey) {\n throw new Error('API key is required for listing files');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to list files: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Get information about a specific file.\n * \n * @param fileId - The file ID\n * @returns Promise resolving to file information\n * @throws Error if file not found or request fails\n */\n public async getFileInfo(fileId: string): Promise<FileInfo> {\n if (!this.apiKey) {\n throw new Error('API key is required for getting file info');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files/${fileId}`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to get file info: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Query a specific file using semantic search.\n * \n * @param fileId - The file ID\n * @param query - The search query\n * @param maxResults - Maximum number of results (default: 10)\n * @returns Promise resolving to query results\n * @throws Error if query fails\n */\n public async queryFile(fileId: string, query: string, maxResults: number = 10): Promise<FileQueryResponse> {\n if (!this.apiKey) {\n throw new Error('API key is required for querying files');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files/${fileId}/query`, {\n ...this.getFetchOptions({\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({ query, max_results: maxResults })\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to query file: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Delete a specific file.\n * \n * @param fileId - The file ID\n * @returns Promise resolving to deletion result\n * @throws Error if deletion fails\n */\n public async deleteFile(fileId: string): Promise<{ message: string; file_id: string }> {\n if (!this.apiKey) {\n throw new Error('API key is required for deleting files');\n }\n\n const url = `${this.apiUrl}/api/files/${fileId}`;\n const fetchOptions = this.getFetchOptions({\n method: 'DELETE'\n });\n\n try {\n const response = await fetch(url, fetchOptions);\n\n if (!response.ok) {\n const errorText = await response.text();\n let friendlyMessage: string;\n try {\n const errorJson = JSON.parse(errorText);\n friendlyMessage = errorJson.detail || errorJson.message || `Failed to delete file (HTTP ${response.status})`;\n } catch {\n friendlyMessage = `Failed to delete file (HTTP ${response.status})`;\n }\n console.warn(`[ApiClient] ${friendlyMessage}`);\n throw new Error(friendlyMessage);\n }\n\n const result = await response.json();\n return result;\n } catch (error: any) {\n // Extract user-friendly error message\n let friendlyMessage: string;\n \n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n friendlyMessage = 'Could not connect to the server. Please check if the server is running.';\n } else if (error.message && !error.message.includes('Failed to delete file')) {\n // Use existing message if it's already user-friendly\n friendlyMessage = error.message;\n } else {\n friendlyMessage = `Failed to delete file. Please try again.`;\n }\n \n console.warn(`[ApiClient] ${friendlyMessage}`);\n throw new Error(friendlyMessage);\n }\n }\n}\n\n// Legacy compatibility functions - these create a default client instance\n// These are kept for backward compatibility but should be deprecated in favor of the class-based approach\n\nlet defaultClient: ApiClient | null = null;\n\n// Configure the API with a custom URL, API key (optional), and session ID (optional)\nexport const configureApi = (apiUrl: string, apiKey: string | null = null, sessionId: string | null = null): void => {\n defaultClient = new ApiClient({ apiUrl, apiKey, sessionId });\n}\n\n// Legacy streamChat function that uses the default client\nexport async function* streamChat(\n message: string,\n stream: boolean = true,\n fileIds?: string[],\n threadId?: string,\n audioInput?: string,\n audioFormat?: string,\n language?: string,\n returnAudio?: boolean,\n ttsVoice?: string,\n sourceLanguage?: string,\n targetLanguage?: string\n): AsyncGenerator<StreamResponse> {\n if (!defaultClient) {\n throw new Error('API not configured. Please call configureApi() with your server URL before using any API functions.');\n }\n \n yield* defaultClient.streamChat(\n message, \n stream, \n fileIds,\n threadId,\n audioInput,\n audioFormat,\n language,\n returnAudio,\n ttsVoice,\n sourceLanguage,\n targetLanguage\n );\n}\n\n"],"names":["httpAgent","httpsAgent","http","https","_a","_b","err","ApiClient","config","__publicField","sessionId","response","fetchError","errorText","errorDetail","friendlyMessage","errorJson","status","error","options","baseOptions","agent","headers","incomingHeaders","key","value","message","stream","fileIds","threadId","audioInput","audioFormat","language","returnAudio","ttsVoice","sourceLanguage","targetLanguage","request","controller","timeoutId","data","reader","decoder","buffer","hasReceivedContent","done","chunk","lineStartIndex","newlineIndex","line","jsonText","responseText","parseError","targetSessionId","fileIdsParam","url","messageId","file","formData","fileId","query","maxResults","fetchOptions","defaultClient","configureApi","apiUrl","apiKey","streamChat"],"mappings":";;;AACA,IAAIA,IAAiB,MACjBC,IAAkB;AAGlB,OAAO,SAAW,OAEpB,QAAQ,IAAI;AAAA;AAAA,EAEV,OAAO,MAAM,EAAE,MAAM,MAAM,IAAI;AAAA;AAAA,EAE/B,OAAO,OAAO,EAAE,MAAM,MAAM,IAAI;AAAA,CACjC,EAAE,KAAK,CAAC,CAACC,GAAMC,CAAK,MAAM;AAX7B,MAAAC,GAAAC;AAYI,GAAID,IAAAF,KAAA,gBAAAA,EAAM,YAAN,QAAAE,EA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,GAAQ,QAAAC,GAAQ,WAAAxD,GAAW;AAC7D;AAGA,gBAAuByD,EACrBzC,GACAC,IAAkB,IAClBC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACgC;AAChC,MAAI,CAAC2B;AACH,UAAM,IAAI,MAAM,qGAAqG;AAGvH,SAAOA,EAAc;AAAA,IACnBrC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"api.mjs","sources":["../api.ts"],"sourcesContent":["// For Node.js environments, we can use http.Agent for connection pooling\nlet httpAgent: any = null;\nlet httpsAgent: any = null;\n\n// Initialize agents for connection pooling in Node.js environments\nif (typeof window === 'undefined') {\n // Lazy load to avoid including 'http' in browser bundles\n Promise.all([\n // @ts-expect-error - Dynamic import of Node.js built-in module (only available in Node.js runtime)\n import('http').catch(() => null),\n // @ts-expect-error - Dynamic import of Node.js built-in module (only available in Node.js runtime)\n import('https').catch(() => null)\n ]).then(([http, https]) => {\n if (http?.default?.Agent) {\n httpAgent = new http.default.Agent({ keepAlive: true });\n } else if (http?.Agent) {\n httpAgent = new http.Agent({ keepAlive: true });\n }\n \n if (https?.default?.Agent) {\n httpsAgent = new https.default.Agent({ keepAlive: true });\n } else if (https?.Agent) {\n httpsAgent = new https.Agent({ keepAlive: true });\n }\n }).catch(err => {\n // Silently fail - connection pooling is optional\n console.warn('Failed to initialize HTTP agents:', err.message);\n });\n}\n\n// Define the StreamResponse interface\nexport interface StreamResponse {\n text: string;\n done: boolean;\n audio?: string; // Optional base64-encoded audio data (TTS response) - full audio\n audioFormat?: string; // Audio format (mp3, wav, etc.)\n audio_chunk?: string; // Optional streaming audio chunk (base64-encoded)\n chunk_index?: number; // Index of the audio chunk for ordering\n threading?: { // Optional threading metadata\n supports_threading: boolean;\n message_id: string;\n session_id: string;\n };\n}\n\n// The server now returns this directly for non-streaming chat\nexport interface ChatResponse {\n response: string;\n sources?: any[];\n audio?: string; // Optional base64-encoded audio data (TTS response)\n audio_format?: string; // Audio format (mp3, wav, etc.)\n}\n\n// Thread-related interfaces\nexport interface ThreadInfo {\n thread_id: string;\n thread_session_id: string;\n parent_message_id: string;\n parent_session_id: string;\n adapter_name: string;\n created_at: string;\n expires_at: string;\n}\n\n// The request body for the /v1/chat endpoint\ninterface ChatRequest {\n messages: Array<{ role: string; content: string; }>;\n stream: boolean;\n file_ids?: string[]; // Optional list of file IDs for file context\n thread_id?: string; // Optional thread ID for follow-up questions\n audio_input?: string; // Optional base64-encoded audio data for STT\n audio_format?: string; // Optional audio format (mp3, wav, etc.)\n language?: string; // Optional language code for STT (e.g., \"en-US\")\n return_audio?: boolean; // Whether to return audio response (TTS)\n tts_voice?: string; // Voice for TTS (e.g., \"alloy\", \"echo\" for OpenAI)\n source_language?: string; // Source language for translation\n target_language?: string; // Target language for translation\n}\n\n// File-related interfaces\nexport interface FileUploadResponse {\n file_id: string;\n filename: string;\n mime_type: string;\n file_size: number;\n status: string;\n chunk_count: number;\n message: string;\n}\n\nexport interface FileInfo {\n file_id: string;\n filename: string;\n mime_type: string;\n file_size: number;\n upload_timestamp: string;\n processing_status: string;\n chunk_count: number;\n storage_type: string;\n}\n\nexport interface FileQueryRequest {\n query: string;\n max_results?: number;\n}\n\nexport interface FileQueryResponse {\n file_id: string;\n filename: string;\n results: Array<{\n content: string;\n metadata: {\n chunk_id: string;\n file_id: string;\n chunk_index: number;\n confidence: number;\n };\n }>;\n}\n\n// API key status interface\nexport interface ApiKeyStatus {\n exists: boolean;\n active: boolean;\n adapter_name?: string | null;\n client_name?: string | null;\n created_at?: string | number | null;\n system_prompt?: {\n id: string;\n exists: boolean;\n } | null;\n message?: string;\n}\n\n// Adapter information interface\nexport interface AdapterInfo {\n client_name: string;\n adapter_name: string;\n model: string | null;\n isFileSupported?: boolean;\n notes?: string | null;\n}\n\nexport interface ConversationHistoryMessage {\n message_id?: string | null;\n role: string;\n content: string;\n timestamp: string | number | Date | null;\n metadata?: Record<string, any>;\n}\n\nexport interface ConversationHistoryResponse {\n session_id: string;\n messages: ConversationHistoryMessage[];\n count: number;\n}\n\nexport class ApiClient {\n private readonly apiUrl: string;\n private readonly apiKey: string | null;\n private sessionId: string | null; // Session ID can be mutable\n\n constructor(config: { apiUrl: string; apiKey?: string | null; sessionId?: string | null }) {\n if (!config.apiUrl || typeof config.apiUrl !== 'string') {\n throw new Error('API URL must be a valid string');\n }\n if (config.apiKey !== undefined && config.apiKey !== null && typeof config.apiKey !== 'string') {\n throw new Error('API key must be a valid string or null');\n }\n if (config.sessionId !== undefined && config.sessionId !== null && typeof config.sessionId !== 'string') {\n throw new Error('Session ID must be a valid string or null');\n }\n \n this.apiUrl = config.apiUrl;\n this.apiKey = config.apiKey ?? null;\n this.sessionId = config.sessionId ?? null;\n }\n\n public setSessionId(sessionId: string | null): void {\n if (sessionId !== null && typeof sessionId !== 'string') {\n throw new Error('Session ID must be a valid string or null');\n }\n this.sessionId = sessionId;\n }\n\n public getSessionId(): string | null {\n return this.sessionId;\n }\n\n /**\n * Validate that the API key exists and is active.\n *\n * @returns Promise resolving to API key status information\n * @throws Error if API key is not provided, invalid, inactive, or validation fails\n */\n public async validateApiKey(): Promise<ApiKeyStatus> {\n if (!this.apiKey) {\n throw new Error('API key is required for validation');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/admin/api-keys/${this.apiKey}/status`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n }).catch((fetchError: any) => {\n // Catch network errors before they bubble up\n if (fetchError.name === 'TypeError' && fetchError.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n }\n throw fetchError;\n });\n\n if (!response.ok) {\n // Read error response body\n let errorText = '';\n try {\n errorText = await response.text();\n } catch {\n // If we can't read the body, fall back to status code\n errorText = `HTTP ${response.status}`;\n }\n\n let errorDetail: string;\n let friendlyMessage: string;\n\n try {\n const errorJson = JSON.parse(errorText);\n errorDetail = errorJson.detail || errorJson.message || errorText;\n } catch {\n // If parsing fails, use the error text or status code\n errorDetail = errorText || `HTTP ${response.status}`;\n }\n\n // Generate user-friendly error messages based on HTTP status code\n switch (response.status) {\n case 401:\n friendlyMessage = 'API key is invalid or expired';\n break;\n case 403:\n friendlyMessage = 'Access denied: API key does not have required permissions';\n break;\n case 404:\n friendlyMessage = 'API key not found';\n break;\n case 503:\n friendlyMessage = 'API key management is not available in inference-only mode';\n break;\n default:\n friendlyMessage = `Failed to validate API key: ${errorDetail}`;\n break;\n }\n\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n const status: ApiKeyStatus = await response.json();\n\n // Check if the key exists\n if (!status.exists) {\n const friendlyMessage = 'API key does not exist';\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n // Check if the key is active\n if (!status.active) {\n const friendlyMessage = 'API key is inactive';\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n return status;\n } catch (error: any) {\n // Extract user-friendly error message\n let friendlyMessage: string;\n\n if (error instanceof Error && error.message) {\n // If it's already a user-friendly Error from above, use it directly\n if (error.message.includes('API key') ||\n error.message.includes('Access denied') ||\n error.message.includes('invalid') ||\n error.message.includes('expired') ||\n error.message.includes('inactive') ||\n error.message.includes('not found') ||\n error.message.includes('Could not connect')) {\n friendlyMessage = error.message;\n } else {\n friendlyMessage = `API key validation failed: ${error.message}`;\n }\n } else if (error.name === 'TypeError' && error.message?.includes('Failed to fetch')) {\n friendlyMessage = 'Could not connect to the server. Please check if the server is running.';\n } else {\n friendlyMessage = 'API key validation failed. Please check your API key and try again.';\n }\n\n // Only log warning if it's not a network error (those are already logged by browser)\n // For validation errors, we log once with a friendly message\n // Note: Browser will still log HTTP errors (401, 404, etc.) - this is unavoidable\n console.warn(`[ApiClient] ${friendlyMessage}`);\n\n // Throw the friendly error message\n throw new Error(friendlyMessage);\n }\n }\n\n /**\n * Get adapter information for the current API key.\n *\n * Returns information about the adapter and model being used by the API key.\n * This is useful for displaying configuration details to users.\n *\n * @returns Promise resolving to adapter information\n * @throws Error if API key is not provided, invalid, disabled, or request fails\n */\n public async getAdapterInfo(): Promise<AdapterInfo> {\n if (!this.apiKey) {\n throw new Error('API key is required to get adapter information');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/admin/adapters/info`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n }).catch((fetchError: any) => {\n // Catch network errors before they bubble up\n if (fetchError.name === 'TypeError' && fetchError.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n }\n throw fetchError;\n });\n\n if (!response.ok) {\n // Read error response body\n let errorText = '';\n try {\n errorText = await response.text();\n } catch {\n // If we can't read the body, fall back to status code\n errorText = `HTTP ${response.status}`;\n }\n\n let errorDetail: string;\n let friendlyMessage: string;\n\n try {\n const errorJson = JSON.parse(errorText);\n errorDetail = errorJson.detail || errorJson.message || errorText;\n } catch {\n // If parsing fails, use the error text or status code\n errorDetail = errorText || `HTTP ${response.status}`;\n }\n\n // Generate user-friendly error messages based on HTTP status code\n switch (response.status) {\n case 401:\n friendlyMessage = 'API key is invalid, disabled, or has no associated adapter';\n break;\n case 404:\n friendlyMessage = 'Adapter configuration not found';\n break;\n case 503:\n friendlyMessage = 'Service is not available';\n break;\n default:\n friendlyMessage = `Failed to get adapter info: ${errorDetail}`;\n break;\n }\n\n // Throw error - will be logged in catch block to avoid duplicates\n throw new Error(friendlyMessage);\n }\n\n const adapterInfo: AdapterInfo = await response.json();\n return adapterInfo;\n } catch (error: any) {\n // Extract user-friendly error message\n let friendlyMessage: string;\n\n if (error instanceof Error && error.message) {\n // If it's already a user-friendly Error from above, use it directly\n if (error.message.includes('API key') ||\n error.message.includes('Adapter') ||\n error.message.includes('invalid') ||\n error.message.includes('disabled') ||\n error.message.includes('not found') ||\n error.message.includes('Could not connect')) {\n friendlyMessage = error.message;\n } else {\n friendlyMessage = `Failed to get adapter info: ${error.message}`;\n }\n } else if (error.name === 'TypeError' && error.message?.includes('Failed to fetch')) {\n friendlyMessage = 'Could not connect to the server. Please check if the server is running.';\n } else {\n friendlyMessage = 'Failed to get adapter information. Please try again.';\n }\n\n console.warn(`[ApiClient] ${friendlyMessage}`);\n\n // Throw the friendly error message\n throw new Error(friendlyMessage);\n }\n }\n\n // Helper to get fetch options with connection pooling if available\n private getFetchOptions(options: RequestInit = {}): RequestInit {\n const baseOptions: RequestInit = {};\n \n // Environment-specific options\n if (typeof window === 'undefined') {\n // Node.js: Use connection pooling agent\n const isHttps = this.apiUrl.startsWith('https:');\n const agent = isHttps ? httpsAgent : httpAgent;\n if (agent) {\n (baseOptions as any).agent = agent;\n }\n } else {\n // Browser: Use keep-alive header\n baseOptions.headers = { 'Connection': 'keep-alive' };\n }\n\n // Common headers\n const headers: Record<string, string> = {\n 'X-Request-ID': Date.now().toString(36) + Math.random().toString(36).substring(2),\n };\n\n // Merge base options headers (for browser keep-alive)\n if (baseOptions.headers) {\n Object.assign(headers, baseOptions.headers);\n }\n\n // Merge original request headers (but don't overwrite API key)\n if (options.headers) {\n const incomingHeaders = options.headers as Record<string, string>;\n for (const [key, value] of Object.entries(incomingHeaders)) {\n // Don't overwrite X-API-Key if we have one\n if (key.toLowerCase() !== 'x-api-key' || !this.apiKey) {\n headers[key] = value;\n }\n }\n }\n\n if (this.apiKey) {\n headers['X-API-Key'] = this.apiKey;\n }\n\n if (this.sessionId) {\n headers['X-Session-ID'] = this.sessionId;\n }\n\n return {\n ...options,\n ...baseOptions,\n headers,\n };\n }\n\n // Create Chat request\n private createChatRequest(\n message: string, \n stream: boolean = true, \n fileIds?: string[],\n threadId?: string,\n audioInput?: string,\n audioFormat?: string,\n language?: string,\n returnAudio?: boolean,\n ttsVoice?: string,\n sourceLanguage?: string,\n targetLanguage?: string\n ): ChatRequest {\n const request: ChatRequest = {\n messages: [\n { role: \"user\", content: message }\n ],\n stream\n };\n if (fileIds && fileIds.length > 0) {\n request.file_ids = fileIds;\n }\n if (threadId) {\n request.thread_id = threadId;\n }\n if (audioInput) {\n request.audio_input = audioInput;\n }\n if (audioFormat) {\n request.audio_format = audioFormat;\n }\n if (language) {\n request.language = language;\n }\n if (returnAudio !== undefined) {\n request.return_audio = returnAudio;\n }\n if (ttsVoice) {\n request.tts_voice = ttsVoice;\n }\n if (sourceLanguage) {\n request.source_language = sourceLanguage;\n }\n if (targetLanguage) {\n request.target_language = targetLanguage;\n }\n return request;\n }\n\n public async *streamChat(\n message: string,\n stream: boolean = true,\n fileIds?: string[],\n threadId?: string,\n audioInput?: string,\n audioFormat?: string,\n language?: string,\n returnAudio?: boolean,\n ttsVoice?: string,\n sourceLanguage?: string,\n targetLanguage?: string\n ): AsyncGenerator<StreamResponse> {\n try {\n // Add timeout to the fetch request\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 60000); // 60 second timeout\n\n const response = await fetch(`${this.apiUrl}/v1/chat`, {\n ...this.getFetchOptions({\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': stream ? 'text/event-stream' : 'application/json'\n },\n body: JSON.stringify(this.createChatRequest(\n message, \n stream, \n fileIds,\n threadId,\n audioInput,\n audioFormat,\n language,\n returnAudio,\n ttsVoice,\n sourceLanguage,\n targetLanguage\n )),\n }),\n signal: controller.signal\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Network response was not ok: ${response.status} ${errorText}`);\n }\n\n if (!stream) {\n // Handle non-streaming response\n const data = await response.json() as ChatResponse;\n if (data.response) {\n yield {\n text: data.response,\n done: true,\n audio: data.audio,\n audioFormat: data.audio_format\n } as StreamResponse & { audio?: string; audioFormat?: string };\n }\n return;\n }\n \n const reader = response.body?.getReader();\n if (!reader) throw new Error('No reader available');\n\n const decoder = new TextDecoder();\n let buffer = '';\n let hasReceivedContent = false;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n \n // Process complete lines immediately as they arrive\n let lineStartIndex = 0;\n let newlineIndex;\n \n while ((newlineIndex = buffer.indexOf('\\n', lineStartIndex)) !== -1) {\n const line = buffer.slice(lineStartIndex, newlineIndex).trim();\n lineStartIndex = newlineIndex + 1;\n \n if (line && line.startsWith('data: ')) {\n const jsonText = line.slice(6).trim();\n \n if (!jsonText || jsonText === '[DONE]') {\n yield { text: '', done: true };\n return;\n }\n\n try {\n const data = JSON.parse(jsonText);\n\n if (data.error) {\n const errorMessage = data.error?.message || data.error || 'Unknown server error';\n const friendlyMessage = `Server error: ${errorMessage}`;\n console.warn(`[ApiClient] ${friendlyMessage}`);\n throw new Error(friendlyMessage);\n }\n\n // Check for done chunk first - it may not have a response field\n // This handles the final done chunk that contains threading metadata\n if (data.done === true) {\n hasReceivedContent = true;\n yield {\n text: '',\n done: true,\n audio: data.audio,\n audioFormat: data.audio_format || data.audioFormat,\n threading: data.threading // Pass through threading metadata\n };\n return;\n }\n\n // Note: Base64 audio filtering is handled by chatStore's sanitizeMessageContent\n // We keep response text as-is here and let the application layer decide\n const responseText = data.response || '';\n\n // Handle streaming audio chunks\n if (data.audio_chunk !== undefined) {\n yield {\n text: '',\n done: false,\n audio_chunk: data.audio_chunk,\n audioFormat: data.audioFormat || data.audio_format || 'opus',\n chunk_index: data.chunk_index ?? 0\n };\n }\n\n if (responseText || data.audio) {\n hasReceivedContent = true;\n yield {\n text: responseText,\n done: data.done || false,\n audio: data.audio,\n audioFormat: data.audio_format || data.audioFormat,\n threading: data.threading // Include threading if present\n };\n }\n\n } catch (parseError: any) {\n // Re-throw intentional errors (like moderation blocks) - don't swallow them\n if (parseError?.message?.startsWith('Server error:')) {\n throw parseError;\n }\n // Log JSON parse errors for debugging\n console.warn('[ApiClient] Unable to parse server response. This may be a temporary issue.');\n console.warn('[ApiClient] Parse error details:', parseError?.message);\n console.warn('[ApiClient] JSON text length:', jsonText?.length);\n console.warn('[ApiClient] JSON text preview (first 200 chars):', jsonText?.substring(0, 200));\n console.warn('[ApiClient] JSON text preview (last 200 chars):', jsonText?.substring(jsonText.length - 200));\n }\n } else if (line) {\n // Handle raw text chunks that are not in SSE format\n hasReceivedContent = true;\n yield { text: line, done: false };\n }\n }\n \n buffer = buffer.slice(lineStartIndex);\n\n if (buffer.length > 1000000) { // 1MB limit\n console.warn('[ApiClient] Buffer too large, truncating...');\n buffer = buffer.slice(-500000); // Keep last 500KB\n }\n }\n \n if (hasReceivedContent) {\n yield { text: '', done: true };\n }\n \n } finally {\n reader.releaseLock();\n }\n \n } catch (error: any) {\n if (error.name === 'AbortError') {\n throw new Error('Connection timed out. Please check if the server is running.');\n } else if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n public async getConversationHistory(\n sessionId?: string,\n limit?: number\n ): Promise<ConversationHistoryResponse> {\n /**\n * Retrieve persisted conversation history for a session.\n *\n * @param sessionId - Optional session ID to fetch. If not provided, uses current session.\n * @param limit - Optional maximum number of messages to return\n * @returns Promise resolving to conversation history payload\n */\n const targetSessionId = sessionId || this.sessionId;\n\n if (!targetSessionId) {\n throw new Error('No session ID provided and no current session available');\n }\n\n const headers: Record<string, string> = {};\n if (this.apiKey) {\n headers['X-API-Key'] = this.apiKey;\n }\n\n try {\n const url = new URL(`${this.apiUrl}/admin/chat-history/${targetSessionId}`);\n if (typeof limit === 'number' && Number.isFinite(limit) && limit > 0) {\n url.searchParams.set('limit', String(Math.floor(limit)));\n }\n\n const response = await fetch(url.toString(), {\n ...this.getFetchOptions({\n method: 'GET',\n headers\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to fetch conversation history: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n const messages = Array.isArray(result?.messages) ? result.messages : [];\n const count = typeof result?.count === 'number' ? result.count : messages.length;\n\n return {\n session_id: result?.session_id || targetSessionId,\n messages,\n count\n };\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n public async clearConversationHistory(sessionId?: string): Promise<{\n status: string;\n message: string;\n session_id: string;\n deleted_count: number;\n timestamp: string;\n }> {\n /**\n * Clear conversation history for a session.\n *\n * @param sessionId - Optional session ID to clear. If not provided, uses current session.\n * @returns Promise resolving to operation result\n * @throws Error if the operation fails\n */\n const targetSessionId = sessionId || this.sessionId;\n\n if (!targetSessionId) {\n throw new Error('No session ID provided and no current session available');\n }\n\n if (!this.apiKey) {\n throw new Error('API key is required for clearing conversation history');\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Session-ID': targetSessionId,\n 'X-API-Key': this.apiKey\n };\n\n try {\n const response = await fetch(`${this.apiUrl}/admin/chat-history/${targetSessionId}`, {\n ...this.getFetchOptions({\n method: 'DELETE',\n headers\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to clear conversation history: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n return result;\n\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n public async deleteConversationWithFiles(sessionId?: string, fileIds?: string[]): Promise<{\n status: string;\n message: string;\n session_id: string;\n deleted_messages: number;\n deleted_files: number;\n file_deletion_errors: string[] | null;\n timestamp: string;\n }> {\n /**\n * Delete a conversation and all associated files.\n *\n * This method performs a complete conversation deletion:\n * - Deletes each file provided in fileIds (metadata, content, and vector store chunks)\n * - Clears conversation history\n *\n * File tracking is managed by the frontend (localStorage). The backend is stateless\n * and requires fileIds to be provided explicitly.\n *\n * @param sessionId - Optional session ID to delete. If not provided, uses current session.\n * @param fileIds - Optional list of file IDs to delete (from conversation's attachedFiles)\n * @returns Promise resolving to deletion result with counts\n * @throws Error if the operation fails\n */\n const targetSessionId = sessionId || this.sessionId;\n\n if (!targetSessionId) {\n throw new Error('No session ID provided and no current session available');\n }\n\n if (!this.apiKey) {\n throw new Error('API key is required for deleting conversation');\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-Session-ID': targetSessionId,\n 'X-API-Key': this.apiKey\n };\n\n // Build URL with file_ids query parameter\n const fileIdsParam = fileIds && fileIds.length > 0 ? `?file_ids=${fileIds.join(',')}` : '';\n const url = `${this.apiUrl}/admin/conversations/${targetSessionId}${fileIdsParam}`;\n\n try {\n const response = await fetch(url, {\n ...this.getFetchOptions({\n method: 'DELETE',\n headers\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to delete conversation: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n return result;\n\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Create a conversation thread from a parent message.\n *\n * @param messageId - ID of the parent message\n * @param sessionId - Session ID of the parent conversation\n * @returns Promise resolving to thread information\n * @throws Error if the operation fails\n */\n public async createThread(messageId: string, sessionId: string): Promise<ThreadInfo> {\n if (!this.apiKey) {\n throw new Error('API key is required for creating threads');\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-API-Key': this.apiKey\n };\n\n try {\n const response = await fetch(`${this.apiUrl}/api/threads`, {\n ...this.getFetchOptions({\n method: 'POST',\n headers,\n body: JSON.stringify({\n message_id: messageId,\n session_id: sessionId\n })\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to create thread: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n return result;\n\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Get thread information by thread ID.\n *\n * @param threadId - Thread identifier\n * @returns Promise resolving to thread information\n * @throws Error if the operation fails\n */\n public async getThreadInfo(threadId: string): Promise<ThreadInfo> {\n if (!this.apiKey) {\n throw new Error('API key is required for getting thread info');\n }\n\n const headers: Record<string, string> = {\n 'X-API-Key': this.apiKey\n };\n\n try {\n const response = await fetch(`${this.apiUrl}/api/threads/${threadId}`, {\n ...this.getFetchOptions({\n method: 'GET',\n headers\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to get thread info: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n return result;\n\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Delete a thread and its associated dataset.\n *\n * @param threadId - Thread identifier\n * @returns Promise resolving to deletion result\n * @throws Error if the operation fails\n */\n public async deleteThread(threadId: string): Promise<{ status: string; message: string; thread_id: string }> {\n if (!this.apiKey) {\n throw new Error('API key is required for deleting threads');\n }\n\n const headers: Record<string, string> = {\n 'X-API-Key': this.apiKey\n };\n\n try {\n const response = await fetch(`${this.apiUrl}/api/threads/${threadId}`, {\n ...this.getFetchOptions({\n method: 'DELETE',\n headers\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to delete thread: ${response.status} ${errorText}`);\n }\n\n const result = await response.json();\n return result;\n\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Upload a file for processing and indexing.\n *\n * @param file - The file to upload\n * @returns Promise resolving to upload response with file_id\n * @throws Error if upload fails\n */\n public async uploadFile(file: File): Promise<FileUploadResponse> {\n if (!this.apiKey) {\n throw new Error('API key is required for file upload');\n }\n\n const formData = new FormData();\n formData.append('file', file);\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files/upload`, {\n ...this.getFetchOptions({\n method: 'POST',\n body: formData\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to upload file: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * List all files for the current API key.\n * \n * @returns Promise resolving to list of file information\n * @throws Error if request fails\n */\n public async listFiles(): Promise<FileInfo[]> {\n if (!this.apiKey) {\n throw new Error('API key is required for listing files');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to list files: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Get information about a specific file.\n * \n * @param fileId - The file ID\n * @returns Promise resolving to file information\n * @throws Error if file not found or request fails\n */\n public async getFileInfo(fileId: string): Promise<FileInfo> {\n if (!this.apiKey) {\n throw new Error('API key is required for getting file info');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files/${fileId}`, {\n ...this.getFetchOptions({\n method: 'GET'\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to get file info: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Query a specific file using semantic search.\n * \n * @param fileId - The file ID\n * @param query - The search query\n * @param maxResults - Maximum number of results (default: 10)\n * @returns Promise resolving to query results\n * @throws Error if query fails\n */\n public async queryFile(fileId: string, query: string, maxResults: number = 10): Promise<FileQueryResponse> {\n if (!this.apiKey) {\n throw new Error('API key is required for querying files');\n }\n\n try {\n const response = await fetch(`${this.apiUrl}/api/files/${fileId}/query`, {\n ...this.getFetchOptions({\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({ query, max_results: maxResults })\n })\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to query file: ${response.status} ${errorText}`);\n }\n\n return await response.json();\n } catch (error: any) {\n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n throw new Error('Could not connect to the server. Please check if the server is running.');\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Delete a specific file.\n * \n * @param fileId - The file ID\n * @returns Promise resolving to deletion result\n * @throws Error if deletion fails\n */\n public async deleteFile(fileId: string): Promise<{ message: string; file_id: string }> {\n if (!this.apiKey) {\n throw new Error('API key is required for deleting files');\n }\n\n const url = `${this.apiUrl}/api/files/${fileId}`;\n const fetchOptions = this.getFetchOptions({\n method: 'DELETE'\n });\n\n try {\n const response = await fetch(url, fetchOptions);\n\n if (!response.ok) {\n const errorText = await response.text();\n let friendlyMessage: string;\n try {\n const errorJson = JSON.parse(errorText);\n friendlyMessage = errorJson.detail || errorJson.message || `Failed to delete file (HTTP ${response.status})`;\n } catch {\n friendlyMessage = `Failed to delete file (HTTP ${response.status})`;\n }\n console.warn(`[ApiClient] ${friendlyMessage}`);\n throw new Error(friendlyMessage);\n }\n\n const result = await response.json();\n return result;\n } catch (error: any) {\n // Extract user-friendly error message\n let friendlyMessage: string;\n \n if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {\n friendlyMessage = 'Could not connect to the server. Please check if the server is running.';\n } else if (error.message && !error.message.includes('Failed to delete file')) {\n // Use existing message if it's already user-friendly\n friendlyMessage = error.message;\n } else {\n friendlyMessage = `Failed to delete file. Please try again.`;\n }\n \n console.warn(`[ApiClient] ${friendlyMessage}`);\n throw new Error(friendlyMessage);\n }\n }\n}\n\n// Legacy compatibility functions - these create a default client instance\n// These are kept for backward compatibility but should be deprecated in favor of the class-based approach\n\nlet defaultClient: ApiClient | null = null;\n\n// Configure the API with a custom URL, API key (optional), and session ID (optional)\nexport const configureApi = (apiUrl: string, apiKey: string | null = null, sessionId: string | null = null): void => {\n defaultClient = new ApiClient({ apiUrl, apiKey, sessionId });\n}\n\n// Legacy streamChat function that uses the default client\nexport async function* streamChat(\n message: string,\n stream: boolean = true,\n fileIds?: string[],\n threadId?: string,\n audioInput?: string,\n audioFormat?: string,\n language?: string,\n returnAudio?: boolean,\n ttsVoice?: string,\n sourceLanguage?: string,\n targetLanguage?: string\n): AsyncGenerator<StreamResponse> {\n if (!defaultClient) {\n throw new Error('API not configured. Please call configureApi() with your server URL before using any API functions.');\n }\n \n yield* defaultClient.streamChat(\n message, \n stream, \n fileIds,\n threadId,\n audioInput,\n audioFormat,\n language,\n returnAudio,\n ttsVoice,\n sourceLanguage,\n targetLanguage\n );\n}\n"],"names":["httpAgent","httpsAgent","http","https","_a","_b","err","ApiClient","config","__publicField","sessionId","response","fetchError","errorText","errorDetail","friendlyMessage","errorJson","status","error","options","baseOptions","agent","headers","incomingHeaders","key","value","message","stream","fileIds","threadId","audioInput","audioFormat","language","returnAudio","ttsVoice","sourceLanguage","targetLanguage","request","_c","controller","timeoutId","data","reader","decoder","buffer","hasReceivedContent","done","chunk","lineStartIndex","newlineIndex","line","jsonText","responseText","parseError","limit","targetSessionId","url","result","messages","count","fileIdsParam","messageId","file","formData","fileId","query","maxResults","fetchOptions","defaultClient","configureApi","apiUrl","apiKey","streamChat"],"mappings":";;;AACA,IAAIA,IAAiB,MACjBC,IAAkB;AAGlB,OAAO,SAAW,OAEpB,QAAQ,IAAI;AAAA;AAAA,EAEV,OAAO,MAAM,EAAE,MAAM,MAAM,IAAI;AAAA;AAAA,EAE/B,OAAO,OAAO,EAAE,MAAM,MAAM,IAAI;AAAA,CACjC,EAAE,KAAK,CAAC,CAACC,GAAMC,CAAK,MAAM;AAX7B,MAA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C,IAAe,CAACC,GAAgBC,IAAwB,MAAM7D,IAA2B,SAAe;AACnH,EAAA0D,IAAgB,IAAI7D,EAAU,EAAE,QAAA+D,GAAQ,QAAAC,GAAQ,WAAA7D,GAAW;AAC7D;AAGA,gBAAuB8D,EACrB9C,GACAC,IAAkB,IAClBC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACgC;AAChC,MAAI,CAACgC;AACH,UAAM,IAAI,MAAM,qGAAqG;AAGvH,SAAOA,EAAc;AAAA,IACnB1C;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,IACAC;AAAA,EAAA;AAEJ;"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@schmitech/chatbot-api",
3
3
  "private": false,
4
- "version": "2.1.2",
4
+ "version": "2.1.4",
5
5
  "description": "API client for the ORBIT MCP server",
6
6
  "type": "module",
7
7
  "main": "./dist/api.cjs",