@lanonasis/mem-intel-sdk 2.0.2 → 2.0.5
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/CHANGELOG.md +16 -0
- package/README.md +81 -10
- package/dist/core/behavior-types.d.ts +336 -0
- package/dist/core/client.d.ts +97 -1
- package/dist/core/errors.d.ts +0 -1
- package/dist/core/index.cjs +205 -0
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.js +203 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/prediction-types.d.ts +0 -1
- package/dist/core/types.d.ts +0 -1
- package/dist/index-sdk.d.ts +2 -1
- package/dist/index.cjs +245 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +241 -1
- package/dist/index.js.map +1 -1
- package/dist/node/client.d.ts +0 -1
- package/dist/node/index.cjs +170 -0
- package/dist/node/index.cjs.map +1 -1
- package/dist/node/index.d.ts +0 -1
- package/dist/node/index.js +170 -0
- package/dist/node/index.js.map +1 -1
- package/dist/react/context/MemoryIntelligenceProvider.d.ts +0 -1
- package/dist/react/hooks/useMemoryIntelligence.d.ts +0 -1
- package/dist/react/index.cjs +170 -0
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.ts +0 -1
- package/dist/react/index.js +170 -0
- package/dist/react/index.js.map +1 -1
- package/dist/server/index.cjs +352 -0
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.ts +0 -1
- package/dist/server/index.js +352 -0
- package/dist/server/index.js.map +1 -1
- package/dist/server/mcp-server.d.ts +0 -1
- package/dist/utils/embeddings.d.ts +0 -1
- package/dist/utils/formatting.d.ts +0 -1
- package/dist/utils/http-client.d.ts +0 -1
- package/dist/utils/index.d.ts +0 -1
- package/dist/utils/prediction-engine.d.ts +0 -1
- package/dist/utils/response-adapter.d.ts +0 -1
- package/dist/utils/similarity.d.ts +0 -1
- package/dist/vue/composables/useMemoryIntelligence.d.ts +0 -1
- package/dist/vue/index.d.ts +0 -1
- package/package.json +2 -2
- package/dist/core/client.d.ts.map +0 -1
- package/dist/core/errors.d.ts.map +0 -1
- package/dist/core/index.d.ts.map +0 -1
- package/dist/core/prediction-types.d.ts.map +0 -1
- package/dist/core/types.d.ts.map +0 -1
- package/dist/index-sdk.d.ts.map +0 -1
- package/dist/node/client.d.ts.map +0 -1
- package/dist/node/index.d.ts.map +0 -1
- package/dist/react/context/MemoryIntelligenceProvider.d.ts.map +0 -1
- package/dist/react/hooks/useMemoryIntelligence.d.ts.map +0 -1
- package/dist/react/index.d.ts.map +0 -1
- package/dist/server/index.d.ts.map +0 -1
- package/dist/server/mcp-server.d.ts.map +0 -1
- package/dist/utils/embeddings.d.ts.map +0 -1
- package/dist/utils/formatting.d.ts.map +0 -1
- package/dist/utils/http-client.d.ts.map +0 -1
- package/dist/utils/index.d.ts.map +0 -1
- package/dist/utils/prediction-engine.d.ts.map +0 -1
- package/dist/utils/response-adapter.d.ts.map +0 -1
- package/dist/utils/similarity.d.ts.map +0 -1
- package/dist/vue/composables/useMemoryIntelligence.d.ts.map +0 -1
- package/dist/vue/index.d.ts.map +0 -1
package/dist/react/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/errors.ts","../../src/utils/response-adapter.ts","../../src/utils/http-client.ts","../../src/core/client.ts","../../src/react/context/MemoryIntelligenceProvider.tsx","../../src/react/hooks/useMemoryIntelligence.ts","../../src/core/types.ts"],"names":[],"mappings":";;;;;;;;AAIO,IAAM,uBAAA,GAAN,cAAsC,KAAA,CAAM;AAAA,EACjD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,yBAAA;AAAA,EACd;AACF;AAEO,IAAM,kBAAA,GAAN,cAAiC,uBAAA,CAAwB;AAAA,EAC9D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,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,CAAC","file":"index.js","sourcesContent":["/**\n * SDK-specific error classes\n */\n\nexport class MemoryIntelligenceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"MemoryIntelligenceError\";\n }\n}\n\nexport class ConfigurationError extends MemoryIntelligenceError {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigurationError\";\n }\n}\n\nexport class MemoryNotFoundError extends MemoryIntelligenceError {\n constructor(memoryId: string) {\n super(`Memory not found: ${memoryId}`);\n this.name = \"MemoryNotFoundError\";\n }\n}\n\nexport class DatabaseError extends MemoryIntelligenceError {\n constructor(message: string, public originalError?: Error) {\n super(message);\n this.name = \"DatabaseError\";\n }\n}\n\nexport class EmbeddingError extends MemoryIntelligenceError {\n constructor(message: string, public originalError?: Error) {\n super(message);\n this.name = \"EmbeddingError\";\n }\n}\n\nexport class ValidationError extends MemoryIntelligenceError {\n constructor(message: string) {\n super(message);\n this.name = \"ValidationError\";\n }\n}\n","/**\n * Response Adapter for Edge Function envelope format\n * Handles the transition between direct API responses and Edge Function wrapped responses\n */\n\nimport { EdgeFunctionResponse } from \"../core/types.js\";\nimport { ApiResponse } from \"./http-client.js\";\n\nexport interface UsageInfo {\n tokens_used: number;\n cost_usd: number;\n cached: boolean;\n}\n\nexport interface TierInfo {\n tier: string;\n usage_remaining: number;\n}\n\nexport interface UnwrappedResponse<T> {\n data?: T;\n error?: {\n message: string;\n code?: string;\n };\n usage?: UsageInfo;\n tier_info?: TierInfo;\n status: number;\n}\n\n/**\n * Adapts Edge Function envelope response to SDK internal format\n * Edge Functions return: { success, data, error, usage, tier_info }\n * SDK expects: { data, error, status }\n */\nexport function adaptEdgeFunctionResponse<T>(\n httpResponse: ApiResponse<EdgeFunctionResponse<T>>\n): UnwrappedResponse<T> {\n // If HTTP request itself failed\n if (httpResponse.error) {\n return {\n status: httpResponse.status,\n error: httpResponse.error,\n };\n }\n\n const envelope = httpResponse.data;\n\n // If no envelope data (shouldn't happen)\n if (!envelope) {\n return {\n status: httpResponse.status,\n error: {\n message: \"Empty response from server\",\n code: \"EMPTY_RESPONSE\",\n },\n };\n }\n\n // If Edge Function returned an error\n if (!envelope.success && envelope.error) {\n return {\n status: httpResponse.status,\n error: envelope.error,\n usage: envelope.usage,\n tier_info: envelope.tier_info,\n };\n }\n\n // Successful response\n return {\n status: httpResponse.status,\n data: envelope.data,\n usage: envelope.usage,\n tier_info: envelope.tier_info,\n };\n}\n\n/**\n * Checks if a response appears to be an Edge Function envelope\n */\nexport function isEdgeFunctionEnvelope(data: unknown): data is EdgeFunctionResponse<unknown> {\n if (typeof data !== \"object\" || data === null) {\n return false;\n }\n\n const obj = data as Record<string, unknown>;\n return \"success\" in obj && typeof obj.success === \"boolean\";\n}\n\n/**\n * Smart adapter that detects response format and adapts accordingly\n * Supports both direct API responses and Edge Function envelopes\n */\nexport function adaptResponse<T>(\n httpResponse: ApiResponse<T | EdgeFunctionResponse<T>>\n): UnwrappedResponse<T> {\n // If HTTP request itself failed\n if (httpResponse.error) {\n return {\n status: httpResponse.status,\n error: httpResponse.error,\n };\n }\n\n const responseData = httpResponse.data;\n\n // Check if it's an Edge Function envelope\n if (isEdgeFunctionEnvelope(responseData)) {\n return adaptEdgeFunctionResponse({\n status: httpResponse.status,\n data: responseData as EdgeFunctionResponse<T>,\n });\n }\n\n // Direct API response (legacy format)\n return {\n status: httpResponse.status,\n data: responseData as T,\n };\n}\n\n/**\n * Cache entry for offline fallback support\n */\nexport interface CacheEntry<T> {\n data: T;\n timestamp: number;\n endpoint: string;\n params?: Record<string, unknown>;\n}\n\n/**\n * Simple in-memory cache for offline fallback\n */\nexport class ResponseCache {\n private cache: Map<string, CacheEntry<unknown>> = new Map();\n private ttl: number;\n\n constructor(ttlMs: number = 300000) { // Default 5 minutes\n this.ttl = ttlMs;\n }\n\n private generateKey(endpoint: string, params?: Record<string, unknown>): string {\n const paramStr = params ? JSON.stringify(params) : \"\";\n return `${endpoint}:${paramStr}`;\n }\n\n set<T>(endpoint: string, data: T, params?: Record<string, unknown>): void {\n const key = this.generateKey(endpoint, params);\n this.cache.set(key, {\n data,\n timestamp: Date.now(),\n endpoint,\n params,\n });\n }\n\n get<T>(endpoint: string, params?: Record<string, unknown>): T | null {\n const key = this.generateKey(endpoint, params);\n const entry = this.cache.get(key);\n\n if (!entry) {\n return null;\n }\n\n // Check if expired\n if (Date.now() - entry.timestamp > this.ttl) {\n this.cache.delete(key);\n return null;\n }\n\n return entry.data as T;\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Clean up expired entries\n */\n cleanup(): void {\n const now = Date.now();\n for (const [key, entry] of this.cache.entries()) {\n if (now - entry.timestamp > this.ttl) {\n this.cache.delete(key);\n }\n }\n }\n}\n","/**\n * HTTP client for Lanonasis API\n * Supports Edge Function envelope format with caching for offline fallback\n */\n\nimport { ConfigurationError } from \"../core/errors.js\";\nimport { EdgeFunctionResponse, ProcessingMode } from \"../core/types.js\";\nimport { adaptResponse, ResponseCache, UsageInfo, TierInfo } from \"./response-adapter.js\";\n\nexport interface HttpClientConfig {\n apiUrl: string;\n apiKey?: string;\n authToken?: string;\n authType?: \"apiKey\" | \"bearer\";\n allowMissingAuth?: boolean;\n timeout?: number;\n headers?: Record<string, string>;\n processingMode?: ProcessingMode;\n enableCache?: boolean;\n cacheTTL?: number;\n}\n\nexport interface ApiResponse<T = any> {\n data?: T;\n error?: {\n message: string;\n code?: string;\n };\n status: number;\n}\n\nexport interface EnhancedApiResponse<T = any> extends ApiResponse<T> {\n usage?: UsageInfo;\n tier_info?: TierInfo;\n fromCache?: boolean;\n}\n\nexport class HttpClient {\n private apiUrl: string;\n private apiKey: string | undefined;\n private timeout: number;\n private headers: Record<string, string>;\n private processingMode: ProcessingMode;\n private cache: ResponseCache | null;\n\n constructor(config: HttpClientConfig) {\n this.apiUrl = config.apiUrl.replace(/\\/$/, \"\"); // Remove trailing slash\n\n // Determine auth type: explicit config, or infer from provided credentials\n let authType: \"apiKey\" | \"bearer\";\n if (config.authType) {\n authType = config.authType;\n } else if (config.apiKey) {\n authType = \"apiKey\";\n } else if (config.authToken) {\n authType = \"bearer\";\n } else if (config.allowMissingAuth) {\n // Default to apiKey when no auth provided but missing auth is allowed\n authType = \"apiKey\";\n } else {\n throw new ConfigurationError(\n \"Authentication required: provide apiKey, authToken, or set allowMissingAuth to true\"\n );\n }\n\n const allowMissingAuth = Boolean(config.allowMissingAuth);\n\n if (authType === \"apiKey\") {\n if (!config.apiKey && !allowMissingAuth) {\n throw new ConfigurationError(\"API key is required when authType is 'apiKey'\");\n }\n if (config.apiKey && !config.apiKey.startsWith(\"lano_\")) {\n throw new ConfigurationError(\n \"Invalid API key format. API key should start with 'lano_'\"\n );\n }\n } else if (!config.authToken && !allowMissingAuth) {\n throw new ConfigurationError(\"Bearer token is required when authType is 'bearer'\");\n }\n\n this.apiKey = config.apiKey;\n this.timeout = config.timeout || 30000;\n this.processingMode = config.processingMode || \"api\";\n\n const baseHeaders: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...config.headers,\n };\n\n if (authType === \"apiKey\" && this.apiKey && !(\"X-API-Key\" in baseHeaders)) {\n baseHeaders[\"X-API-Key\"] = this.apiKey;\n }\n\n if (authType === \"bearer\" && config.authToken && !(\"Authorization\" in baseHeaders)) {\n baseHeaders[\"Authorization\"] = `Bearer ${config.authToken}`;\n }\n\n this.headers = baseHeaders;\n\n // Initialize cache for offline-fallback mode\n if (config.enableCache !== false && this.processingMode === \"offline-fallback\") {\n this.cache = new ResponseCache(config.cacheTTL || 300000);\n } else {\n this.cache = null;\n }\n }\n\n /**\n * Get the current processing mode\n */\n getProcessingMode(): ProcessingMode {\n return this.processingMode;\n }\n\n /**\n * Check if cache is enabled\n */\n isCacheEnabled(): boolean {\n return this.cache !== null;\n }\n\n /**\n * Clear the response cache\n */\n clearCache(): void {\n this.cache?.clear();\n }\n\n private async request<T>(\n method: string,\n endpoint: string,\n data?: any\n ): Promise<ApiResponse<T>> {\n const url = `${this.apiUrl}${endpoint}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const options: RequestInit = {\n method,\n headers: this.headers,\n signal: controller.signal,\n };\n\n if (data && (method === \"POST\" || method === \"PUT\" || method === \"PATCH\")) {\n options.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, options);\n clearTimeout(timeoutId);\n\n const responseData = await response.json() as any;\n\n if (!response.ok) {\n return {\n status: response.status,\n error: {\n message: responseData?.message || responseData?.error || \"Request failed\",\n code: responseData?.code,\n },\n };\n }\n\n return {\n status: response.status,\n data: responseData as T,\n };\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n return {\n status: 408,\n error: {\n message: `Request timeout after ${this.timeout}ms`,\n code: \"TIMEOUT\",\n },\n };\n }\n\n return {\n status: 0,\n error: {\n message: error.message,\n code: \"NETWORK_ERROR\",\n },\n };\n }\n\n return {\n status: 0,\n error: {\n message: \"Unknown error occurred\",\n code: \"UNKNOWN_ERROR\",\n },\n };\n }\n }\n\n /**\n * Enhanced request that handles Edge Function envelope format\n * and supports offline-fallback caching\n */\n private async enhancedRequest<T>(\n method: string,\n endpoint: string,\n data?: any\n ): Promise<EnhancedApiResponse<T>> {\n const cacheKey = data ? JSON.stringify(data) : undefined;\n\n // Try API request first\n const rawResponse = await this.request<EdgeFunctionResponse<T> | T>(method, endpoint, data);\n\n // Handle network errors with offline fallback\n if (rawResponse.error?.code === \"NETWORK_ERROR\" || rawResponse.error?.code === \"TIMEOUT\") {\n if (this.processingMode === \"offline-fallback\" && this.cache) {\n const cached = this.cache.get<T>(endpoint, cacheKey ? JSON.parse(cacheKey) : undefined);\n if (cached) {\n return {\n status: 200,\n data: cached,\n fromCache: true,\n };\n }\n }\n // No cache available, return original error\n return {\n status: rawResponse.status,\n error: rawResponse.error,\n fromCache: false,\n };\n }\n\n // Adapt response (handles both direct and envelope formats)\n const adapted = adaptResponse<T>(rawResponse);\n\n // Cache successful responses for offline fallback\n if (!adapted.error && adapted.data && this.cache) {\n this.cache.set(endpoint, adapted.data, cacheKey ? JSON.parse(cacheKey) : undefined);\n }\n\n return {\n status: adapted.status,\n data: adapted.data,\n error: adapted.error,\n usage: adapted.usage,\n tier_info: adapted.tier_info,\n fromCache: false,\n };\n }\n\n async get<T>(endpoint: string): Promise<ApiResponse<T>> {\n return this.request<T>(\"GET\", endpoint);\n }\n\n async post<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {\n return this.request<T>(\"POST\", endpoint, data);\n }\n\n async put<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {\n return this.request<T>(\"PUT\", endpoint, data);\n }\n\n async patch<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {\n return this.request<T>(\"PATCH\", endpoint, data);\n }\n\n async delete<T>(endpoint: string): Promise<ApiResponse<T>> {\n return this.request<T>(\"DELETE\", endpoint);\n }\n\n // Enhanced methods with Edge Function envelope support\n\n async getEnhanced<T>(endpoint: string): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"GET\", endpoint);\n }\n\n async postEnhanced<T>(endpoint: string, data?: any): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"POST\", endpoint, data);\n }\n\n async putEnhanced<T>(endpoint: string, data?: any): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"PUT\", endpoint, data);\n }\n\n async patchEnhanced<T>(endpoint: string, data?: any): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"PATCH\", endpoint, data);\n }\n\n async deleteEnhanced<T>(endpoint: string): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"DELETE\", endpoint);\n }\n}\n","/**\n * Core Memory Intelligence Client\n * Supports API-first with offline-fallback capability\n */\n\nimport {\n MemoryIntelligenceConfig,\n AnalyzePatternsParams,\n PatternAnalysis,\n SuggestTagsParams,\n TagSuggestionsResult,\n FindRelatedParams,\n RelatedMemoriesResult,\n DetectDuplicatesParams,\n DuplicatesResult,\n ExtractInsightsParams,\n InsightsResult,\n HealthCheckParams,\n MemoryHealth,\n QueryMemoriesOptions,\n MemoryEntry,\n ProcessingMode,\n} from \"./types.js\";\nimport {\n PredictiveRecallParams,\n PredictiveRecallResult,\n} from \"./prediction-types.js\";\nimport { DatabaseError } from \"./errors.js\";\nimport { HttpClient } from \"../utils/http-client.js\";\nimport { UsageInfo, TierInfo } from \"../utils/response-adapter.js\";\n\nconst DEFAULT_API_URL = \"https://api.lanonasis.com/api/v1\";\n\nexport interface IntelligenceResponse<T> {\n data: T;\n usage?: UsageInfo;\n tier_info?: TierInfo;\n fromCache?: boolean;\n}\n\nexport class MemoryIntelligenceClient {\n private httpClient: HttpClient;\n private defaultResponseFormat: \"json\" | \"markdown\";\n private processingMode: ProcessingMode;\n\n constructor(config: MemoryIntelligenceConfig) {\n this.processingMode = config.processingMode || \"api\";\n const authType = config.authType || (config.apiKey ? \"apiKey\" : \"bearer\");\n\n this.httpClient = new HttpClient({\n apiUrl: config.apiUrl || DEFAULT_API_URL,\n apiKey: config.apiKey,\n authToken: config.authToken,\n authType,\n allowMissingAuth: config.allowMissingAuth,\n timeout: config.timeout,\n headers: config.headers,\n processingMode: this.processingMode,\n enableCache: config.enableCache,\n cacheTTL: config.cacheTTL,\n });\n\n this.defaultResponseFormat = config.responseFormat || \"markdown\";\n }\n\n /**\n * Get the current processing mode\n */\n getProcessingMode(): ProcessingMode {\n return this.processingMode;\n }\n\n /**\n * Check if cache is enabled (for offline-fallback mode)\n */\n isCacheEnabled(): boolean {\n return this.httpClient.isCacheEnabled();\n }\n\n /**\n * Clear the response cache\n */\n clearCache(): void {\n this.httpClient.clearCache();\n }\n\n /**\n * Get HTTP client for direct API access\n */\n public getHttpClient(): HttpClient {\n return this.httpClient;\n }\n\n /**\n * Query memories from the API\n */\n public async queryMemories(\n userId: string,\n options: QueryMemoriesOptions = {}\n ): Promise<MemoryEntry[]> {\n const { type, limit = 100, offset = 0 } = options;\n\n const params = new URLSearchParams({\n user_id: userId,\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (type) {\n params.append(\"type\", type);\n }\n\n const response = await this.httpClient.get<{ memories: MemoryEntry[] }>(\n `/intelligence/memories?${params.toString()}`\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to query memories: ${response.error.message}`);\n }\n\n return response.data?.memories || [];\n }\n\n /**\n * Analyze usage patterns and trends in memory collection\n */\n async analyzePatterns(params: AnalyzePatternsParams): Promise<IntelligenceResponse<PatternAnalysis>> {\n const response = await this.httpClient.postEnhanced<PatternAnalysis>(\n \"/intelligence/analyze-patterns\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to analyze patterns: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Get AI-powered tag suggestions for a memory\n */\n async suggestTags(params: SuggestTagsParams): Promise<IntelligenceResponse<TagSuggestionsResult>> {\n const response = await this.httpClient.postEnhanced<TagSuggestionsResult>(\n \"/intelligence/suggest-tags\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to suggest tags: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Find semantically related memories using vector similarity\n */\n async findRelated(params: FindRelatedParams): Promise<IntelligenceResponse<RelatedMemoriesResult>> {\n const response = await this.httpClient.postEnhanced<RelatedMemoriesResult>(\n \"/intelligence/find-related\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to find related memories: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Detect potential duplicate memories\n */\n async detectDuplicates(params: DetectDuplicatesParams): Promise<IntelligenceResponse<DuplicatesResult>> {\n const response = await this.httpClient.postEnhanced<DuplicatesResult>(\n \"/intelligence/detect-duplicates\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to detect duplicates: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Extract insights and patterns from memories\n */\n async extractInsights(params: ExtractInsightsParams): Promise<IntelligenceResponse<InsightsResult>> {\n const response = await this.httpClient.postEnhanced<InsightsResult>(\n \"/intelligence/extract-insights\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to extract insights: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Check the health and organization quality of memories\n */\n async healthCheck(params: HealthCheckParams): Promise<IntelligenceResponse<MemoryHealth>> {\n const response = await this.httpClient.postEnhanced<MemoryHealth>(\n \"/intelligence/health-check\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to check health: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Predictive Memory Recall - AI that anticipates what you need\n *\n * Uses a weighted scoring algorithm:\n * - Semantic similarity to current context (40%)\n * - Temporal relevance (recency decay curve) (30%)\n * - Usage frequency (20%)\n * - Serendipity factor (adjacent discoveries) (10%)\n *\n * @example\n * ```typescript\n * const result = await client.predictiveRecall({\n * userId: \"user-123\",\n * context: {\n * currentProject: \"Building dashboard components\",\n * recentTopics: [\"React\", \"performance\", \"hooks\"],\n * contextText: \"Optimizing render performance for data tables\"\n * },\n * limit: 5,\n * minConfidence: 50\n * });\n *\n * for (const prediction of result.data.predictions) {\n * console.log(`[${prediction.confidence}%] ${prediction.title}`);\n * console.log(` Reason: ${prediction.reason}`);\n * console.log(` Action: ${prediction.suggestedAction}`);\n * }\n * ```\n */\n async predictiveRecall(\n params: PredictiveRecallParams\n ): Promise<IntelligenceResponse<PredictiveRecallResult>> {\n const response = await this.httpClient.postEnhanced<PredictiveRecallResult>(\n \"/intelligence/predictive-recall\",\n {\n userId: params.userId,\n context: params.context,\n limit: params.limit || 5,\n minConfidence: params.minConfidence || 40,\n includeSerendipity: params.includeSerendipity !== false,\n memoryTypes: params.memoryTypes,\n timeWindowDays: params.timeWindowDays || 90,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to get predictions: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Record feedback on a prediction (for improving accuracy over time)\n *\n * @example\n * ```typescript\n * await client.recordPredictionFeedback({\n * memoryId: \"mem-123\",\n * userId: \"user-123\",\n * useful: true,\n * action: \"clicked\"\n * });\n * ```\n */\n async recordPredictionFeedback(params: {\n memoryId: string;\n userId: string;\n useful: boolean;\n action: \"clicked\" | \"saved\" | \"dismissed\" | \"ignored\";\n dismissReason?: \"not_relevant\" | \"already_know\" | \"not_now\" | \"other\";\n }): Promise<void> {\n await this.httpClient.post(\"/intelligence/prediction-feedback\", params);\n }\n}\n","/** @jsxImportSource react */\n/**\n * React Context Provider for Memory Intelligence\n */\n\nimport {\n createContext,\n useContext,\n ReactNode,\n useState,\n useEffect,\n} from \"react\";\nimport { MemoryIntelligenceClient } from \"../../core/client.js\";\nimport { MemoryIntelligenceConfig } from \"../../core/types.js\";\n\ninterface MemoryIntelligenceContextValue {\n client: MemoryIntelligenceClient;\n}\n\nconst MemoryIntelligenceContext =\n createContext<MemoryIntelligenceContextValue | null>(null);\n\ninterface MemoryIntelligenceProviderProps {\n config: MemoryIntelligenceConfig;\n children: ReactNode;\n}\n\nexport function MemoryIntelligenceProvider({\n config,\n children,\n}: MemoryIntelligenceProviderProps) {\n // Use useState to avoid recreating client on every render when config object is recreated\n const [client, setClient] = useState(\n () => new MemoryIntelligenceClient(config),\n );\n\n // Only recreate client when primitive config values change\n useEffect(() => {\n setClient(new MemoryIntelligenceClient(config));\n }, [\n config.apiUrl,\n config.apiKey,\n config.authToken,\n config.authType,\n config.allowMissingAuth,\n config.timeout,\n config.processingMode,\n config.enableCache,\n config.cacheTTL,\n ]);\n\n return (\n <MemoryIntelligenceContext.Provider value={{ client }}>\n {children}\n </MemoryIntelligenceContext.Provider>\n );\n}\n\nexport function useMemoryIntelligenceContext() {\n const context = useContext(MemoryIntelligenceContext);\n if (!context) {\n throw new Error(\n \"useMemoryIntelligenceContext must be used within MemoryIntelligenceProvider\",\n );\n }\n return context;\n}\n\nexport { MemoryIntelligenceContext };\n","/**\n * React hooks for Memory Intelligence using React Query\n */\n\nimport { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from \"@tanstack/react-query\";\nimport { useMemoryIntelligenceContext } from \"../context/MemoryIntelligenceProvider.js\";\nimport {\n PatternAnalysis,\n TagSuggestionsResult,\n RelatedMemoriesResult,\n DuplicatesResult,\n InsightsResult,\n MemoryHealth,\n AnalyzePatternsParams,\n SuggestTagsParams,\n FindRelatedParams,\n DetectDuplicatesParams,\n ExtractInsightsParams,\n HealthCheckParams,\n} from \"../../core/types.js\";\nimport {\n PredictiveRecallParams,\n PredictiveRecallResult,\n} from \"../../core/prediction-types.js\";\nimport type { IntelligenceResponse } from \"../../core/client.js\";\n\n/**\n * Get the Memory Intelligence client from context\n */\nexport function useMemoryIntelligence() {\n const { client } = useMemoryIntelligenceContext();\n return client;\n}\n\n/**\n * Hook for analyzing memory patterns\n *\n * @example\n * ```tsx\n * const { data, isLoading, error } = usePatternAnalysis({\n * userId: \"user-123\",\n * timeRangeDays: 30,\n * responseFormat: \"json\"\n * });\n * ```\n */\nexport function usePatternAnalysis(\n params: AnalyzePatternsParams,\n options?: Omit<UseQueryOptions<IntelligenceResponse<PatternAnalysis>>, \"queryKey\" | \"queryFn\">\n) {\n const client = useMemoryIntelligence();\n\n return useQuery<IntelligenceResponse<PatternAnalysis>>({\n queryKey: [\"memory-intelligence\", \"analyze-patterns\", params],\n queryFn: () => client.analyzePatterns(params),\n ...options,\n });\n}\n\n/**\n * Hook for getting tag suggestions\n *\n * @example\n * ```tsx\n * const { data, isLoading } = useTagSuggestions({\n * memoryId: \"mem-123\",\n * userId: \"user-123\",\n * maxSuggestions: 5\n * });\n * ```\n */\nexport function useTagSuggestions(\n params: SuggestTagsParams,\n options?: Omit<UseQueryOptions<IntelligenceResponse<TagSuggestionsResult>>, \"queryKey\" | \"queryFn\">\n) {\n const client = useMemoryIntelligence();\n\n return useQuery<IntelligenceResponse<TagSuggestionsResult>>({\n queryKey: [\"memory-intelligence\", \"suggest-tags\", params],\n queryFn: () => client.suggestTags(params),\n ...options,\n });\n}\n\n/**\n * Mutation hook for getting tag suggestions (if you need manual trigger)\n *\n * @example\n * ```tsx\n * const { mutate, data, isPending } = useTagSuggestionsMutation();\n *\n * // Later...\n * mutate({\n * memoryId: \"mem-123\",\n * userId: \"user-123\"\n * });\n * ```\n */\nexport function useTagSuggestionsMutation(\n options?: UseMutationOptions<IntelligenceResponse<TagSuggestionsResult>, Error, SuggestTagsParams>\n) {\n const client = useMemoryIntelligence();\n\n return useMutation<IntelligenceResponse<TagSuggestionsResult>, Error, SuggestTagsParams>({\n mutationFn: (params) => client.suggestTags(params),\n ...options,\n });\n}\n\n/**\n * Hook for finding related memories\n *\n * @example\n * ```tsx\n * const { data, isLoading } = useRelatedMemories({\n * memoryId: \"mem-123\",\n * userId: \"user-123\",\n * limit: 10,\n * similarityThreshold: 0.7\n * });\n * ```\n */\nexport function useRelatedMemories(\n params: FindRelatedParams,\n options?: Omit<UseQueryOptions<IntelligenceResponse<RelatedMemoriesResult>>, \"queryKey\" | \"queryFn\">\n) {\n const client = useMemoryIntelligence();\n\n return useQuery<IntelligenceResponse<RelatedMemoriesResult>>({\n queryKey: [\"memory-intelligence\", \"find-related\", params],\n queryFn: () => client.findRelated(params),\n ...options,\n });\n}\n\n/**\n * Hook for detecting duplicate memories\n *\n * @example\n * ```tsx\n * const { data, isLoading } = useDuplicateDetection({\n * userId: \"user-123\",\n * similarityThreshold: 0.9,\n * maxPairs: 20\n * });\n * ```\n */\nexport function useDuplicateDetection(\n params: DetectDuplicatesParams,\n options?: Omit<UseQueryOptions<IntelligenceResponse<DuplicatesResult>>, \"queryKey\" | \"queryFn\">\n) {\n const client = useMemoryIntelligence();\n\n return useQuery<IntelligenceResponse<DuplicatesResult>>({\n queryKey: [\"memory-intelligence\", \"detect-duplicates\", params],\n queryFn: () => client.detectDuplicates(params),\n ...options,\n });\n}\n\n/**\n * Mutation hook for duplicate detection (if you need manual trigger)\n */\nexport function useDuplicateDetectionMutation(\n options?: UseMutationOptions<IntelligenceResponse<DuplicatesResult>, Error, DetectDuplicatesParams>\n) {\n const client = useMemoryIntelligence();\n\n return useMutation<IntelligenceResponse<DuplicatesResult>, Error, DetectDuplicatesParams>({\n mutationFn: (params) => client.detectDuplicates(params),\n ...options,\n });\n}\n\n/**\n * Hook for extracting insights\n *\n * @example\n * ```tsx\n * const { data, isLoading } = useInsightExtraction({\n * userId: \"user-123\",\n * topic: \"machine learning\",\n * maxMemories: 20\n * });\n * ```\n */\nexport function useInsightExtraction(\n params: ExtractInsightsParams,\n options?: Omit<UseQueryOptions<IntelligenceResponse<InsightsResult>>, \"queryKey\" | \"queryFn\">\n) {\n const client = useMemoryIntelligence();\n\n return useQuery<IntelligenceResponse<InsightsResult>>({\n queryKey: [\"memory-intelligence\", \"extract-insights\", params],\n queryFn: () => client.extractInsights(params),\n ...options,\n });\n}\n\n/**\n * Mutation hook for insight extraction (if you need manual trigger)\n */\nexport function useInsightExtractionMutation(\n options?: UseMutationOptions<IntelligenceResponse<InsightsResult>, Error, ExtractInsightsParams>\n) {\n const client = useMemoryIntelligence();\n\n return useMutation<IntelligenceResponse<InsightsResult>, Error, ExtractInsightsParams>({\n mutationFn: (params) => client.extractInsights(params),\n ...options,\n });\n}\n\n/**\n * Hook for checking memory health\n *\n * @example\n * ```tsx\n * const { data, isLoading } = useHealthCheck({\n * userId: \"user-123\",\n * responseFormat: \"json\"\n * });\n * ```\n */\nexport function useHealthCheck(\n params: HealthCheckParams,\n options?: Omit<UseQueryOptions<IntelligenceResponse<MemoryHealth>>, \"queryKey\" | \"queryFn\">\n) {\n const client = useMemoryIntelligence();\n\n return useQuery<IntelligenceResponse<MemoryHealth>>({\n queryKey: [\"memory-intelligence\", \"health-check\", params],\n queryFn: () => client.healthCheck(params),\n ...options,\n });\n}\n\n/**\n * Mutation hook for health check (if you need manual trigger)\n */\nexport function useHealthCheckMutation(\n options?: UseMutationOptions<IntelligenceResponse<MemoryHealth>, Error, HealthCheckParams>\n) {\n const client = useMemoryIntelligence();\n\n return useMutation<IntelligenceResponse<MemoryHealth>, Error, HealthCheckParams>({\n mutationFn: (params) => client.healthCheck(params),\n ...options,\n });\n}\n\n/**\n * Hook for predictive memory recall\n *\n * AI-powered prediction of memories you'll need based on your current context.\n * Uses semantic similarity, temporal relevance, usage patterns, and serendipity\n * scoring to anticipate what you need before you realize it.\n *\n * @example\n * ```tsx\n * const { data, isLoading, error } = usePredictiveRecall({\n * userId: \"user-123\",\n * context: {\n * currentProject: \"Building dashboard components\",\n * recentTopics: [\"React\", \"performance\"],\n * contextText: \"Optimizing render performance\"\n * },\n * limit: 5,\n * minConfidence: 50\n * });\n *\n * // Display predictions\n * {data?.data.predictions.map(pred => (\n * <PredictionCard\n * key={pred.id}\n * title={pred.title}\n * confidence={pred.confidence}\n * reason={pred.reason}\n * action={pred.suggestedAction}\n * />\n * ))}\n * ```\n */\nexport function usePredictiveRecall(\n params: PredictiveRecallParams,\n options?: Omit<UseQueryOptions<IntelligenceResponse<PredictiveRecallResult>>, \"queryKey\" | \"queryFn\">\n) {\n const client = useMemoryIntelligence();\n\n return useQuery<IntelligenceResponse<PredictiveRecallResult>>({\n queryKey: [\"memory-intelligence\", \"predictive-recall\", params],\n queryFn: () => client.predictiveRecall(params),\n // Predictions should refresh periodically as context changes\n staleTime: 60000, // 1 minute\n ...options,\n });\n}\n\n/**\n * Mutation hook for predictive recall (if you need manual trigger)\n *\n * @example\n * ```tsx\n * const { mutate, data, isPending } = usePredictiveRecallMutation();\n *\n * // Trigger prediction when context changes\n * const handleContextChange = (newContext) => {\n * mutate({\n * userId: \"user-123\",\n * context: newContext,\n * limit: 5\n * });\n * };\n * ```\n */\nexport function usePredictiveRecallMutation(\n options?: UseMutationOptions<IntelligenceResponse<PredictiveRecallResult>, Error, PredictiveRecallParams>\n) {\n const client = useMemoryIntelligence();\n\n return useMutation<IntelligenceResponse<PredictiveRecallResult>, Error, PredictiveRecallParams>({\n mutationFn: (params) => client.predictiveRecall(params),\n ...options,\n });\n}\n\n/**\n * Hook for recording prediction feedback\n *\n * @example\n * ```tsx\n * const { mutate: recordFeedback } = usePredictionFeedback();\n *\n * // When user clicks on a prediction\n * const handlePredictionClick = (memoryId: string) => {\n * recordFeedback({\n * memoryId,\n * userId: \"user-123\",\n * useful: true,\n * action: \"clicked\"\n * });\n * };\n * ```\n */\nexport function usePredictionFeedback(\n options?: UseMutationOptions<void, Error, {\n memoryId: string;\n userId: string;\n useful: boolean;\n action: \"clicked\" | \"saved\" | \"dismissed\" | \"ignored\";\n dismissReason?: \"not_relevant\" | \"already_know\" | \"not_now\" | \"other\";\n }>\n) {\n const client = useMemoryIntelligence();\n\n return useMutation<void, Error, {\n memoryId: string;\n userId: string;\n useful: boolean;\n action: \"clicked\" | \"saved\" | \"dismissed\" | \"ignored\";\n dismissReason?: \"not_relevant\" | \"already_know\" | \"not_now\" | \"other\";\n }>({\n mutationFn: (params) => client.recordPredictionFeedback(params),\n ...options,\n });\n}\n","/**\n * Type definitions for Memory Intelligence SDK\n */\n\nimport { z } from \"zod\";\n\n// Response format enum\nexport const ResponseFormat = {\n JSON: \"json\",\n MARKDOWN: \"markdown\",\n} as const;\n\nexport type ResponseFormatType = (typeof ResponseFormat)[keyof typeof ResponseFormat];\n\n// Memory type enum\nexport const MemoryType = z.enum([\n \"context\",\n \"project\",\n \"knowledge\",\n \"reference\",\n \"personal\",\n \"workflow\",\n]);\n\nexport type MemoryTypeValue = z.infer<typeof MemoryType>;\n\n// Processing mode for SDK operations\nexport type ProcessingMode = 'api' | 'offline-fallback';\n\n// Configuration interface\nexport interface MemoryIntelligenceConfig {\n apiUrl?: string; // Lanonasis API URL (default: https://api.lanonasis.com/api/v1)\n apiKey?: string; // Lanonasis API key (format: lano_xxxxxxxxxx)\n authToken?: string; // Bearer token for user-scoped auth (dashboard/SSO)\n authType?: 'apiKey' | 'bearer'; // Explicitly set auth type; inferred from apiKey/authToken if not provided\n allowMissingAuth?: boolean; // Allow client creation without auth (SDK consumers should gate calls)\n timeout?: number; // Request timeout in milliseconds (default: 30000)\n responseFormat?: ResponseFormatType;\n headers?: Record<string, string>; // Custom headers\n\n /**\n * Processing mode for intelligence operations\n * - 'api': Always use Lanonasis API endpoints (default)\n * - 'offline-fallback': Use API, fall back to cached/local data if unreachable\n * @default 'api'\n */\n processingMode?: ProcessingMode;\n\n /**\n * Enable caching of API responses for offline fallback\n * Only used when processingMode is 'offline-fallback'\n * @default true\n */\n enableCache?: boolean;\n\n /**\n * Cache TTL in milliseconds (default: 5 minutes)\n * @default 300000\n */\n cacheTTL?: number;\n}\n\n// API response wrapper from Edge Functions\nexport interface EdgeFunctionResponse<T> {\n success: boolean;\n data?: T;\n error?: {\n message: string;\n code?: string;\n };\n usage?: {\n tokens_used: number;\n cost_usd: number;\n cached: boolean;\n };\n tier_info?: {\n tier: string;\n usage_remaining: number;\n };\n}\n\n// Tool parameter interfaces\nexport interface AnalyzePatternsParams {\n userId: string;\n timeRangeDays?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface SuggestTagsParams {\n memoryId: string;\n userId: string;\n maxSuggestions?: number;\n includeExistingTags?: boolean;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface FindRelatedParams {\n memoryId: string;\n userId: string;\n limit?: number;\n similarityThreshold?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface DetectDuplicatesParams {\n userId: string;\n similarityThreshold?: number;\n maxPairs?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface ExtractInsightsParams {\n userId: string;\n topic?: string;\n memoryType?: MemoryTypeValue;\n maxMemories?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface HealthCheckParams {\n userId: string;\n responseFormat?: ResponseFormatType;\n}\n\n// Tool result interfaces\nexport interface PatternAnalysis {\n total_memories: number;\n memories_by_type: Record<string, number>;\n memories_by_day_of_week: Record<string, number>;\n peak_creation_hours: number[];\n average_content_length: number;\n most_common_tags: Array<{ tag: string; count: number }>;\n creation_velocity: {\n daily_average: number;\n trend: \"increasing\" | \"stable\" | \"decreasing\";\n };\n insights: string[];\n}\n\nexport interface TagSuggestion {\n tag: string;\n confidence: number;\n reasoning: string;\n}\n\nexport interface TagSuggestionsResult {\n memory_id: string;\n existing_tags: string[];\n suggestions: TagSuggestion[];\n context: {\n memory_type: string;\n related_memories_analyzed: number;\n };\n}\n\nexport interface RelatedMemory {\n id: string;\n title: string;\n type: string;\n similarity_score: number;\n shared_tags: string[];\n content_preview: string;\n}\n\nexport interface RelatedMemoriesResult {\n source_memory: {\n id: string;\n title: string;\n type: string;\n };\n related_memories: RelatedMemory[];\n total_found: number;\n}\n\nexport interface DuplicateEntry {\n id: string;\n title: string;\n similarity: number;\n created_at: string;\n}\n\nexport interface DuplicateGroup {\n primary_id: string;\n primary_title: string;\n duplicates: DuplicateEntry[];\n similarity_score: number;\n}\n\nexport interface DuplicatesResult {\n duplicate_groups: DuplicateGroup[];\n total_groups: number;\n total_duplicates: number;\n detection_method: \"semantic\" | \"text\";\n threshold_used: number;\n memories_analyzed: number;\n potential_storage_savings: string;\n}\n\nexport interface Insight {\n type: \"themes\" | \"connections\" | \"gaps\" | \"actions\" | \"summary\";\n content: string;\n confidence: number;\n related_memory_ids: string[];\n}\n\nexport interface InsightsResult {\n insights: Insight[];\n overall_summary: string;\n memories_analyzed: number;\n insight_types: string[];\n topic_filter?: string | null;\n generated_at: string;\n}\n\nexport interface HealthScoreBreakdown {\n organization: number;\n tagging: number;\n recency: number;\n completeness: number;\n diversity: number;\n}\n\nexport interface HealthScore {\n overall: number;\n breakdown: HealthScoreBreakdown;\n}\n\nexport interface HealthStatistics {\n total_memories: number;\n active_memories: number;\n archived_memories: number;\n memories_with_tags: number;\n unique_tags: number;\n memory_types: number;\n recent_memories_30d: number;\n stale_memories_90d: number;\n}\n\nexport interface HealthIssue {\n severity: \"high\" | \"medium\" | \"low\";\n category: string;\n description: string;\n affected_count: number;\n recommendation: string;\n}\n\nexport interface MemoryHealth {\n health_score: HealthScore;\n status: \"excellent\" | \"good\" | \"needs_attention\" | \"poor\";\n statistics: HealthStatistics;\n issues: HealthIssue[];\n recommendations: string[];\n generated_at: string;\n}\n\n// Memory entry interface (from database)\nexport interface MemoryEntry {\n id: string;\n user_id: string;\n title: string;\n content: string;\n type: MemoryTypeValue;\n tags?: string[];\n metadata?: Record<string, any>;\n embedding?: number[];\n created_at: string;\n updated_at: string;\n}\n\n// Query options for internal use\nexport interface QueryMemoriesOptions {\n type?: string;\n limit?: number;\n offset?: number;\n includeEmbeddings?: boolean;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/core/errors.ts","../../src/utils/response-adapter.ts","../../src/utils/http-client.ts","../../src/core/client.ts","../../src/react/context/MemoryIntelligenceProvider.tsx","../../src/react/hooks/useMemoryIntelligence.ts","../../src/core/types.ts"],"names":[],"mappings":";;;;;;;;AAIO,IAAM,uBAAA,GAAN,cAAsC,KAAA,CAAM;AAAA,EACjD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;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;AAcO,SAAS,qBAAA,CACd,QACA,OAAA,EACA;AACA,EAAA,MAAM,SAAS,qBAAA,EAAsB;AAErC,EAAA,OAAO,QAAA,CAAiD;AAAA,IACtD,QAAA,EAAU,CAAC,qBAAA,EAAuB,mBAAA,EAAqB,MAAM,CAAA;AAAA,IAC7D,OAAA,EAAS,MAAM,MAAA,CAAO,gBAAA,CAAiB,MAAM,CAAA;AAAA,IAC7C,GAAG;AAAA,GACJ,CAAA;AACH;AA4BO,SAAS,oBAAA,CACd,QACA,OAAA,EACA;AACA,EAAA,MAAM,SAAS,qBAAA,EAAsB;AAErC,EAAA,OAAO,QAAA,CAA+C;AAAA,IACpD,QAAA,EAAU,CAAC,qBAAA,EAAuB,kBAAA,EAAoB,MAAM,CAAA;AAAA,IAC5D,OAAA,EAAS,MAAM,MAAA,CAAO,eAAA,CAAgB,MAAM,CAAA;AAAA,IAC5C,GAAG;AAAA,GACJ,CAAA;AACH;AA2BO,SAAS,cAAA,CACd,QACA,OAAA,EACA;AACA,EAAA,MAAM,SAAS,qBAAA,EAAsB;AAErC,EAAA,OAAO,QAAA,CAA6C;AAAA,IAClD,QAAA,EAAU,CAAC,qBAAA,EAAuB,cAAA,EAAgB,MAAM,CAAA;AAAA,IACxD,OAAA,EAAS,MAAM,MAAA,CAAO,WAAA,CAAY,MAAM,CAAA;AAAA,IACxC,GAAG;AAAA,GACJ,CAAA;AACH;ACpOO,IAAM,cAAA,GAAiB;AAAA,EAC5B,IAAA,EAAM,MAAA;AAAA,EACN,QAAA,EAAU;AACZ;AAKO,IAAM,UAAA,GAAa,EAAE,IAAA,CAAK;AAAA,EAC/B,SAAA;AAAA,EACA,SAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF,CAAC","file":"index.js","sourcesContent":["/**\n * SDK-specific error classes\n */\n\nexport class MemoryIntelligenceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"MemoryIntelligenceError\";\n }\n}\n\nexport class ConfigurationError extends MemoryIntelligenceError {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigurationError\";\n }\n}\n\nexport class MemoryNotFoundError extends MemoryIntelligenceError {\n constructor(memoryId: string) {\n super(`Memory not found: ${memoryId}`);\n this.name = \"MemoryNotFoundError\";\n }\n}\n\nexport class DatabaseError extends MemoryIntelligenceError {\n constructor(message: string, public originalError?: Error) {\n super(message);\n this.name = \"DatabaseError\";\n }\n}\n\nexport class EmbeddingError extends MemoryIntelligenceError {\n constructor(message: string, public originalError?: Error) {\n super(message);\n this.name = \"EmbeddingError\";\n }\n}\n\nexport class ValidationError extends MemoryIntelligenceError {\n constructor(message: string) {\n super(message);\n this.name = \"ValidationError\";\n }\n}\n","/**\n * Response Adapter for Edge Function envelope format\n * Handles the transition between direct API responses and Edge Function wrapped responses\n */\n\nimport { EdgeFunctionResponse } from \"../core/types.js\";\nimport { ApiResponse } from \"./http-client.js\";\n\nexport interface UsageInfo {\n tokens_used: number;\n cost_usd: number;\n cached: boolean;\n}\n\nexport interface TierInfo {\n tier: string;\n usage_remaining: number;\n}\n\nexport interface UnwrappedResponse<T> {\n data?: T;\n error?: {\n message: string;\n code?: string;\n };\n usage?: UsageInfo;\n tier_info?: TierInfo;\n status: number;\n}\n\n/**\n * Adapts Edge Function envelope response to SDK internal format\n * Edge Functions return: { success, data, error, usage, tier_info }\n * SDK expects: { data, error, status }\n */\nexport function adaptEdgeFunctionResponse<T>(\n httpResponse: ApiResponse<EdgeFunctionResponse<T>>\n): UnwrappedResponse<T> {\n // If HTTP request itself failed\n if (httpResponse.error) {\n return {\n status: httpResponse.status,\n error: httpResponse.error,\n };\n }\n\n const envelope = httpResponse.data;\n\n // If no envelope data (shouldn't happen)\n if (!envelope) {\n return {\n status: httpResponse.status,\n error: {\n message: \"Empty response from server\",\n code: \"EMPTY_RESPONSE\",\n },\n };\n }\n\n // If Edge Function returned an error\n if (!envelope.success && envelope.error) {\n return {\n status: httpResponse.status,\n error: envelope.error,\n usage: envelope.usage,\n tier_info: envelope.tier_info,\n };\n }\n\n // Successful response\n return {\n status: httpResponse.status,\n data: envelope.data,\n usage: envelope.usage,\n tier_info: envelope.tier_info,\n };\n}\n\n/**\n * Checks if a response appears to be an Edge Function envelope\n */\nexport function isEdgeFunctionEnvelope(data: unknown): data is EdgeFunctionResponse<unknown> {\n if (typeof data !== \"object\" || data === null) {\n return false;\n }\n\n const obj = data as Record<string, unknown>;\n return \"success\" in obj && typeof obj.success === \"boolean\";\n}\n\n/**\n * Smart adapter that detects response format and adapts accordingly\n * Supports both direct API responses and Edge Function envelopes\n */\nexport function adaptResponse<T>(\n httpResponse: ApiResponse<T | EdgeFunctionResponse<T>>\n): UnwrappedResponse<T> {\n // If HTTP request itself failed\n if (httpResponse.error) {\n return {\n status: httpResponse.status,\n error: httpResponse.error,\n };\n }\n\n const responseData = httpResponse.data;\n\n // Check if it's an Edge Function envelope\n if (isEdgeFunctionEnvelope(responseData)) {\n return adaptEdgeFunctionResponse({\n status: httpResponse.status,\n data: responseData as EdgeFunctionResponse<T>,\n });\n }\n\n // Direct API response (legacy format)\n return {\n status: httpResponse.status,\n data: responseData as T,\n };\n}\n\n/**\n * Cache entry for offline fallback support\n */\nexport interface CacheEntry<T> {\n data: T;\n timestamp: number;\n endpoint: string;\n params?: Record<string, unknown>;\n}\n\n/**\n * Simple in-memory cache for offline fallback\n */\nexport class ResponseCache {\n private cache: Map<string, CacheEntry<unknown>> = new Map();\n private ttl: number;\n\n constructor(ttlMs: number = 300000) { // Default 5 minutes\n this.ttl = ttlMs;\n }\n\n private generateKey(endpoint: string, params?: Record<string, unknown>): string {\n const paramStr = params ? JSON.stringify(params) : \"\";\n return `${endpoint}:${paramStr}`;\n }\n\n set<T>(endpoint: string, data: T, params?: Record<string, unknown>): void {\n const key = this.generateKey(endpoint, params);\n this.cache.set(key, {\n data,\n timestamp: Date.now(),\n endpoint,\n params,\n });\n }\n\n get<T>(endpoint: string, params?: Record<string, unknown>): T | null {\n const key = this.generateKey(endpoint, params);\n const entry = this.cache.get(key);\n\n if (!entry) {\n return null;\n }\n\n // Check if expired\n if (Date.now() - entry.timestamp > this.ttl) {\n this.cache.delete(key);\n return null;\n }\n\n return entry.data as T;\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Clean up expired entries\n */\n cleanup(): void {\n const now = Date.now();\n for (const [key, entry] of this.cache.entries()) {\n if (now - entry.timestamp > this.ttl) {\n this.cache.delete(key);\n }\n }\n }\n}\n","/**\n * HTTP client for Lanonasis API\n * Supports Edge Function envelope format with caching for offline fallback\n */\n\nimport { ConfigurationError } from \"../core/errors.js\";\nimport { EdgeFunctionResponse, ProcessingMode } from \"../core/types.js\";\nimport { adaptResponse, ResponseCache, UsageInfo, TierInfo } from \"./response-adapter.js\";\n\nexport interface HttpClientConfig {\n apiUrl: string;\n apiKey?: string;\n authToken?: string;\n authType?: \"apiKey\" | \"bearer\";\n allowMissingAuth?: boolean;\n timeout?: number;\n headers?: Record<string, string>;\n processingMode?: ProcessingMode;\n enableCache?: boolean;\n cacheTTL?: number;\n}\n\nexport interface ApiResponse<T = any> {\n data?: T;\n error?: {\n message: string;\n code?: string;\n };\n status: number;\n}\n\nexport interface EnhancedApiResponse<T = any> extends ApiResponse<T> {\n usage?: UsageInfo;\n tier_info?: TierInfo;\n fromCache?: boolean;\n}\n\nexport class HttpClient {\n private apiUrl: string;\n private apiKey: string | undefined;\n private timeout: number;\n private headers: Record<string, string>;\n private processingMode: ProcessingMode;\n private cache: ResponseCache | null;\n\n constructor(config: HttpClientConfig) {\n this.apiUrl = config.apiUrl.replace(/\\/$/, \"\"); // Remove trailing slash\n\n // Determine auth type: explicit config, or infer from provided credentials\n let authType: \"apiKey\" | \"bearer\";\n if (config.authType) {\n authType = config.authType;\n } else if (config.apiKey) {\n authType = \"apiKey\";\n } else if (config.authToken) {\n authType = \"bearer\";\n } else if (config.allowMissingAuth) {\n // Default to apiKey when no auth provided but missing auth is allowed\n authType = \"apiKey\";\n } else {\n throw new ConfigurationError(\n \"Authentication required: provide apiKey, authToken, or set allowMissingAuth to true\"\n );\n }\n\n const allowMissingAuth = Boolean(config.allowMissingAuth);\n\n if (authType === \"apiKey\") {\n if (!config.apiKey && !allowMissingAuth) {\n throw new ConfigurationError(\"API key is required when authType is 'apiKey'\");\n }\n if (config.apiKey && !config.apiKey.startsWith(\"lano_\")) {\n throw new ConfigurationError(\n \"Invalid API key format. API key should start with 'lano_'\"\n );\n }\n } else if (!config.authToken && !allowMissingAuth) {\n throw new ConfigurationError(\"Bearer token is required when authType is 'bearer'\");\n }\n\n this.apiKey = config.apiKey;\n this.timeout = config.timeout || 30000;\n this.processingMode = config.processingMode || \"api\";\n\n const baseHeaders: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...config.headers,\n };\n\n if (authType === \"apiKey\" && this.apiKey && !(\"X-API-Key\" in baseHeaders)) {\n baseHeaders[\"X-API-Key\"] = this.apiKey;\n }\n\n if (authType === \"bearer\" && config.authToken && !(\"Authorization\" in baseHeaders)) {\n baseHeaders[\"Authorization\"] = `Bearer ${config.authToken}`;\n }\n\n this.headers = baseHeaders;\n\n // Initialize cache for offline-fallback mode\n if (config.enableCache !== false && this.processingMode === \"offline-fallback\") {\n this.cache = new ResponseCache(config.cacheTTL || 300000);\n } else {\n this.cache = null;\n }\n }\n\n /**\n * Get the current processing mode\n */\n getProcessingMode(): ProcessingMode {\n return this.processingMode;\n }\n\n /**\n * Check if cache is enabled\n */\n isCacheEnabled(): boolean {\n return this.cache !== null;\n }\n\n /**\n * Clear the response cache\n */\n clearCache(): void {\n this.cache?.clear();\n }\n\n private async request<T>(\n method: string,\n endpoint: string,\n data?: any\n ): Promise<ApiResponse<T>> {\n const url = `${this.apiUrl}${endpoint}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const options: RequestInit = {\n method,\n headers: this.headers,\n signal: controller.signal,\n };\n\n if (data && (method === \"POST\" || method === \"PUT\" || method === \"PATCH\")) {\n options.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, options);\n clearTimeout(timeoutId);\n\n const responseData = await response.json() as any;\n\n if (!response.ok) {\n return {\n status: response.status,\n error: {\n message: responseData?.message || responseData?.error || \"Request failed\",\n code: responseData?.code,\n },\n };\n }\n\n return {\n status: response.status,\n data: responseData as T,\n };\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n return {\n status: 408,\n error: {\n message: `Request timeout after ${this.timeout}ms`,\n code: \"TIMEOUT\",\n },\n };\n }\n\n return {\n status: 0,\n error: {\n message: error.message,\n code: \"NETWORK_ERROR\",\n },\n };\n }\n\n return {\n status: 0,\n error: {\n message: \"Unknown error occurred\",\n code: \"UNKNOWN_ERROR\",\n },\n };\n }\n }\n\n /**\n * Enhanced request that handles Edge Function envelope format\n * and supports offline-fallback caching\n */\n private async enhancedRequest<T>(\n method: string,\n endpoint: string,\n data?: any\n ): Promise<EnhancedApiResponse<T>> {\n const cacheKey = data ? JSON.stringify(data) : undefined;\n\n // Try API request first\n const rawResponse = await this.request<EdgeFunctionResponse<T> | T>(method, endpoint, data);\n\n // Handle network errors with offline fallback\n if (rawResponse.error?.code === \"NETWORK_ERROR\" || rawResponse.error?.code === \"TIMEOUT\") {\n if (this.processingMode === \"offline-fallback\" && this.cache) {\n const cached = this.cache.get<T>(endpoint, cacheKey ? JSON.parse(cacheKey) : undefined);\n if (cached) {\n return {\n status: 200,\n data: cached,\n fromCache: true,\n };\n }\n }\n // No cache available, return original error\n return {\n status: rawResponse.status,\n error: rawResponse.error,\n fromCache: false,\n };\n }\n\n // Adapt response (handles both direct and envelope formats)\n const adapted = adaptResponse<T>(rawResponse);\n\n // Cache successful responses for offline fallback\n if (!adapted.error && adapted.data && this.cache) {\n this.cache.set(endpoint, adapted.data, cacheKey ? JSON.parse(cacheKey) : undefined);\n }\n\n return {\n status: adapted.status,\n data: adapted.data,\n error: adapted.error,\n usage: adapted.usage,\n tier_info: adapted.tier_info,\n fromCache: false,\n };\n }\n\n async get<T>(endpoint: string): Promise<ApiResponse<T>> {\n return this.request<T>(\"GET\", endpoint);\n }\n\n async post<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {\n return this.request<T>(\"POST\", endpoint, data);\n }\n\n async put<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {\n return this.request<T>(\"PUT\", endpoint, data);\n }\n\n async patch<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {\n return this.request<T>(\"PATCH\", endpoint, data);\n }\n\n async delete<T>(endpoint: string): Promise<ApiResponse<T>> {\n return this.request<T>(\"DELETE\", endpoint);\n }\n\n // Enhanced methods with Edge Function envelope support\n\n async getEnhanced<T>(endpoint: string): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"GET\", endpoint);\n }\n\n async postEnhanced<T>(endpoint: string, data?: any): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"POST\", endpoint, data);\n }\n\n async putEnhanced<T>(endpoint: string, data?: any): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"PUT\", endpoint, data);\n }\n\n async patchEnhanced<T>(endpoint: string, data?: any): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"PATCH\", endpoint, data);\n }\n\n async deleteEnhanced<T>(endpoint: string): Promise<EnhancedApiResponse<T>> {\n return this.enhancedRequest<T>(\"DELETE\", endpoint);\n }\n}\n","/**\n * Core Memory Intelligence Client\n * Supports API-first with offline-fallback capability\n */\n\nimport {\n MemoryIntelligenceConfig,\n AnalyzePatternsParams,\n PatternAnalysis,\n SuggestTagsParams,\n TagSuggestionsResult,\n FindRelatedParams,\n RelatedMemoriesResult,\n DetectDuplicatesParams,\n DuplicatesResult,\n ExtractInsightsParams,\n InsightsResult,\n HealthCheckParams,\n MemoryHealth,\n QueryMemoriesOptions,\n MemoryEntry,\n ProcessingMode,\n} from \"./types.js\";\nimport {\n PredictiveRecallParams,\n PredictiveRecallResult,\n} from \"./prediction-types.js\";\nimport {\n RecordBehaviorParams,\n RecordBehaviorResult,\n RecallBehaviorParams,\n RecallBehaviorResult,\n SuggestActionParams,\n SuggestActionResult,\n BehaviorPattern,\n} from \"./behavior-types.js\";\nimport { DatabaseError } from \"./errors.js\";\nimport { HttpClient } from \"../utils/http-client.js\";\nimport { UsageInfo, TierInfo } from \"../utils/response-adapter.js\";\n\nconst DEFAULT_API_URL = \"https://api.lanonasis.com/api/v1\";\n\nexport interface IntelligenceResponse<T> {\n data: T;\n usage?: UsageInfo;\n tier_info?: TierInfo;\n fromCache?: boolean;\n}\n\nexport class MemoryIntelligenceClient {\n private httpClient: HttpClient;\n private defaultResponseFormat: \"json\" | \"markdown\";\n private processingMode: ProcessingMode;\n\n constructor(config: MemoryIntelligenceConfig) {\n this.processingMode = config.processingMode || \"api\";\n const authType = config.authType || (config.apiKey ? \"apiKey\" : \"bearer\");\n\n this.httpClient = new HttpClient({\n apiUrl: config.apiUrl || DEFAULT_API_URL,\n apiKey: config.apiKey,\n authToken: config.authToken,\n authType,\n allowMissingAuth: config.allowMissingAuth,\n timeout: config.timeout,\n headers: config.headers,\n processingMode: this.processingMode,\n enableCache: config.enableCache,\n cacheTTL: config.cacheTTL,\n });\n\n this.defaultResponseFormat = config.responseFormat || \"markdown\";\n }\n\n /**\n * Get the current processing mode\n */\n getProcessingMode(): ProcessingMode {\n return this.processingMode;\n }\n\n /**\n * Check if cache is enabled (for offline-fallback mode)\n */\n isCacheEnabled(): boolean {\n return this.httpClient.isCacheEnabled();\n }\n\n /**\n * Clear the response cache\n */\n clearCache(): void {\n this.httpClient.clearCache();\n }\n\n /**\n * Get HTTP client for direct API access\n */\n public getHttpClient(): HttpClient {\n return this.httpClient;\n }\n\n /**\n * Query memories from the API\n */\n public async queryMemories(\n userId: string,\n options: QueryMemoriesOptions = {}\n ): Promise<MemoryEntry[]> {\n const { type, limit = 100, offset = 0 } = options;\n\n const params = new URLSearchParams({\n user_id: userId,\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (type) {\n params.append(\"type\", type);\n }\n\n const response = await this.httpClient.get<{ memories: MemoryEntry[] }>(\n `/intelligence/memories?${params.toString()}`\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to query memories: ${response.error.message}`);\n }\n\n return response.data?.memories || [];\n }\n\n /**\n * Analyze usage patterns and trends in memory collection\n */\n async analyzePatterns(params: AnalyzePatternsParams): Promise<IntelligenceResponse<PatternAnalysis>> {\n const response = await this.httpClient.postEnhanced<PatternAnalysis>(\n \"/intelligence/analyze-patterns\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to analyze patterns: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Get AI-powered tag suggestions for a memory\n */\n async suggestTags(params: SuggestTagsParams): Promise<IntelligenceResponse<TagSuggestionsResult>> {\n const response = await this.httpClient.postEnhanced<TagSuggestionsResult>(\n \"/intelligence/suggest-tags\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to suggest tags: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Find semantically related memories using vector similarity\n */\n async findRelated(params: FindRelatedParams): Promise<IntelligenceResponse<RelatedMemoriesResult>> {\n const response = await this.httpClient.postEnhanced<RelatedMemoriesResult>(\n \"/intelligence/find-related\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to find related memories: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Detect potential duplicate memories\n */\n async detectDuplicates(params: DetectDuplicatesParams): Promise<IntelligenceResponse<DuplicatesResult>> {\n const response = await this.httpClient.postEnhanced<DuplicatesResult>(\n \"/intelligence/detect-duplicates\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to detect duplicates: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Extract insights and patterns from memories\n */\n async extractInsights(params: ExtractInsightsParams): Promise<IntelligenceResponse<InsightsResult>> {\n const response = await this.httpClient.postEnhanced<InsightsResult>(\n \"/intelligence/extract-insights\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to extract insights: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Check the health and organization quality of memories\n */\n async healthCheck(params: HealthCheckParams): Promise<IntelligenceResponse<MemoryHealth>> {\n const response = await this.httpClient.postEnhanced<MemoryHealth>(\n \"/intelligence/health-check\",\n {\n ...params,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to check health: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Predictive Memory Recall - AI that anticipates what you need\n *\n * Uses a weighted scoring algorithm:\n * - Semantic similarity to current context (40%)\n * - Temporal relevance (recency decay curve) (30%)\n * - Usage frequency (20%)\n * - Serendipity factor (adjacent discoveries) (10%)\n *\n * @example\n * ```typescript\n * const result = await client.predictiveRecall({\n * userId: \"user-123\",\n * context: {\n * currentProject: \"Building dashboard components\",\n * recentTopics: [\"React\", \"performance\", \"hooks\"],\n * contextText: \"Optimizing render performance for data tables\"\n * },\n * limit: 5,\n * minConfidence: 50\n * });\n *\n * for (const prediction of result.data.predictions) {\n * console.log(`[${prediction.confidence}%] ${prediction.title}`);\n * console.log(` Reason: ${prediction.reason}`);\n * console.log(` Action: ${prediction.suggestedAction}`);\n * }\n * ```\n */\n async predictiveRecall(\n params: PredictiveRecallParams\n ): Promise<IntelligenceResponse<PredictiveRecallResult>> {\n const response = await this.httpClient.postEnhanced<PredictiveRecallResult>(\n \"/intelligence/predictive-recall\",\n {\n userId: params.userId,\n context: params.context,\n limit: params.limit || 5,\n minConfidence: params.minConfidence || 40,\n includeSerendipity: params.includeSerendipity !== false,\n memoryTypes: params.memoryTypes,\n timeWindowDays: params.timeWindowDays || 90,\n responseFormat: params.responseFormat || this.defaultResponseFormat,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to get predictions: ${response.error.message}`);\n }\n\n return {\n data: response.data!,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Record feedback on a prediction (for improving accuracy over time)\n *\n * @example\n * ```typescript\n * await client.recordPredictionFeedback({\n * memoryId: \"mem-123\",\n * userId: \"user-123\",\n * useful: true,\n * action: \"clicked\"\n * });\n * ```\n */\n async recordPredictionFeedback(params: {\n memoryId: string;\n userId: string;\n useful: boolean;\n action: \"clicked\" | \"saved\" | \"dismissed\" | \"ignored\";\n dismissReason?: \"not_relevant\" | \"already_know\" | \"not_now\" | \"other\";\n }): Promise<void> {\n await this.httpClient.post(\"/intelligence/prediction-feedback\", params);\n }\n\n // ============================================================================\n // Behavioral Learning Methods\n // ============================================================================\n\n /**\n * Record a successful behavior pattern for future recall\n *\n * The system automatically:\n * - Generates an embedding from the trigger description\n * - Detects and updates duplicates (>95% similarity)\n * - Tracks usage counts for pattern prioritization\n *\n * @example\n * ```typescript\n * const result = await client.recordBehavior({\n * user_id: \"user-123\",\n * trigger: \"User wants to refactor a React component to use hooks\",\n * context: {\n * project: \"dashboard-app\",\n * active_files: [\"src/components/DataTable.tsx\"]\n * },\n * actions: [\n * { tool: \"read_file\", params: { path: \"src/components/DataTable.tsx\" } },\n * { tool: \"analyze_code\", params: { focus: \"class_components\" } },\n * { tool: \"edit_file\", params: { path: \"src/components/DataTable.tsx\" } }\n * ],\n * final_outcome: \"Successfully converted class component to functional with hooks\"\n * });\n *\n * if (result.data.was_duplicate) {\n * console.log(\"Updated existing pattern:\", result.data.pattern.id);\n * }\n * ```\n */\n async recordBehavior(\n params: RecordBehaviorParams\n ): Promise<IntelligenceResponse<RecordBehaviorResult>> {\n const response = await this.httpClient.postEnhanced<RecordBehaviorResult>(\n \"/intelligence/behavior-record\",\n {\n user_id: params.user_id,\n trigger: params.trigger,\n context: params.context || {},\n actions: params.actions,\n final_outcome: params.final_outcome,\n confidence: params.confidence ?? 0.7,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to record behavior: ${response.error.message}`);\n }\n\n // Handle the edge function response format\n const data = response.data as any;\n return {\n data: {\n pattern: data.data || data,\n was_duplicate: data.message?.includes(\"duplicate\") || false,\n message: data.message || \"Behavior pattern recorded successfully\",\n },\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Recall similar behavior patterns based on current context\n *\n * Use this to find workflows that match the user's current task,\n * enabling AI assistants to suggest proven approaches.\n *\n * @example\n * ```typescript\n * const result = await client.recallBehavior({\n * user_id: \"user-123\",\n * context: {\n * current_task: \"Need to optimize database queries for user dashboard\"\n * },\n * limit: 5,\n * similarity_threshold: 0.7\n * });\n *\n * for (const match of result.data.patterns) {\n * console.log(`[${Math.round(match.similarity_score * 100)}%] ${match.pattern.trigger}`);\n * console.log(` Actions: ${match.pattern.actions.map(a => a.tool).join(\" → \")}`);\n * }\n * ```\n */\n async recallBehavior(\n params: RecallBehaviorParams\n ): Promise<IntelligenceResponse<RecallBehaviorResult>> {\n const response = await this.httpClient.postEnhanced<RecallBehaviorResult>(\n \"/intelligence/behavior-recall\",\n {\n user_id: params.user_id,\n context: params.context,\n limit: params.limit ?? 5,\n similarity_threshold: params.similarity_threshold ?? 0.7,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to recall behaviors: ${response.error.message}`);\n }\n\n // Handle the edge function response format\n const data = response.data as any;\n return {\n data: data.data || data,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * Get AI-powered action suggestions based on learned patterns\n *\n * Analyzes the current state and completed steps to predict\n * what action the user should take next based on similar workflows.\n *\n * @example\n * ```typescript\n * const result = await client.suggestAction({\n * user_id: \"user-123\",\n * current_state: {\n * task_description: \"Implementing user authentication with OAuth\",\n * completed_steps: [\n * { tool: \"create_file\", params: { path: \"src/auth/oauth.ts\" } },\n * { tool: \"read_file\", params: { path: \"package.json\" } }\n * ]\n * },\n * max_suggestions: 3\n * });\n *\n * for (const suggestion of result.data.suggestions) {\n * console.log(`[${Math.round(suggestion.confidence * 100)}%] ${suggestion.action}`);\n * console.log(` Tool: ${suggestion.tool}`);\n * console.log(` Why: ${suggestion.reasoning}`);\n * }\n * ```\n */\n async suggestAction(\n params: SuggestActionParams\n ): Promise<IntelligenceResponse<SuggestActionResult>> {\n const response = await this.httpClient.postEnhanced<SuggestActionResult>(\n \"/intelligence/behavior-suggest\",\n {\n user_id: params.user_id,\n current_state: params.current_state,\n max_suggestions: params.max_suggestions ?? 3,\n }\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to get action suggestions: ${response.error.message}`);\n }\n\n // Handle the edge function response format\n const data = response.data as any;\n return {\n data: data.data || data,\n usage: response.usage,\n tier_info: response.tier_info,\n fromCache: response.fromCache,\n };\n }\n\n /**\n * List all behavior patterns for a user\n *\n * @example\n * ```typescript\n * const patterns = await client.listBehaviorPatterns(\"user-123\", { limit: 20 });\n * console.log(`Found ${patterns.length} patterns`);\n * ```\n */\n async listBehaviorPatterns(\n userId: string,\n options: { limit?: number; offset?: number } = {}\n ): Promise<BehaviorPattern[]> {\n const { limit = 50, offset = 0 } = options;\n\n const response = await this.httpClient.get<{ patterns: BehaviorPattern[] }>(\n `/intelligence/behavior-patterns?user_id=${userId}&limit=${limit}&offset=${offset}`\n );\n\n if (response.error) {\n throw new DatabaseError(`Failed to list behavior patterns: ${response.error.message}`);\n }\n\n return response.data?.patterns || [];\n }\n}\n","/** @jsxImportSource react */\n/**\n * React Context Provider for Memory Intelligence\n */\n\nimport {\n createContext,\n useContext,\n ReactNode,\n useState,\n useEffect,\n} from \"react\";\nimport { MemoryIntelligenceClient } from \"../../core/client.js\";\nimport { MemoryIntelligenceConfig } from \"../../core/types.js\";\n\ninterface MemoryIntelligenceContextValue {\n client: MemoryIntelligenceClient;\n}\n\nconst MemoryIntelligenceContext =\n createContext<MemoryIntelligenceContextValue | null>(null);\n\ninterface MemoryIntelligenceProviderProps {\n config: MemoryIntelligenceConfig;\n children: ReactNode;\n}\n\nexport function MemoryIntelligenceProvider({\n config,\n children,\n}: MemoryIntelligenceProviderProps) {\n // Use useState to avoid recreating client on every render when config object is recreated\n const [client, setClient] = useState(\n () => new MemoryIntelligenceClient(config),\n );\n\n // Only recreate client when primitive config values change\n useEffect(() => {\n setClient(new MemoryIntelligenceClient(config));\n }, [\n config.apiUrl,\n config.apiKey,\n config.authToken,\n config.authType,\n config.allowMissingAuth,\n config.timeout,\n config.processingMode,\n config.enableCache,\n config.cacheTTL,\n ]);\n\n return (\n <MemoryIntelligenceContext.Provider value={{ client }}>\n {children}\n </MemoryIntelligenceContext.Provider>\n );\n}\n\nexport function useMemoryIntelligenceContext() {\n const context = useContext(MemoryIntelligenceContext);\n if (!context) {\n throw new Error(\n \"useMemoryIntelligenceContext must be used within MemoryIntelligenceProvider\",\n );\n }\n return context;\n}\n\nexport { MemoryIntelligenceContext };\n","/**\n * React hooks for Memory Intelligence using React Query\n */\n\nimport { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from \"@tanstack/react-query\";\nimport { useMemoryIntelligenceContext } from \"../context/MemoryIntelligenceProvider.js\";\nimport {\n PatternAnalysis,\n TagSuggestionsResult,\n RelatedMemoriesResult,\n DuplicatesResult,\n InsightsResult,\n MemoryHealth,\n AnalyzePatternsParams,\n SuggestTagsParams,\n FindRelatedParams,\n DetectDuplicatesParams,\n ExtractInsightsParams,\n HealthCheckParams,\n} from \"../../core/types.js\";\nimport {\n PredictiveRecallParams,\n PredictiveRecallResult,\n} from \"../../core/prediction-types.js\";\nimport type { IntelligenceResponse } from \"../../core/client.js\";\n\n/**\n * Get the Memory Intelligence client from context\n */\nexport function useMemoryIntelligence() {\n const { client } = useMemoryIntelligenceContext();\n return client;\n}\n\n/**\n * Hook for analyzing memory patterns\n *\n * @example\n * ```tsx\n * const { data, isLoading, error } = usePatternAnalysis({\n * userId: \"user-123\",\n * timeRangeDays: 30,\n * responseFormat: \"json\"\n * });\n * ```\n */\nexport function usePatternAnalysis(\n params: AnalyzePatternsParams,\n options?: Omit<UseQueryOptions<IntelligenceResponse<PatternAnalysis>>, \"queryKey\" | \"queryFn\">\n) {\n const client = useMemoryIntelligence();\n\n return useQuery<IntelligenceResponse<PatternAnalysis>>({\n queryKey: [\"memory-intelligence\", \"analyze-patterns\", params],\n queryFn: () => client.analyzePatterns(params),\n ...options,\n });\n}\n\n/**\n * Hook for getting tag suggestions\n *\n * @example\n * ```tsx\n * const { data, isLoading } = useTagSuggestions({\n * memoryId: \"mem-123\",\n * userId: \"user-123\",\n * maxSuggestions: 5\n * });\n * ```\n */\nexport function useTagSuggestions(\n params: SuggestTagsParams,\n options?: Omit<UseQueryOptions<IntelligenceResponse<TagSuggestionsResult>>, \"queryKey\" | \"queryFn\">\n) {\n const client = useMemoryIntelligence();\n\n return useQuery<IntelligenceResponse<TagSuggestionsResult>>({\n queryKey: [\"memory-intelligence\", \"suggest-tags\", params],\n queryFn: () => client.suggestTags(params),\n ...options,\n });\n}\n\n/**\n * Mutation hook for getting tag suggestions (if you need manual trigger)\n *\n * @example\n * ```tsx\n * const { mutate, data, isPending } = useTagSuggestionsMutation();\n *\n * // Later...\n * mutate({\n * memoryId: \"mem-123\",\n * userId: \"user-123\"\n * });\n * ```\n */\nexport function useTagSuggestionsMutation(\n options?: UseMutationOptions<IntelligenceResponse<TagSuggestionsResult>, Error, SuggestTagsParams>\n) {\n const client = useMemoryIntelligence();\n\n return useMutation<IntelligenceResponse<TagSuggestionsResult>, Error, SuggestTagsParams>({\n mutationFn: (params) => client.suggestTags(params),\n ...options,\n });\n}\n\n/**\n * Hook for finding related memories\n *\n * @example\n * ```tsx\n * const { data, isLoading } = useRelatedMemories({\n * memoryId: \"mem-123\",\n * userId: \"user-123\",\n * limit: 10,\n * similarityThreshold: 0.7\n * });\n * ```\n */\nexport function useRelatedMemories(\n params: FindRelatedParams,\n options?: Omit<UseQueryOptions<IntelligenceResponse<RelatedMemoriesResult>>, \"queryKey\" | \"queryFn\">\n) {\n const client = useMemoryIntelligence();\n\n return useQuery<IntelligenceResponse<RelatedMemoriesResult>>({\n queryKey: [\"memory-intelligence\", \"find-related\", params],\n queryFn: () => client.findRelated(params),\n ...options,\n });\n}\n\n/**\n * Hook for detecting duplicate memories\n *\n * @example\n * ```tsx\n * const { data, isLoading } = useDuplicateDetection({\n * userId: \"user-123\",\n * similarityThreshold: 0.9,\n * maxPairs: 20\n * });\n * ```\n */\nexport function useDuplicateDetection(\n params: DetectDuplicatesParams,\n options?: Omit<UseQueryOptions<IntelligenceResponse<DuplicatesResult>>, \"queryKey\" | \"queryFn\">\n) {\n const client = useMemoryIntelligence();\n\n return useQuery<IntelligenceResponse<DuplicatesResult>>({\n queryKey: [\"memory-intelligence\", \"detect-duplicates\", params],\n queryFn: () => client.detectDuplicates(params),\n ...options,\n });\n}\n\n/**\n * Mutation hook for duplicate detection (if you need manual trigger)\n */\nexport function useDuplicateDetectionMutation(\n options?: UseMutationOptions<IntelligenceResponse<DuplicatesResult>, Error, DetectDuplicatesParams>\n) {\n const client = useMemoryIntelligence();\n\n return useMutation<IntelligenceResponse<DuplicatesResult>, Error, DetectDuplicatesParams>({\n mutationFn: (params) => client.detectDuplicates(params),\n ...options,\n });\n}\n\n/**\n * Hook for extracting insights\n *\n * @example\n * ```tsx\n * const { data, isLoading } = useInsightExtraction({\n * userId: \"user-123\",\n * topic: \"machine learning\",\n * maxMemories: 20\n * });\n * ```\n */\nexport function useInsightExtraction(\n params: ExtractInsightsParams,\n options?: Omit<UseQueryOptions<IntelligenceResponse<InsightsResult>>, \"queryKey\" | \"queryFn\">\n) {\n const client = useMemoryIntelligence();\n\n return useQuery<IntelligenceResponse<InsightsResult>>({\n queryKey: [\"memory-intelligence\", \"extract-insights\", params],\n queryFn: () => client.extractInsights(params),\n ...options,\n });\n}\n\n/**\n * Mutation hook for insight extraction (if you need manual trigger)\n */\nexport function useInsightExtractionMutation(\n options?: UseMutationOptions<IntelligenceResponse<InsightsResult>, Error, ExtractInsightsParams>\n) {\n const client = useMemoryIntelligence();\n\n return useMutation<IntelligenceResponse<InsightsResult>, Error, ExtractInsightsParams>({\n mutationFn: (params) => client.extractInsights(params),\n ...options,\n });\n}\n\n/**\n * Hook for checking memory health\n *\n * @example\n * ```tsx\n * const { data, isLoading } = useHealthCheck({\n * userId: \"user-123\",\n * responseFormat: \"json\"\n * });\n * ```\n */\nexport function useHealthCheck(\n params: HealthCheckParams,\n options?: Omit<UseQueryOptions<IntelligenceResponse<MemoryHealth>>, \"queryKey\" | \"queryFn\">\n) {\n const client = useMemoryIntelligence();\n\n return useQuery<IntelligenceResponse<MemoryHealth>>({\n queryKey: [\"memory-intelligence\", \"health-check\", params],\n queryFn: () => client.healthCheck(params),\n ...options,\n });\n}\n\n/**\n * Mutation hook for health check (if you need manual trigger)\n */\nexport function useHealthCheckMutation(\n options?: UseMutationOptions<IntelligenceResponse<MemoryHealth>, Error, HealthCheckParams>\n) {\n const client = useMemoryIntelligence();\n\n return useMutation<IntelligenceResponse<MemoryHealth>, Error, HealthCheckParams>({\n mutationFn: (params) => client.healthCheck(params),\n ...options,\n });\n}\n\n/**\n * Hook for predictive memory recall\n *\n * AI-powered prediction of memories you'll need based on your current context.\n * Uses semantic similarity, temporal relevance, usage patterns, and serendipity\n * scoring to anticipate what you need before you realize it.\n *\n * @example\n * ```tsx\n * const { data, isLoading, error } = usePredictiveRecall({\n * userId: \"user-123\",\n * context: {\n * currentProject: \"Building dashboard components\",\n * recentTopics: [\"React\", \"performance\"],\n * contextText: \"Optimizing render performance\"\n * },\n * limit: 5,\n * minConfidence: 50\n * });\n *\n * // Display predictions\n * {data?.data.predictions.map(pred => (\n * <PredictionCard\n * key={pred.id}\n * title={pred.title}\n * confidence={pred.confidence}\n * reason={pred.reason}\n * action={pred.suggestedAction}\n * />\n * ))}\n * ```\n */\nexport function usePredictiveRecall(\n params: PredictiveRecallParams,\n options?: Omit<UseQueryOptions<IntelligenceResponse<PredictiveRecallResult>>, \"queryKey\" | \"queryFn\">\n) {\n const client = useMemoryIntelligence();\n\n return useQuery<IntelligenceResponse<PredictiveRecallResult>>({\n queryKey: [\"memory-intelligence\", \"predictive-recall\", params],\n queryFn: () => client.predictiveRecall(params),\n // Predictions should refresh periodically as context changes\n staleTime: 60000, // 1 minute\n ...options,\n });\n}\n\n/**\n * Mutation hook for predictive recall (if you need manual trigger)\n *\n * @example\n * ```tsx\n * const { mutate, data, isPending } = usePredictiveRecallMutation();\n *\n * // Trigger prediction when context changes\n * const handleContextChange = (newContext) => {\n * mutate({\n * userId: \"user-123\",\n * context: newContext,\n * limit: 5\n * });\n * };\n * ```\n */\nexport function usePredictiveRecallMutation(\n options?: UseMutationOptions<IntelligenceResponse<PredictiveRecallResult>, Error, PredictiveRecallParams>\n) {\n const client = useMemoryIntelligence();\n\n return useMutation<IntelligenceResponse<PredictiveRecallResult>, Error, PredictiveRecallParams>({\n mutationFn: (params) => client.predictiveRecall(params),\n ...options,\n });\n}\n\n/**\n * Hook for recording prediction feedback\n *\n * @example\n * ```tsx\n * const { mutate: recordFeedback } = usePredictionFeedback();\n *\n * // When user clicks on a prediction\n * const handlePredictionClick = (memoryId: string) => {\n * recordFeedback({\n * memoryId,\n * userId: \"user-123\",\n * useful: true,\n * action: \"clicked\"\n * });\n * };\n * ```\n */\nexport function usePredictionFeedback(\n options?: UseMutationOptions<void, Error, {\n memoryId: string;\n userId: string;\n useful: boolean;\n action: \"clicked\" | \"saved\" | \"dismissed\" | \"ignored\";\n dismissReason?: \"not_relevant\" | \"already_know\" | \"not_now\" | \"other\";\n }>\n) {\n const client = useMemoryIntelligence();\n\n return useMutation<void, Error, {\n memoryId: string;\n userId: string;\n useful: boolean;\n action: \"clicked\" | \"saved\" | \"dismissed\" | \"ignored\";\n dismissReason?: \"not_relevant\" | \"already_know\" | \"not_now\" | \"other\";\n }>({\n mutationFn: (params) => client.recordPredictionFeedback(params),\n ...options,\n });\n}\n","/**\n * Type definitions for Memory Intelligence SDK\n */\n\nimport { z } from \"zod\";\n\n// Response format enum\nexport const ResponseFormat = {\n JSON: \"json\",\n MARKDOWN: \"markdown\",\n} as const;\n\nexport type ResponseFormatType = (typeof ResponseFormat)[keyof typeof ResponseFormat];\n\n// Memory type enum\nexport const MemoryType = z.enum([\n \"context\",\n \"project\",\n \"knowledge\",\n \"reference\",\n \"personal\",\n \"workflow\",\n]);\n\nexport type MemoryTypeValue = z.infer<typeof MemoryType>;\n\n// Processing mode for SDK operations\nexport type ProcessingMode = 'api' | 'offline-fallback';\n\n// Configuration interface\nexport interface MemoryIntelligenceConfig {\n apiUrl?: string; // Lanonasis API URL (default: https://api.lanonasis.com/api/v1)\n apiKey?: string; // Lanonasis API key (format: lano_xxxxxxxxxx)\n authToken?: string; // Bearer token for user-scoped auth (dashboard/SSO)\n authType?: 'apiKey' | 'bearer'; // Explicitly set auth type; inferred from apiKey/authToken if not provided\n allowMissingAuth?: boolean; // Allow client creation without auth (SDK consumers should gate calls)\n timeout?: number; // Request timeout in milliseconds (default: 30000)\n responseFormat?: ResponseFormatType;\n headers?: Record<string, string>; // Custom headers\n\n /**\n * Processing mode for intelligence operations\n * - 'api': Always use Lanonasis API endpoints (default)\n * - 'offline-fallback': Use API, fall back to cached/local data if unreachable\n * @default 'api'\n */\n processingMode?: ProcessingMode;\n\n /**\n * Enable caching of API responses for offline fallback\n * Only used when processingMode is 'offline-fallback'\n * @default true\n */\n enableCache?: boolean;\n\n /**\n * Cache TTL in milliseconds (default: 5 minutes)\n * @default 300000\n */\n cacheTTL?: number;\n}\n\n// API response wrapper from Edge Functions\nexport interface EdgeFunctionResponse<T> {\n success: boolean;\n data?: T;\n error?: {\n message: string;\n code?: string;\n };\n usage?: {\n tokens_used: number;\n cost_usd: number;\n cached: boolean;\n };\n tier_info?: {\n tier: string;\n usage_remaining: number;\n };\n}\n\n// Tool parameter interfaces\nexport interface AnalyzePatternsParams {\n userId: string;\n timeRangeDays?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface SuggestTagsParams {\n memoryId: string;\n userId: string;\n maxSuggestions?: number;\n includeExistingTags?: boolean;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface FindRelatedParams {\n memoryId: string;\n userId: string;\n limit?: number;\n similarityThreshold?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface DetectDuplicatesParams {\n userId: string;\n similarityThreshold?: number;\n maxPairs?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface ExtractInsightsParams {\n userId: string;\n topic?: string;\n memoryType?: MemoryTypeValue;\n maxMemories?: number;\n responseFormat?: ResponseFormatType;\n}\n\nexport interface HealthCheckParams {\n userId: string;\n responseFormat?: ResponseFormatType;\n}\n\n// Tool result interfaces\nexport interface PatternAnalysis {\n total_memories: number;\n memories_by_type: Record<string, number>;\n memories_by_day_of_week: Record<string, number>;\n peak_creation_hours: number[];\n average_content_length: number;\n most_common_tags: Array<{ tag: string; count: number }>;\n creation_velocity: {\n daily_average: number;\n trend: \"increasing\" | \"stable\" | \"decreasing\";\n };\n insights: string[];\n}\n\nexport interface TagSuggestion {\n tag: string;\n confidence: number;\n reasoning: string;\n}\n\nexport interface TagSuggestionsResult {\n memory_id: string;\n existing_tags: string[];\n suggestions: TagSuggestion[];\n context: {\n memory_type: string;\n related_memories_analyzed: number;\n };\n}\n\nexport interface RelatedMemory {\n id: string;\n title: string;\n type: string;\n similarity_score: number;\n shared_tags: string[];\n content_preview: string;\n}\n\nexport interface RelatedMemoriesResult {\n source_memory: {\n id: string;\n title: string;\n type: string;\n };\n related_memories: RelatedMemory[];\n total_found: number;\n}\n\nexport interface DuplicateEntry {\n id: string;\n title: string;\n similarity: number;\n created_at: string;\n}\n\nexport interface DuplicateGroup {\n primary_id: string;\n primary_title: string;\n duplicates: DuplicateEntry[];\n similarity_score: number;\n}\n\nexport interface DuplicatesResult {\n duplicate_groups: DuplicateGroup[];\n total_groups: number;\n total_duplicates: number;\n detection_method: \"semantic\" | \"text\";\n threshold_used: number;\n memories_analyzed: number;\n potential_storage_savings: string;\n}\n\nexport interface Insight {\n type: \"themes\" | \"connections\" | \"gaps\" | \"actions\" | \"summary\";\n content: string;\n confidence: number;\n related_memory_ids: string[];\n}\n\nexport interface InsightsResult {\n insights: Insight[];\n overall_summary: string;\n memories_analyzed: number;\n insight_types: string[];\n topic_filter?: string | null;\n generated_at: string;\n}\n\nexport interface HealthScoreBreakdown {\n organization: number;\n tagging: number;\n recency: number;\n completeness: number;\n diversity: number;\n}\n\nexport interface HealthScore {\n overall: number;\n breakdown: HealthScoreBreakdown;\n}\n\nexport interface HealthStatistics {\n total_memories: number;\n active_memories: number;\n archived_memories: number;\n memories_with_tags: number;\n unique_tags: number;\n memory_types: number;\n recent_memories_30d: number;\n stale_memories_90d: number;\n}\n\nexport interface HealthIssue {\n severity: \"high\" | \"medium\" | \"low\";\n category: string;\n description: string;\n affected_count: number;\n recommendation: string;\n}\n\nexport interface MemoryHealth {\n health_score: HealthScore;\n status: \"excellent\" | \"good\" | \"needs_attention\" | \"poor\";\n statistics: HealthStatistics;\n issues: HealthIssue[];\n recommendations: string[];\n generated_at: string;\n}\n\n// Memory entry interface (from database)\nexport interface MemoryEntry {\n id: string;\n user_id: string;\n title: string;\n content: string;\n type: MemoryTypeValue;\n tags?: string[];\n metadata?: Record<string, any>;\n embedding?: number[];\n created_at: string;\n updated_at: string;\n}\n\n// Query options for internal use\nexport interface QueryMemoriesOptions {\n type?: string;\n limit?: number;\n offset?: number;\n includeEmbeddings?: boolean;\n}\n"]}
|