@lanonasis/mem-intel-sdk 1.0.1 → 2.0.0
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 +230 -15
- package/README.md +258 -4
- package/dist/core/client.d.ts +79 -7
- package/dist/core/client.d.ts.map +1 -1
- package/dist/core/index.cjs +360 -13
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +359 -14
- package/dist/core/index.js.map +1 -1
- package/dist/core/prediction-types.d.ts +270 -0
- package/dist/core/prediction-types.d.ts.map +1 -0
- package/dist/core/types.d.ts +94 -38
- package/dist/core/types.d.ts.map +1 -1
- package/dist/index-sdk.d.ts +2 -0
- package/dist/index-sdk.d.ts.map +1 -1
- package/dist/index.cjs +320 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +320 -13
- package/dist/index.js.map +1 -1
- package/dist/node/index.cjs +320 -13
- package/dist/node/index.cjs.map +1 -1
- package/dist/node/index.js +320 -13
- package/dist/node/index.js.map +1 -1
- package/dist/react/hooks/useMemoryIntelligence.d.ts +94 -10
- package/dist/react/hooks/useMemoryIntelligence.d.ts.map +1 -1
- package/dist/react/index.cjs +320 -13
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.js +320 -13
- package/dist/react/index.js.map +1 -1
- package/dist/server/index.cjs +571 -47
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.js +571 -47
- package/dist/server/index.js.map +1 -1
- package/dist/server/mcp-server.d.ts.map +1 -1
- package/dist/utils/http-client.d.ts +35 -0
- package/dist/utils/http-client.d.ts.map +1 -1
- package/dist/utils/index.d.ts +3 -1
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/prediction-engine.d.ts +90 -0
- package/dist/utils/prediction-engine.d.ts.map +1 -0
- package/dist/utils/response-adapter.d.ts +66 -0
- package/dist/utils/response-adapter.d.ts.map +1 -0
- package/dist/vue/composables/useMemoryIntelligence.d.ts +59 -0
- package/dist/vue/composables/useMemoryIntelligence.d.ts.map +1 -1
- package/dist/vue/index.cjs.map +1 -1
- package/dist/vue/index.js.map +1 -1
- package/package.json +11 -5
package/dist/core/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/errors.ts","../../src/utils/http-client.ts","../../src/core/client.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,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AAAA,EACd;AACF;AAEO,IAAM,mBAAA,GAAN,cAAkC,uBAAA,CAAwB;AAAA,EAC/D,YAAY,QAAA,EAAkB;AAC5B,IAAA,KAAA,CAAM,CAAA,kBAAA,EAAqB,QAAQ,CAAA,CAAE,CAAA;AACrC,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAEO,IAAM,aAAA,GAAN,cAA4B,uBAAA,CAAwB;AAAA,EACzD,WAAA,CAAY,SAAwB,aAAA,EAAuB;AACzD,IAAA,KAAA,CAAM,OAAO,CAAA;AADqB,IAAA,IAAA,CAAA,aAAA,GAAA,aAAA;AAElC,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AACF;AAEO,IAAM,cAAA,GAAN,cAA6B,uBAAA,CAAwB;AAAA,EAC1D,WAAA,CAAY,SAAwB,aAAA,EAAuB;AACzD,IAAA,KAAA,CAAM,OAAO,CAAA;AADqB,IAAA,IAAA,CAAA,aAAA,GAAA,aAAA;AA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kB,IAAA,CAAK;AAAA;AAChD,KACF;AAEA,IAAA,IAAI,SAAS,KAAA,EAAO;AAClB,MAAA,MAAM,IAAI,aAAA,CAAc,CAAA,wBAAA,EAA2B,QAAA,CAAS,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,IAC7E;AAEA,IAAA,OAAO,QAAA,CAAS,IAAA;AAAA,EAClB;AACF;AC/LO,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 * HTTP client for Lanonasis API\n */\n\nimport { ConfigurationError } from \"../core/errors.js\";\n\nexport interface HttpClientConfig {\n apiUrl: string;\n apiKey: string;\n timeout?: number;\n headers?: Record<string, string>;\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 class HttpClient {\n private apiUrl: string;\n private apiKey: string;\n private timeout: number;\n private headers: Record<string, string>;\n\n constructor(config: HttpClientConfig) {\n if (!config.apiKey) {\n throw new ConfigurationError(\"API key is required\");\n }\n\n if (!config.apiKey.startsWith(\"lano_\")) {\n throw new ConfigurationError(\n \"Invalid API key format. API key should start with 'lano_'\"\n );\n }\n\n this.apiUrl = config.apiUrl.replace(/\\/$/, \"\"); // Remove trailing slash\n this.apiKey = config.apiKey;\n this.timeout = config.timeout || 30000;\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"X-API-Key\": this.apiKey,\n ...config.headers,\n };\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 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","/**\n * Core Memory Intelligence Client\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} from \"./types.js\";\nimport { ConfigurationError, DatabaseError } from \"./errors.js\";\nimport { HttpClient } from \"../utils/http-client.js\";\n\nconst DEFAULT_API_URL = \"https://api.lanonasis.com/api/v1\";\n\nexport class MemoryIntelligenceClient {\n private httpClient: HttpClient;\n private defaultResponseFormat: \"json\" | \"markdown\";\n\n constructor(config: MemoryIntelligenceConfig) {\n // Validate configuration\n if (!config.apiKey) {\n throw new ConfigurationError(\n \"Missing required configuration: apiKey is required (format: lano_xxxxxxxxxx)\"\n );\n }\n\n this.httpClient = new HttpClient({\n apiUrl: config.apiUrl || DEFAULT_API_URL,\n apiKey: config.apiKey,\n timeout: config.timeout,\n headers: config.headers,\n });\n\n this.defaultResponseFormat = config.responseFormat || \"markdown\";\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<PatternAnalysis> {\n const response = await this.httpClient.post<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 response.data!;\n }\n\n /**\n * Get AI-powered tag suggestions for a memory\n */\n async suggestTags(params: SuggestTagsParams): Promise<TagSuggestionsResult> {\n const response = await this.httpClient.post<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 response.data!;\n }\n\n /**\n * Find semantically related memories using vector similarity\n */\n async findRelated(params: FindRelatedParams): Promise<RelatedMemoriesResult> {\n const response = await this.httpClient.post<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 response.data!;\n }\n\n /**\n * Detect potential duplicate memories\n */\n async detectDuplicates(params: DetectDuplicatesParams): Promise<DuplicatesResult> {\n const response = await this.httpClient.post<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 response.data!;\n }\n\n /**\n * Extract insights and patterns from memories\n */\n async extractInsights(params: ExtractInsightsParams): Promise<InsightsResult> {\n const response = await this.httpClient.post<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 response.data!;\n }\n\n /**\n * Check the health and organization quality of memories\n */\n async healthCheck(params: HealthCheckParams): Promise<MemoryHealth> {\n const response = await this.httpClient.post<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 response.data!;\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// 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 timeout?: number; // Request timeout in milliseconds (default: 30000)\n responseFormat?: ResponseFormatType;\n headers?: Record<string, string>; // Custom headers\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 DuplicatePair {\n memory_1: {\n id: string;\n title: string;\n created_at: string;\n };\n memory_2: {\n id: string;\n title: string;\n created_at: string;\n };\n similarity_score: number;\n recommendation: \"keep_newer\" | \"keep_older\" | \"merge\" | \"review_manually\";\n reasoning: string;\n}\n\nexport interface DuplicatesResult {\n total_memories_analyzed: number;\n duplicate_pairs_found: number;\n duplicate_pairs: DuplicatePair[];\n estimated_storage_savings: string;\n}\n\nexport interface Insight {\n category: \"pattern\" | \"learning\" | \"opportunity\" | \"risk\" | \"action_item\";\n title: string;\n description: string;\n confidence: number;\n supporting_memories: string[];\n}\n\nexport interface InsightsResult {\n total_memories_analyzed: number;\n insights: Insight[];\n summary: string;\n topic_filter?: string;\n type_filter?: string;\n}\n\nexport interface MemoryHealth {\n user_id: string;\n health_score: number;\n metrics: {\n total_memories: number;\n memories_with_embeddings: number;\n embedding_coverage_percentage: number;\n memories_with_tags: number;\n tagging_percentage: number;\n average_tags_per_memory: number;\n memories_by_type: Record<string, number>;\n };\n issues: string[];\n recommendations: string[];\n analysis_date: 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/core/types.ts","../../src/core/prediction-types.ts"],"names":["z"],"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,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AAAA,EACd;AACF;AAEO,IAAM,mBAAA,GAAN,cAAkC,uBAAA,CAAwB;AAAA,EAC/D,YAAY,QAAA,EAAkB;AAC5B,IAAA,KAAA,CAAM,CAAA,kBAAA,EAAqB,QAAQ,CAAA,CAAE,CAAA;AACrC,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAEO,IAAM,aAAA,GAAN,cAA4B,uBAAA,CAA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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 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;\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 if (!config.apiKey) {\n throw new ConfigurationError(\"API key is required\");\n }\n\n if (!config.apiKey.startsWith(\"lano_\")) {\n throw new ConfigurationError(\n \"Invalid API key format. API key should start with 'lano_'\"\n );\n }\n\n this.apiUrl = config.apiUrl.replace(/\\/$/, \"\"); // Remove trailing slash\n this.apiKey = config.apiKey;\n this.timeout = config.timeout || 30000;\n this.processingMode = config.processingMode || \"api\";\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"X-API-Key\": this.apiKey,\n ...config.headers,\n };\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 { ConfigurationError, 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 // Validate configuration\n if (!config.apiKey) {\n throw new ConfigurationError(\n \"Missing required configuration: apiKey is required (format: lano_xxxxxxxxxx)\"\n );\n }\n\n this.processingMode = config.processingMode || \"api\";\n\n this.httpClient = new HttpClient({\n apiUrl: config.apiUrl || DEFAULT_API_URL,\n apiKey: config.apiKey,\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 * 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 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","/**\n * Predictive Memory System Types\n *\n * The AI that anticipates what you need before you realize it.\n *\n * Scoring Algorithm:\n * - Semantic similarity to current context (40%)\n * - Temporal relevance (recency decay curve) (30%)\n * - Usage frequency of similar memories (20%)\n * - Serendipity factor (adjacent/surprising topics) (10%)\n */\n\nimport { z } from \"zod\";\nimport { ResponseFormatType, MemoryTypeValue } from \"./types.js\";\n\n// ============================================================================\n// Input Parameters\n// ============================================================================\n\n/**\n * Context describing the user's current work/focus\n */\nexport interface PredictiveContext {\n /** Current project or task description */\n currentProject?: string;\n\n /** Recent work patterns or topics */\n recentTopics?: string[];\n\n /** Current files being worked on */\n activeFiles?: string[];\n\n /** Free-form context text (e.g., current task, meeting notes) */\n contextText?: string;\n\n /** Team channel or conversation topics (for team-aware predictions) */\n teamContext?: string;\n}\n\n/**\n * Parameters for predictive memory recall\n */\nexport interface PredictiveRecallParams {\n /** User ID */\n userId: string;\n\n /** Current context for prediction scoring */\n context: PredictiveContext;\n\n /** Maximum predictions to return (default: 5, max: 20) */\n limit?: number;\n\n /** Minimum confidence threshold (0-100, default: 40) */\n minConfidence?: number;\n\n /** Include serendipity/surprise suggestions (default: true) */\n includeSerendipity?: boolean;\n\n /** Filter by memory types */\n memoryTypes?: MemoryTypeValue[];\n\n /** Time window in days for recency scoring (default: 90) */\n timeWindowDays?: number;\n\n /** Response format */\n responseFormat?: ResponseFormatType;\n}\n\n// Zod schema for MCP/API validation\nexport const PredictiveRecallParamsSchema = z.object({\n userId: z.string().uuid(),\n context: z.object({\n currentProject: z.string().optional(),\n recentTopics: z.array(z.string()).optional(),\n activeFiles: z.array(z.string()).optional(),\n contextText: z.string().optional(),\n teamContext: z.string().optional(),\n }),\n limit: z.number().int().min(1).max(20).default(5),\n minConfidence: z.number().min(0).max(100).default(40),\n includeSerendipity: z.boolean().default(true),\n memoryTypes: z.array(z.enum([\n \"context\", \"project\", \"knowledge\", \"reference\", \"personal\", \"workflow\"\n ])).optional(),\n timeWindowDays: z.number().int().min(1).max(365).default(90),\n responseFormat: z.enum([\"json\", \"markdown\"]).default(\"markdown\"),\n});\n\n// ============================================================================\n// Scoring Components\n// ============================================================================\n\n/**\n * Individual scoring factors for a prediction\n */\nexport interface PredictionScoreBreakdown {\n /** Semantic similarity to current context (0-100) */\n semanticScore: number;\n\n /** Temporal relevance based on age (0-100) */\n temporalScore: number;\n\n /** Usage frequency of similar content (0-100) */\n frequencyScore: number;\n\n /** Serendipity/surprise factor (0-100) */\n serendipityScore: number;\n\n /** Weighted combination (0-100) */\n combinedScore: number;\n}\n\n/**\n * Reason why a memory was predicted\n */\nexport type PredictionReason =\n | \"semantic_match\" // High semantic similarity to current context\n | \"recent_related\" // Recently viewed similar content\n | \"team_trending\" // Team is discussing related topics\n | \"pattern_match\" // Matches user's work patterns\n | \"adjacent_discovery\" // Serendipitous adjacent topic\n | \"expert_topic\" // User has expertise in this area\n | \"prerequisite\" // Foundational for current work\n | \"frequently_used\"; // Often accessed in similar contexts\n\n// ============================================================================\n// Output Types\n// ============================================================================\n\n/**\n * A single predicted memory with confidence and explanation\n */\nexport interface PredictedMemory {\n /** Memory ID */\n id: string;\n\n /** Memory title */\n title: string;\n\n /** Memory type */\n type: MemoryTypeValue;\n\n /** Memory tags */\n tags: string[];\n\n /** Content preview (first 300 chars) */\n contentPreview: string;\n\n /** Confidence score (0-100) */\n confidence: number;\n\n /** Human-readable explanation of why this was predicted */\n reason: string;\n\n /** Structured reason type */\n reasonType: PredictionReason;\n\n /** Detailed score breakdown */\n scoreBreakdown: PredictionScoreBreakdown;\n\n /** Days since memory was created */\n daysSinceCreated: number;\n\n /** Days since memory was last accessed */\n daysSinceAccessed?: number;\n\n /** Suggested action for the user */\n suggestedAction: \"review\" | \"apply\" | \"reference\" | \"explore\";\n\n /** Related topic clusters */\n relatedTopics?: string[];\n}\n\n/**\n * Result of predictive recall operation\n */\nexport interface PredictiveRecallResult {\n /** Predicted memories ranked by confidence */\n predictions: PredictedMemory[];\n\n /** Total predictions returned */\n totalPredictions: number;\n\n /** Total memories analyzed */\n memoriesAnalyzed: number;\n\n /** Context that was used for prediction */\n contextUsed: {\n projectContext: boolean;\n topicsContext: boolean;\n filesContext: boolean;\n textContext: boolean;\n teamContext: boolean;\n };\n\n /** Scoring weights used */\n scoringWeights: {\n semantic: number;\n temporal: number;\n frequency: number;\n serendipity: number;\n };\n\n /** Algorithm metadata */\n algorithmInfo: {\n version: string;\n embeddingModel: string;\n timeWindowDays: number;\n };\n\n /** Timestamp of prediction */\n generatedAt: string;\n}\n\n// ============================================================================\n// Internal Types (for engine use)\n// ============================================================================\n\n/**\n * Internal memory representation with embedding for scoring\n */\nexport interface ScoredMemoryCandidate {\n id: string;\n title: string;\n content: string;\n type: MemoryTypeValue;\n tags: string[];\n embedding: number[];\n createdAt: Date;\n updatedAt: Date;\n metadata?: Record<string, any>;\n accessCount?: number;\n}\n\n/**\n * Scoring configuration (tunable weights)\n */\nexport interface PredictionScoringConfig {\n /** Weight for semantic similarity (default: 0.40) */\n semanticWeight: number;\n\n /** Weight for temporal relevance (default: 0.30) */\n temporalWeight: number;\n\n /** Weight for usage frequency (default: 0.20) */\n frequencyWeight: number;\n\n /** Weight for serendipity (default: 0.10) */\n serendipityWeight: number;\n\n /** Decay rate for temporal scoring (half-life in days) */\n temporalDecayHalfLife: number;\n\n /** Similarity threshold for semantic matching */\n semanticThreshold: number;\n\n /** Serendipity similarity range (min-max for \"adjacent\" topics) */\n serendipityRange: {\n min: number;\n max: number;\n };\n}\n\n/**\n * Default scoring configuration\n */\nexport const DEFAULT_SCORING_CONFIG: PredictionScoringConfig = {\n semanticWeight: 0.40,\n temporalWeight: 0.30,\n frequencyWeight: 0.20,\n serendipityWeight: 0.10,\n temporalDecayHalfLife: 14, // 2 weeks\n semanticThreshold: 0.5,\n serendipityRange: {\n min: 0.3, // Not too similar\n max: 0.6, // Not too different\n },\n};\n\n// ============================================================================\n// Feedback Types (for learning loop)\n// ============================================================================\n\n/**\n * User feedback on a prediction\n */\nexport interface PredictionFeedback {\n /** Prediction/memory ID */\n memoryId: string;\n\n /** User ID */\n userId: string;\n\n /** Was this prediction useful? */\n useful: boolean;\n\n /** Action taken */\n action: \"clicked\" | \"saved\" | \"dismissed\" | \"ignored\";\n\n /** Optional reason for dismissal */\n dismissReason?: \"not_relevant\" | \"already_know\" | \"not_now\" | \"other\";\n\n /** Timestamp */\n timestamp: string;\n}\n\n/**\n * Aggregated feedback for model improvement\n */\nexport interface PredictionAccuracyMetrics {\n /** Total predictions made */\n totalPredictions: number;\n\n /** Predictions marked as useful */\n usefulPredictions: number;\n\n /** Predictions clicked/engaged */\n engagedPredictions: number;\n\n /** Accuracy rate (useful / total) */\n accuracyRate: number;\n\n /** Engagement rate (engaged / total) */\n engagementRate: number;\n\n /** Time period analyzed */\n timePeriod: {\n start: string;\n end: string;\n };\n}\n"]}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Predictive Memory System Types
|
|
3
|
+
*
|
|
4
|
+
* The AI that anticipates what you need before you realize it.
|
|
5
|
+
*
|
|
6
|
+
* Scoring Algorithm:
|
|
7
|
+
* - Semantic similarity to current context (40%)
|
|
8
|
+
* - Temporal relevance (recency decay curve) (30%)
|
|
9
|
+
* - Usage frequency of similar memories (20%)
|
|
10
|
+
* - Serendipity factor (adjacent/surprising topics) (10%)
|
|
11
|
+
*/
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
import { ResponseFormatType, MemoryTypeValue } from "./types.js";
|
|
14
|
+
/**
|
|
15
|
+
* Context describing the user's current work/focus
|
|
16
|
+
*/
|
|
17
|
+
export interface PredictiveContext {
|
|
18
|
+
/** Current project or task description */
|
|
19
|
+
currentProject?: string;
|
|
20
|
+
/** Recent work patterns or topics */
|
|
21
|
+
recentTopics?: string[];
|
|
22
|
+
/** Current files being worked on */
|
|
23
|
+
activeFiles?: string[];
|
|
24
|
+
/** Free-form context text (e.g., current task, meeting notes) */
|
|
25
|
+
contextText?: string;
|
|
26
|
+
/** Team channel or conversation topics (for team-aware predictions) */
|
|
27
|
+
teamContext?: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Parameters for predictive memory recall
|
|
31
|
+
*/
|
|
32
|
+
export interface PredictiveRecallParams {
|
|
33
|
+
/** User ID */
|
|
34
|
+
userId: string;
|
|
35
|
+
/** Current context for prediction scoring */
|
|
36
|
+
context: PredictiveContext;
|
|
37
|
+
/** Maximum predictions to return (default: 5, max: 20) */
|
|
38
|
+
limit?: number;
|
|
39
|
+
/** Minimum confidence threshold (0-100, default: 40) */
|
|
40
|
+
minConfidence?: number;
|
|
41
|
+
/** Include serendipity/surprise suggestions (default: true) */
|
|
42
|
+
includeSerendipity?: boolean;
|
|
43
|
+
/** Filter by memory types */
|
|
44
|
+
memoryTypes?: MemoryTypeValue[];
|
|
45
|
+
/** Time window in days for recency scoring (default: 90) */
|
|
46
|
+
timeWindowDays?: number;
|
|
47
|
+
/** Response format */
|
|
48
|
+
responseFormat?: ResponseFormatType;
|
|
49
|
+
}
|
|
50
|
+
export declare const PredictiveRecallParamsSchema: z.ZodObject<{
|
|
51
|
+
userId: z.ZodString;
|
|
52
|
+
context: z.ZodObject<{
|
|
53
|
+
currentProject: z.ZodOptional<z.ZodString>;
|
|
54
|
+
recentTopics: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
55
|
+
activeFiles: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
56
|
+
contextText: z.ZodOptional<z.ZodString>;
|
|
57
|
+
teamContext: z.ZodOptional<z.ZodString>;
|
|
58
|
+
}, "strip", z.ZodTypeAny, {
|
|
59
|
+
currentProject?: string | undefined;
|
|
60
|
+
recentTopics?: string[] | undefined;
|
|
61
|
+
activeFiles?: string[] | undefined;
|
|
62
|
+
contextText?: string | undefined;
|
|
63
|
+
teamContext?: string | undefined;
|
|
64
|
+
}, {
|
|
65
|
+
currentProject?: string | undefined;
|
|
66
|
+
recentTopics?: string[] | undefined;
|
|
67
|
+
activeFiles?: string[] | undefined;
|
|
68
|
+
contextText?: string | undefined;
|
|
69
|
+
teamContext?: string | undefined;
|
|
70
|
+
}>;
|
|
71
|
+
limit: z.ZodDefault<z.ZodNumber>;
|
|
72
|
+
minConfidence: z.ZodDefault<z.ZodNumber>;
|
|
73
|
+
includeSerendipity: z.ZodDefault<z.ZodBoolean>;
|
|
74
|
+
memoryTypes: z.ZodOptional<z.ZodArray<z.ZodEnum<["context", "project", "knowledge", "reference", "personal", "workflow"]>, "many">>;
|
|
75
|
+
timeWindowDays: z.ZodDefault<z.ZodNumber>;
|
|
76
|
+
responseFormat: z.ZodDefault<z.ZodEnum<["json", "markdown"]>>;
|
|
77
|
+
}, "strip", z.ZodTypeAny, {
|
|
78
|
+
context: {
|
|
79
|
+
currentProject?: string | undefined;
|
|
80
|
+
recentTopics?: string[] | undefined;
|
|
81
|
+
activeFiles?: string[] | undefined;
|
|
82
|
+
contextText?: string | undefined;
|
|
83
|
+
teamContext?: string | undefined;
|
|
84
|
+
};
|
|
85
|
+
userId: string;
|
|
86
|
+
limit: number;
|
|
87
|
+
minConfidence: number;
|
|
88
|
+
includeSerendipity: boolean;
|
|
89
|
+
timeWindowDays: number;
|
|
90
|
+
responseFormat: "json" | "markdown";
|
|
91
|
+
memoryTypes?: ("context" | "project" | "knowledge" | "reference" | "personal" | "workflow")[] | undefined;
|
|
92
|
+
}, {
|
|
93
|
+
context: {
|
|
94
|
+
currentProject?: string | undefined;
|
|
95
|
+
recentTopics?: string[] | undefined;
|
|
96
|
+
activeFiles?: string[] | undefined;
|
|
97
|
+
contextText?: string | undefined;
|
|
98
|
+
teamContext?: string | undefined;
|
|
99
|
+
};
|
|
100
|
+
userId: string;
|
|
101
|
+
limit?: number | undefined;
|
|
102
|
+
minConfidence?: number | undefined;
|
|
103
|
+
includeSerendipity?: boolean | undefined;
|
|
104
|
+
memoryTypes?: ("context" | "project" | "knowledge" | "reference" | "personal" | "workflow")[] | undefined;
|
|
105
|
+
timeWindowDays?: number | undefined;
|
|
106
|
+
responseFormat?: "json" | "markdown" | undefined;
|
|
107
|
+
}>;
|
|
108
|
+
/**
|
|
109
|
+
* Individual scoring factors for a prediction
|
|
110
|
+
*/
|
|
111
|
+
export interface PredictionScoreBreakdown {
|
|
112
|
+
/** Semantic similarity to current context (0-100) */
|
|
113
|
+
semanticScore: number;
|
|
114
|
+
/** Temporal relevance based on age (0-100) */
|
|
115
|
+
temporalScore: number;
|
|
116
|
+
/** Usage frequency of similar content (0-100) */
|
|
117
|
+
frequencyScore: number;
|
|
118
|
+
/** Serendipity/surprise factor (0-100) */
|
|
119
|
+
serendipityScore: number;
|
|
120
|
+
/** Weighted combination (0-100) */
|
|
121
|
+
combinedScore: number;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Reason why a memory was predicted
|
|
125
|
+
*/
|
|
126
|
+
export type PredictionReason = "semantic_match" | "recent_related" | "team_trending" | "pattern_match" | "adjacent_discovery" | "expert_topic" | "prerequisite" | "frequently_used";
|
|
127
|
+
/**
|
|
128
|
+
* A single predicted memory with confidence and explanation
|
|
129
|
+
*/
|
|
130
|
+
export interface PredictedMemory {
|
|
131
|
+
/** Memory ID */
|
|
132
|
+
id: string;
|
|
133
|
+
/** Memory title */
|
|
134
|
+
title: string;
|
|
135
|
+
/** Memory type */
|
|
136
|
+
type: MemoryTypeValue;
|
|
137
|
+
/** Memory tags */
|
|
138
|
+
tags: string[];
|
|
139
|
+
/** Content preview (first 300 chars) */
|
|
140
|
+
contentPreview: string;
|
|
141
|
+
/** Confidence score (0-100) */
|
|
142
|
+
confidence: number;
|
|
143
|
+
/** Human-readable explanation of why this was predicted */
|
|
144
|
+
reason: string;
|
|
145
|
+
/** Structured reason type */
|
|
146
|
+
reasonType: PredictionReason;
|
|
147
|
+
/** Detailed score breakdown */
|
|
148
|
+
scoreBreakdown: PredictionScoreBreakdown;
|
|
149
|
+
/** Days since memory was created */
|
|
150
|
+
daysSinceCreated: number;
|
|
151
|
+
/** Days since memory was last accessed */
|
|
152
|
+
daysSinceAccessed?: number;
|
|
153
|
+
/** Suggested action for the user */
|
|
154
|
+
suggestedAction: "review" | "apply" | "reference" | "explore";
|
|
155
|
+
/** Related topic clusters */
|
|
156
|
+
relatedTopics?: string[];
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Result of predictive recall operation
|
|
160
|
+
*/
|
|
161
|
+
export interface PredictiveRecallResult {
|
|
162
|
+
/** Predicted memories ranked by confidence */
|
|
163
|
+
predictions: PredictedMemory[];
|
|
164
|
+
/** Total predictions returned */
|
|
165
|
+
totalPredictions: number;
|
|
166
|
+
/** Total memories analyzed */
|
|
167
|
+
memoriesAnalyzed: number;
|
|
168
|
+
/** Context that was used for prediction */
|
|
169
|
+
contextUsed: {
|
|
170
|
+
projectContext: boolean;
|
|
171
|
+
topicsContext: boolean;
|
|
172
|
+
filesContext: boolean;
|
|
173
|
+
textContext: boolean;
|
|
174
|
+
teamContext: boolean;
|
|
175
|
+
};
|
|
176
|
+
/** Scoring weights used */
|
|
177
|
+
scoringWeights: {
|
|
178
|
+
semantic: number;
|
|
179
|
+
temporal: number;
|
|
180
|
+
frequency: number;
|
|
181
|
+
serendipity: number;
|
|
182
|
+
};
|
|
183
|
+
/** Algorithm metadata */
|
|
184
|
+
algorithmInfo: {
|
|
185
|
+
version: string;
|
|
186
|
+
embeddingModel: string;
|
|
187
|
+
timeWindowDays: number;
|
|
188
|
+
};
|
|
189
|
+
/** Timestamp of prediction */
|
|
190
|
+
generatedAt: string;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Internal memory representation with embedding for scoring
|
|
194
|
+
*/
|
|
195
|
+
export interface ScoredMemoryCandidate {
|
|
196
|
+
id: string;
|
|
197
|
+
title: string;
|
|
198
|
+
content: string;
|
|
199
|
+
type: MemoryTypeValue;
|
|
200
|
+
tags: string[];
|
|
201
|
+
embedding: number[];
|
|
202
|
+
createdAt: Date;
|
|
203
|
+
updatedAt: Date;
|
|
204
|
+
metadata?: Record<string, any>;
|
|
205
|
+
accessCount?: number;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Scoring configuration (tunable weights)
|
|
209
|
+
*/
|
|
210
|
+
export interface PredictionScoringConfig {
|
|
211
|
+
/** Weight for semantic similarity (default: 0.40) */
|
|
212
|
+
semanticWeight: number;
|
|
213
|
+
/** Weight for temporal relevance (default: 0.30) */
|
|
214
|
+
temporalWeight: number;
|
|
215
|
+
/** Weight for usage frequency (default: 0.20) */
|
|
216
|
+
frequencyWeight: number;
|
|
217
|
+
/** Weight for serendipity (default: 0.10) */
|
|
218
|
+
serendipityWeight: number;
|
|
219
|
+
/** Decay rate for temporal scoring (half-life in days) */
|
|
220
|
+
temporalDecayHalfLife: number;
|
|
221
|
+
/** Similarity threshold for semantic matching */
|
|
222
|
+
semanticThreshold: number;
|
|
223
|
+
/** Serendipity similarity range (min-max for "adjacent" topics) */
|
|
224
|
+
serendipityRange: {
|
|
225
|
+
min: number;
|
|
226
|
+
max: number;
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Default scoring configuration
|
|
231
|
+
*/
|
|
232
|
+
export declare const DEFAULT_SCORING_CONFIG: PredictionScoringConfig;
|
|
233
|
+
/**
|
|
234
|
+
* User feedback on a prediction
|
|
235
|
+
*/
|
|
236
|
+
export interface PredictionFeedback {
|
|
237
|
+
/** Prediction/memory ID */
|
|
238
|
+
memoryId: string;
|
|
239
|
+
/** User ID */
|
|
240
|
+
userId: string;
|
|
241
|
+
/** Was this prediction useful? */
|
|
242
|
+
useful: boolean;
|
|
243
|
+
/** Action taken */
|
|
244
|
+
action: "clicked" | "saved" | "dismissed" | "ignored";
|
|
245
|
+
/** Optional reason for dismissal */
|
|
246
|
+
dismissReason?: "not_relevant" | "already_know" | "not_now" | "other";
|
|
247
|
+
/** Timestamp */
|
|
248
|
+
timestamp: string;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Aggregated feedback for model improvement
|
|
252
|
+
*/
|
|
253
|
+
export interface PredictionAccuracyMetrics {
|
|
254
|
+
/** Total predictions made */
|
|
255
|
+
totalPredictions: number;
|
|
256
|
+
/** Predictions marked as useful */
|
|
257
|
+
usefulPredictions: number;
|
|
258
|
+
/** Predictions clicked/engaged */
|
|
259
|
+
engagedPredictions: number;
|
|
260
|
+
/** Accuracy rate (useful / total) */
|
|
261
|
+
accuracyRate: number;
|
|
262
|
+
/** Engagement rate (engaged / total) */
|
|
263
|
+
engagementRate: number;
|
|
264
|
+
/** Time period analyzed */
|
|
265
|
+
timePeriod: {
|
|
266
|
+
start: string;
|
|
267
|
+
end: string;
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
//# sourceMappingURL=prediction-types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prediction-types.d.ts","sourceRoot":"","sources":["../../src/core/prediction-types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAMjE;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,0CAA0C;IAC1C,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB,qCAAqC;IACrC,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IAExB,oCAAoC;IACpC,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;IAEvB,iEAAiE;IACjE,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB,uEAAuE;IACvE,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC,cAAc;IACd,MAAM,EAAE,MAAM,CAAC;IAEf,6CAA6C;IAC7C,OAAO,EAAE,iBAAiB,CAAC;IAE3B,0DAA0D;IAC1D,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,wDAAwD;IACxD,aAAa,CAAC,EAAE,MAAM,CAAC;IAEvB,+DAA+D;IAC/D,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAE7B,6BAA6B;IAC7B,WAAW,CAAC,EAAE,eAAe,EAAE,CAAC;IAEhC,4DAA4D;IAC5D,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB,sBAAsB;IACtB,cAAc,CAAC,EAAE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,12 +9,48 @@ export declare const ResponseFormat: {
|
|
|
9
9
|
export type ResponseFormatType = (typeof ResponseFormat)[keyof typeof ResponseFormat];
|
|
10
10
|
export declare const MemoryType: z.ZodEnum<["context", "project", "knowledge", "reference", "personal", "workflow"]>;
|
|
11
11
|
export type MemoryTypeValue = z.infer<typeof MemoryType>;
|
|
12
|
+
export type ProcessingMode = 'api' | 'offline-fallback';
|
|
12
13
|
export interface MemoryIntelligenceConfig {
|
|
13
14
|
apiUrl?: string;
|
|
14
15
|
apiKey: string;
|
|
15
16
|
timeout?: number;
|
|
16
17
|
responseFormat?: ResponseFormatType;
|
|
17
18
|
headers?: Record<string, string>;
|
|
19
|
+
/**
|
|
20
|
+
* Processing mode for intelligence operations
|
|
21
|
+
* - 'api': Always use Lanonasis API endpoints (default)
|
|
22
|
+
* - 'offline-fallback': Use API, fall back to cached/local data if unreachable
|
|
23
|
+
* @default 'api'
|
|
24
|
+
*/
|
|
25
|
+
processingMode?: ProcessingMode;
|
|
26
|
+
/**
|
|
27
|
+
* Enable caching of API responses for offline fallback
|
|
28
|
+
* Only used when processingMode is 'offline-fallback'
|
|
29
|
+
* @default true
|
|
30
|
+
*/
|
|
31
|
+
enableCache?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Cache TTL in milliseconds (default: 5 minutes)
|
|
34
|
+
* @default 300000
|
|
35
|
+
*/
|
|
36
|
+
cacheTTL?: number;
|
|
37
|
+
}
|
|
38
|
+
export interface EdgeFunctionResponse<T> {
|
|
39
|
+
success: boolean;
|
|
40
|
+
data?: T;
|
|
41
|
+
error?: {
|
|
42
|
+
message: string;
|
|
43
|
+
code?: string;
|
|
44
|
+
};
|
|
45
|
+
usage?: {
|
|
46
|
+
tokens_used: number;
|
|
47
|
+
cost_usd: number;
|
|
48
|
+
cached: boolean;
|
|
49
|
+
};
|
|
50
|
+
tier_info?: {
|
|
51
|
+
tier: string;
|
|
52
|
+
usage_remaining: number;
|
|
53
|
+
};
|
|
18
54
|
}
|
|
19
55
|
export interface AnalyzePatternsParams {
|
|
20
56
|
userId: string;
|
|
@@ -99,56 +135,76 @@ export interface RelatedMemoriesResult {
|
|
|
99
135
|
related_memories: RelatedMemory[];
|
|
100
136
|
total_found: number;
|
|
101
137
|
}
|
|
102
|
-
export interface
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
};
|
|
138
|
+
export interface DuplicateEntry {
|
|
139
|
+
id: string;
|
|
140
|
+
title: string;
|
|
141
|
+
similarity: number;
|
|
142
|
+
created_at: string;
|
|
143
|
+
}
|
|
144
|
+
export interface DuplicateGroup {
|
|
145
|
+
primary_id: string;
|
|
146
|
+
primary_title: string;
|
|
147
|
+
duplicates: DuplicateEntry[];
|
|
113
148
|
similarity_score: number;
|
|
114
|
-
recommendation: "keep_newer" | "keep_older" | "merge" | "review_manually";
|
|
115
|
-
reasoning: string;
|
|
116
149
|
}
|
|
117
150
|
export interface DuplicatesResult {
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
151
|
+
duplicate_groups: DuplicateGroup[];
|
|
152
|
+
total_groups: number;
|
|
153
|
+
total_duplicates: number;
|
|
154
|
+
detection_method: "semantic" | "text";
|
|
155
|
+
threshold_used: number;
|
|
156
|
+
memories_analyzed: number;
|
|
157
|
+
potential_storage_savings: string;
|
|
122
158
|
}
|
|
123
159
|
export interface Insight {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
description: string;
|
|
160
|
+
type: "themes" | "connections" | "gaps" | "actions" | "summary";
|
|
161
|
+
content: string;
|
|
127
162
|
confidence: number;
|
|
128
|
-
|
|
163
|
+
related_memory_ids: string[];
|
|
129
164
|
}
|
|
130
165
|
export interface InsightsResult {
|
|
131
|
-
total_memories_analyzed: number;
|
|
132
166
|
insights: Insight[];
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
167
|
+
overall_summary: string;
|
|
168
|
+
memories_analyzed: number;
|
|
169
|
+
insight_types: string[];
|
|
170
|
+
topic_filter?: string | null;
|
|
171
|
+
generated_at: string;
|
|
172
|
+
}
|
|
173
|
+
export interface HealthScoreBreakdown {
|
|
174
|
+
organization: number;
|
|
175
|
+
tagging: number;
|
|
176
|
+
recency: number;
|
|
177
|
+
completeness: number;
|
|
178
|
+
diversity: number;
|
|
179
|
+
}
|
|
180
|
+
export interface HealthScore {
|
|
181
|
+
overall: number;
|
|
182
|
+
breakdown: HealthScoreBreakdown;
|
|
183
|
+
}
|
|
184
|
+
export interface HealthStatistics {
|
|
185
|
+
total_memories: number;
|
|
186
|
+
active_memories: number;
|
|
187
|
+
archived_memories: number;
|
|
188
|
+
memories_with_tags: number;
|
|
189
|
+
unique_tags: number;
|
|
190
|
+
memory_types: number;
|
|
191
|
+
recent_memories_30d: number;
|
|
192
|
+
stale_memories_90d: number;
|
|
193
|
+
}
|
|
194
|
+
export interface HealthIssue {
|
|
195
|
+
severity: "high" | "medium" | "low";
|
|
196
|
+
category: string;
|
|
197
|
+
description: string;
|
|
198
|
+
affected_count: number;
|
|
199
|
+
recommendation: string;
|
|
136
200
|
}
|
|
137
201
|
export interface MemoryHealth {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
memories_with_embeddings: number;
|
|
143
|
-
embedding_coverage_percentage: number;
|
|
144
|
-
memories_with_tags: number;
|
|
145
|
-
tagging_percentage: number;
|
|
146
|
-
average_tags_per_memory: number;
|
|
147
|
-
memories_by_type: Record<string, number>;
|
|
148
|
-
};
|
|
149
|
-
issues: string[];
|
|
202
|
+
health_score: HealthScore;
|
|
203
|
+
status: "excellent" | "good" | "needs_attention" | "poor";
|
|
204
|
+
statistics: HealthStatistics;
|
|
205
|
+
issues: HealthIssue[];
|
|
150
206
|
recommendations: string[];
|
|
151
|
-
|
|
207
|
+
generated_at: string;
|
|
152
208
|
}
|
|
153
209
|
export interface MemoryEntry {
|
|
154
210
|
id: string;
|