devmentorai-server 1.2.2 → 1.2.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "devmentorai-server",
3
- "version": "1.2.2",
3
+ "version": "1.2.3",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "DevMentorAI backend server — AI-powered DevOps mentoring via GitHub Copilot. Run with: npx devmentorai-server",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../packages/shared/src/contracts/api.contracts.ts","../../../packages/shared/src/types/message.ts","../../../packages/shared/src/types/context.ts","../../../packages/shared/src/contracts/session-types.ts","../../../packages/shared/src/utils/helpers.ts","../../../packages/shared/src/utils/update-checker.ts","../src/lib/paths.ts","../src/version.ts"],"sourcesContent":["/**\n * API contract definitions for DevMentorAI\n * These define the endpoints and their request/response types\n */\n\nimport type {\n Session,\n CreateSessionRequest,\n UpdateSessionRequest,\n Message,\n SendMessageRequest,\n ApiResponse,\n PaginatedResponse,\n HealthResponse,\n ModelInfo,\n} from '../types/index.js';\n\n/**\n * Backend API endpoints contract\n */\nexport const API_ENDPOINTS = {\n // Health\n HEALTH: '/api/health',\n \n // Sessions\n SESSIONS: '/api/sessions',\n SESSION: (id: string) => `/api/sessions/${id}`,\n SESSION_RESUME: (id: string) => `/api/sessions/${id}/resume`,\n SESSION_ABORT: (id: string) => `/api/sessions/${id}/abort`,\n SESSION_MESSAGES: (id: string) => `/api/sessions/${id}/messages`,\n \n // Chat\n CHAT: (sessionId: string) => `/api/sessions/${sessionId}/chat`,\n CHAT_STREAM: (sessionId: string) => `/api/sessions/${sessionId}/chat/stream`,\n \n // Models\n MODELS: '/api/models',\n} as const;\n\n/**\n * API endpoint type definitions\n */\nexport interface ApiEndpoints {\n // GET /api/health\n 'GET /api/health': {\n response: ApiResponse<HealthResponse>;\n };\n \n // GET /api/sessions\n 'GET /api/sessions': {\n response: ApiResponse<PaginatedResponse<Session>>;\n };\n \n // POST /api/sessions\n 'POST /api/sessions': {\n body: CreateSessionRequest;\n response: ApiResponse<Session>;\n };\n \n // GET /api/sessions/:id\n 'GET /api/sessions/:id': {\n params: { id: string };\n response: ApiResponse<Session>;\n };\n \n // PATCH /api/sessions/:id\n 'PATCH /api/sessions/:id': {\n params: { id: string };\n body: UpdateSessionRequest;\n response: ApiResponse<Session>;\n };\n \n // DELETE /api/sessions/:id\n 'DELETE /api/sessions/:id': {\n params: { id: string };\n response: ApiResponse<void>;\n };\n \n // POST /api/sessions/:id/resume\n 'POST /api/sessions/:id/resume': {\n params: { id: string };\n response: ApiResponse<Session>;\n };\n \n // POST /api/sessions/:id/abort\n 'POST /api/sessions/:id/abort': {\n params: { id: string };\n response: ApiResponse<void>;\n };\n \n // GET /api/sessions/:id/messages\n 'GET /api/sessions/:id/messages': {\n params: { id: string };\n response: ApiResponse<PaginatedResponse<Message>>;\n };\n \n // POST /api/sessions/:id/chat\n 'POST /api/sessions/:id/chat': {\n params: { id: string };\n body: SendMessageRequest;\n response: ApiResponse<Message>;\n };\n \n // POST /api/sessions/:id/chat/stream (SSE)\n 'POST /api/sessions/:id/chat/stream': {\n params: { id: string };\n body: SendMessageRequest;\n response: ReadableStream; // SSE stream\n };\n \n // GET /api/models\n 'GET /api/models': {\n response: ApiResponse<ModelInfo[]>;\n };\n}\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG = {\n DEFAULT_MODEL: 'gpt-4.1',\n DEFAULT_PORT: 3847,\n DEFAULT_HOST: 'localhost',\n REQUEST_TIMEOUT_MS: 60000,\n STREAM_TIMEOUT_MS: 300000,\n} as const;\n","/**\n * Message type definitions for DevMentorAI\n */\n\nexport type MessageRole = 'user' | 'assistant' | 'system';\n\nexport interface Message {\n id: string;\n sessionId: string;\n role: MessageRole;\n content: string;\n timestamp: string; // ISO date string\n metadata?: MessageMetadata;\n}\n\n// ============================================================================\n// Image Attachment Types\n// ============================================================================\n\nexport type ImageSource = 'screenshot' | 'paste' | 'drop';\nexport type ImageMimeType = 'image/png' | 'image/jpeg' | 'image/webp';\n\nexport interface ImageAttachment {\n id: string;\n source: ImageSource;\n mimeType: ImageMimeType;\n dimensions: { width: number; height: number };\n fileSize: number; // bytes\n timestamp: string; // ISO date string\n /** Original base64 data URL - only present in draft/request, not persisted */\n dataUrl?: string;\n /** Backend-provided thumbnail URL for display in chat history */\n thumbnailUrl?: string;\n /** Backend-provided full image URL for lightbox view */\n fullImageUrl?: string;\n}\n\n/** Image data sent in message request (before processing) */\nexport interface ImagePayload {\n id: string;\n dataUrl: string;\n mimeType: ImageMimeType;\n source: ImageSource;\n}\n\n/** Constants for image handling */\nexport const IMAGE_CONSTANTS = {\n MAX_IMAGES_PER_MESSAGE: 5,\n MAX_IMAGE_SIZE_BYTES: 5 * 1024 * 1024, // 5MB\n SUPPORTED_MIME_TYPES: ['image/png', 'image/jpeg', 'image/webp'] as const,\n THUMBNAIL_MAX_DIMENSION: 200,\n THUMBNAIL_QUALITY: 60,\n} as const;\n\n// ============================================================================\n// Message Metadata\n// ============================================================================\n\nexport interface MessageMetadata {\n pageUrl?: string;\n selectedText?: string;\n action?: QuickAction;\n toolCalls?: ToolCall[];\n streamComplete?: boolean;\n /** Attached images for this message */\n images?: ImageAttachment[];\n /** Whether context-aware mode was used */\n contextAware?: boolean;\n}\n\nexport type QuickAction =\n | 'explain'\n | 'translate'\n | 'rewrite'\n | 'fix_grammar'\n | 'summarize'\n | 'expand'\n | 'analyze_config'\n | 'diagnose_error';\n\nexport interface ToolCall {\n toolName: string;\n toolCallId: string;\n status: 'pending' | 'running' | 'completed' | 'error';\n result?: unknown;\n}\n\nexport interface SendMessageRequest {\n prompt: string;\n context?: MessageContext;\n /** Full extracted context payload for context-aware mode */\n fullContext?: unknown; // ContextPayload - imported separately to avoid circular deps\n /** Whether to use context-aware mode */\n useContextAwareMode?: boolean;\n /** Images to attach to this message */\n images?: ImagePayload[];\n}\n\nexport interface MessageContext {\n pageUrl?: string;\n pageTitle?: string;\n selectedText?: string;\n action?: QuickAction;\n}\n\nexport interface StreamEvent {\n type: StreamEventType;\n data: StreamEventData;\n}\n\nexport type StreamEventType =\n | 'message_start'\n | 'message_delta'\n | 'message_complete'\n | 'tool_start'\n | 'tool_complete'\n | 'error'\n | 'done';\n\nexport interface StreamEventData {\n content?: string;\n deltaContent?: string;\n toolName?: string;\n toolCallId?: string;\n error?: string;\n messageId?: string;\n reason?: string; // Reason for completion (e.g., 'completed', 'timeout', 'idle_timeout')\n}\n","/**\n * Context-Aware Mentor Mode Types\n * \n * These types define the structured context payload that is extracted from\n * the browser and sent to the backend for context-aware AI responses.\n */\n\n// ============================================================================\n// Platform Detection Types\n// ============================================================================\n\nexport type PlatformType =\n | 'azure'\n | 'aws'\n | 'gcp'\n | 'github'\n | 'gitlab'\n | 'datadog'\n | 'newrelic'\n | 'grafana'\n | 'jenkins'\n | 'kubernetes'\n | 'docker'\n | 'generic';\n\nexport interface PlatformDetection {\n type: PlatformType;\n confidence: number; // 0-1\n indicators: string[];\n specificProduct?: string; // e.g., \"Azure DevOps\", \"AWS EC2\"\n specificContext?: Record<string, unknown>; // Phase 2: Platform-specific context\n}\n\n// ============================================================================\n// Error Detection Types\n// ============================================================================\n\nexport type ErrorType = 'error' | 'warning' | 'info';\nexport type ErrorSeverity = 'critical' | 'high' | 'medium' | 'low';\nexport type ErrorSource = 'console' | 'ui' | 'network' | 'dom';\n\nexport interface ExtractedError {\n type: ErrorType;\n message: string;\n source?: ErrorSource;\n severity: ErrorSeverity;\n context?: string; // Surrounding text\n element?: HTMLElementSnapshot;\n stackTrace?: string;\n}\n\nexport interface HTMLElementSnapshot {\n tagName: string;\n id?: string;\n className?: string;\n textContent?: string;\n attributes: Record<string, string>;\n}\n\n// ============================================================================\n// HTML Structure Types\n// ============================================================================\n\nexport type SectionPurpose =\n | 'error-container'\n | 'alert'\n | 'panel'\n | 'table'\n | 'form'\n | 'code-block'\n | 'modal'\n | 'generic';\n\nexport interface HTMLSection {\n purpose: SectionPurpose;\n outerHTML: string; // Truncated to ~500 chars\n textContent: string;\n attributes: Record<string, string>;\n xpath?: string;\n}\n\n// ============================================================================\n// Text Extraction Types\n// ============================================================================\n\nexport interface Heading {\n level: 1 | 2 | 3;\n text: string;\n xpath?: string;\n hierarchy?: string; // Parent > Child hierarchy\n}\n\nexport interface ConsoleLogs {\n errors: string[];\n warnings: string[];\n included: boolean;\n truncated: boolean;\n}\n\n// Phase 2: Console log capture type\nexport interface CapturedConsoleLog {\n level: 'log' | 'warn' | 'error' | 'info' | 'debug';\n message: string;\n timestamp: string;\n stackTrace?: string;\n}\n\n// Phase 2: Network error capture type\nexport interface CapturedNetworkError {\n url: string;\n method: string;\n status?: number;\n statusText?: string;\n errorMessage?: string;\n timestamp: string;\n}\n\nexport interface TextExtractionMetadata {\n totalLength: number;\n truncated: boolean;\n truncationReason?: string;\n}\n\n// ============================================================================\n// User Intent Types (DEPRECATED in Phase 3 - kept for backward compatibility)\n// ============================================================================\n\n/**\n * @deprecated Phase 3: The agent (LLM) now determines intent autonomously.\n * This type is kept for backward compatibility but fields are optional.\n */\nexport type IntentType = 'debug' | 'understand' | 'mentor' | 'help' | 'explain' | 'guide';\n\n/**\n * @deprecated Phase 3: Intent is no longer computed by the extension.\n * The agent interprets user intent directly from their message.\n */\nexport interface UserIntent {\n primary: IntentType;\n keywords: string[];\n explicitGoal?: string;\n implicitSignals: string[];\n}\n\n// ============================================================================\n// Session Context Types\n// ============================================================================\n\n/** Session type specifically for context-aware mode (extends base SessionType) */\nexport type ContextSessionType = 'devops' | 'debugging' | 'frontend' | 'general' | 'writing';\n\nexport interface ContextMessage {\n role: 'user' | 'assistant';\n content: string;\n timestamp: string;\n}\n\n// ============================================================================\n// Visual Context Types (Phase 3)\n// ============================================================================\n\nexport interface ScreenshotData {\n dataUrl: string; // base64 encoded image\n format: 'png' | 'jpeg';\n dimensions: { width: number; height: number };\n fileSize: number; // bytes\n quality?: number; // 0-100 for JPEG\n}\n\nexport interface VisualContext {\n screenshot?: ScreenshotData;\n supported: boolean; // Model supports vision\n included: boolean; // Screenshot actually captured\n reason?: string; // Why included/excluded\n}\n\n// ============================================================================\n// Privacy Types\n// ============================================================================\n\nexport interface PrivacyInfo {\n redactedFields: string[];\n sensitiveDataDetected: boolean;\n consentGiven: boolean;\n dataRetention: 'session' | 'none';\n privacyMaskingApplied?: boolean; // Whether privacy masking was applied\n sensitiveDataTypes?: string[]; // Types of data that were masked (e.g., 'email', 'token')\n}\n\n// ============================================================================\n// Main Context Payload\n// ============================================================================\n\nexport interface ContextPayload {\n // Core Metadata\n metadata: {\n captureTimestamp: string; // ISO 8601\n captureMode: 'auto' | 'manual';\n browserInfo: {\n userAgent: string;\n viewport: { width: number; height: number };\n language: string;\n };\n // Phase 2: Extended metadata\n phase2Features?: {\n consoleLogs: number;\n networkErrors: number;\n codeBlocks: number;\n tables: number;\n forms: number;\n hasModal: boolean;\n };\n // Extended features from context-extractor\n extendedFeatures?: {\n consoleLogs: number;\n networkErrors: number;\n runtimeErrors: number;\n codeBlocks: number;\n tables: number;\n forms: number;\n hasModal: boolean;\n uiState: string;\n privacyMaskingApplied: boolean;\n sensitiveDataTypesFound: string[];\n };\n };\n\n // Page Identity\n page: {\n url: string;\n urlParsed: {\n protocol: string;\n hostname: string;\n pathname: string;\n search: string;\n hash: string;\n };\n title: string;\n favicon?: string;\n platform: PlatformDetection;\n uiState?: Record<string, unknown>;\n };\n\n // Textual Context\n text: {\n selectedText?: string;\n visibleText: string;\n headings: Heading[];\n errors: ExtractedError[];\n logs?: ConsoleLogs;\n // Phase 2: Console and network error capture\n consoleLogs?: CapturedConsoleLog[];\n networkErrors?: CapturedNetworkError[];\n runtimeErrors?: Array<{\n message: string;\n source?: string;\n lineno?: number;\n colno?: number;\n stack?: string;\n timestamp: string;\n type?: string;\n }>;\n metadata: TextExtractionMetadata;\n };\n\n // Structural HTML Context\n structure: {\n relevantSections: HTMLSection[];\n errorContainers: HTMLSection[];\n // Phase 2: Extended structure extraction\n codeBlocks?: HTMLSection[];\n tables?: HTMLSection[];\n forms?: HTMLSection[];\n modal?: HTMLSection;\n activeElements: {\n focusedElement?: HTMLElementSnapshot;\n activeModals?: HTMLSection[];\n activePanels?: HTMLSection[];\n };\n metadata: {\n totalNodes: number;\n extractedNodes: number;\n relevanceScore: number; // 0-1 confidence\n };\n };\n\n // Visual Context (Optional - Phase 3)\n visual?: VisualContext;\n\n // Session Context\n session: {\n sessionId: string;\n sessionType: ContextSessionType;\n intent: UserIntent;\n previousMessages: {\n count: number;\n lastN: ContextMessage[];\n };\n userGoal?: string;\n };\n\n // Privacy & Safety\n privacy: PrivacyInfo;\n}\n\n// ============================================================================\n// Extraction Request/Response Types\n// ============================================================================\n\nexport interface ContextExtractionRequest {\n includeScreenshot?: boolean;\n maxTextLength?: number;\n maxHTMLSections?: number;\n selectedTextOnly?: boolean;\n}\n\nexport interface ContextExtractionResponse {\n success: boolean;\n context?: ContextPayload;\n error?: string;\n extractionTimeMs: number;\n}\n\n// ============================================================================\n// Size Limits Configuration\n// ============================================================================\n\nexport const CONTEXT_SIZE_LIMITS = {\n visibleText: 10000, // chars\n htmlSection: 500, // chars per section\n totalHTML: 5000, // chars total HTML\n headings: 50, // max headings\n errors: 20, // max errors\n consoleLogs: 100, // lines\n screenshot: 1024 * 1024, // 1MB\n selectedText: 5000, // chars\n} as const;\n","/**\n * Session type configurations with pre-defined agents\n */\n\nimport type { SessionType } from '../types/session.js';\n\nexport interface AgentConfig {\n name: string;\n displayName: string;\n description: string;\n prompt: string;\n}\n\nexport interface SessionTypeConfig {\n name: string;\n description: string;\n icon: string;\n agent: AgentConfig | null;\n defaultModel: string;\n}\n\nexport const SESSION_TYPE_CONFIGS: Record<SessionType, SessionTypeConfig> = {\n devops: {\n name: 'DevOps Mentor',\n description: 'Expert in DevOps, cloud infrastructure, and best practices',\n icon: '🛠️',\n defaultModel: 'gpt-4.1',\n agent: {\n name: 'devops-mentor',\n displayName: 'DevOps Mentor',\n description: 'Expert in DevOps, cloud infrastructure, and best practices',\n prompt: `You are a DevOps mentor and expert. You help users with:\n- AWS, Azure, GCP cloud services and best practices\n- Kubernetes, Docker, and container orchestration\n- CI/CD pipelines (GitHub Actions, GitLab CI, Jenkins, CircleCI)\n- Infrastructure as Code (Terraform, Pulumi, CloudFormation, Ansible)\n- Security best practices and compliance\n- Cost optimization and resource management\n- Error diagnosis, log analysis, and troubleshooting\n- Architecture design and scalability patterns\n\nWhen analyzing configurations or errors:\n1. Identify the issue or configuration clearly\n2. Explain WHY something is problematic or recommended\n3. Provide actionable steps to fix or improve\n4. Reference official documentation when helpful\n5. Warn about security implications when relevant\n\nBe concise but thorough. Use code blocks for configurations and commands.`,\n },\n },\n \n writing: {\n name: 'Writing Assistant',\n description: 'Helps with writing, rewriting, and translation',\n icon: '✍️',\n defaultModel: 'gpt-4.1',\n agent: {\n name: 'writing-assistant',\n displayName: 'Writing Assistant',\n description: 'Helps with writing, rewriting, and translation',\n prompt: `You are a professional writing assistant. You help users with:\n- Writing and composing emails (formal, casual, technical)\n- Rewriting text with different tones and styles\n- Grammar, spelling, and clarity improvements\n- Translation between languages (preserving tone and meaning)\n- Summarization and expansion of content\n- Technical documentation writing\n- Business communication and proposals\n\nGuidelines:\n1. Maintain the original meaning and intent\n2. Match the requested tone (formal, casual, friendly, technical)\n3. Preserve formatting when rewriting\n4. For translations, keep cultural nuances in mind\n5. Provide alternatives when helpful\n6. Be concise unless expansion is requested\n\nWhen the user provides text to modify, respond with ONLY the modified text unless they ask for explanation.`,\n },\n },\n \n development: {\n name: 'Development Helper',\n description: 'Assists with code review, debugging, and best practices',\n icon: '💻',\n defaultModel: 'gpt-4.1',\n agent: {\n name: 'dev-helper',\n displayName: 'Development Helper',\n description: 'Assists with code review, debugging, and best practices',\n prompt: `You are a senior software development assistant. You help users with:\n- Code review and improvement suggestions\n- Bug diagnosis and debugging strategies\n- Architecture decisions and design patterns\n- Performance optimization\n- Testing strategies and test writing\n- Documentation and code comments\n- Refactoring and code cleanup\n\nGuidelines:\n1. Be concise and actionable\n2. Explain the \"why\" behind suggestions\n3. Provide code examples when helpful\n4. Consider edge cases and error handling\n5. Suggest tests for critical changes\n6. Reference best practices and patterns\n\nWhen reviewing code, focus on:\n- Correctness and logic errors\n- Security vulnerabilities\n- Performance issues\n- Maintainability and readability\n- Missing error handling`,\n },\n },\n \n general: {\n name: 'General Assistant',\n description: 'General-purpose AI assistant',\n icon: '💬',\n defaultModel: 'gpt-4.1',\n agent: null, // Uses default Copilot behavior\n },\n};\n\n/**\n * Get the agent config for a session type\n */\nexport function getAgentConfig(type: SessionType): AgentConfig | null {\n return SESSION_TYPE_CONFIGS[type]?.agent ?? null;\n}\n\n/**\n * Get the default model for a session type\n */\nexport function getDefaultModel(type: SessionType): string {\n return SESSION_TYPE_CONFIGS[type]?.defaultModel ?? 'gpt-4.1';\n}\n","/**\n * Utility functions for DevMentorAI\n */\n\n/**\n * Generate a unique ID\n */\nexport function generateId(prefix?: string): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 9);\n return prefix ? `${prefix}_${timestamp}${random}` : `${timestamp}${random}`;\n}\n\n/**\n * Generate a session ID\n */\nexport function generateSessionId(): string {\n return generateId('session');\n}\n\n/**\n * Generate a message ID\n */\nexport function generateMessageId(): string {\n return generateId('msg');\n}\n\n/**\n * Format a date as ISO string\n */\nexport function formatDate(date: Date = new Date()): string {\n return date.toISOString();\n}\n\n/**\n * Parse an ISO date string to Date\n */\nexport function parseDate(dateString: string): Date {\n return new Date(dateString);\n}\n\n/**\n * Truncate text to a maximum length\n */\nexport function truncate(text: string, maxLength: number, suffix = '...'): string {\n if (text.length <= maxLength) return text;\n return text.slice(0, maxLength - suffix.length) + suffix;\n}\n\n/**\n * Sleep for a given number of milliseconds\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Retry a function with exponential backoff\n */\nexport async function retry<T>(\n fn: () => Promise<T>,\n options: {\n maxAttempts?: number;\n initialDelay?: number;\n maxDelay?: number;\n backoffFactor?: number;\n } = {}\n): Promise<T> {\n const {\n maxAttempts = 3,\n initialDelay = 1000,\n maxDelay = 30000,\n backoffFactor = 2,\n } = options;\n \n let lastError: Error | undefined;\n let delay = initialDelay;\n \n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n \n if (attempt === maxAttempts) break;\n \n await sleep(delay);\n delay = Math.min(delay * backoffFactor, maxDelay);\n }\n }\n \n throw lastError;\n}\n\n/**\n * Create an AbortController with timeout\n */\nexport function createTimeoutController(timeoutMs: number): AbortController {\n const controller = new AbortController();\n setTimeout(() => controller.abort(), timeoutMs);\n return controller;\n}\n","/**\n * Update checker for DevMentorAI components.\n * Queries GitHub Releases API to detect new versions.\n */\n\nexport type ComponentType = 'backend' | 'extension';\n\nexport interface UpdateInfo {\n hasUpdate: boolean;\n currentVersion: string;\n latestVersion: string;\n releaseUrl: string;\n downloadUrls: { chrome?: string; firefox?: string; npm?: string };\n publishedAt: string;\n}\n\ninterface GitHubRelease {\n tag_name: string;\n html_url: string;\n published_at: string;\n draft: boolean;\n prerelease: boolean;\n assets: Array<{\n name: string;\n browser_download_url: string;\n }>;\n}\n\nconst GITHUB_OWNER = 'BOTOOM';\nconst GITHUB_REPO = 'devmentorai';\nconst TAG_PREFIXES: Record<ComponentType, string> = {\n backend: 'backend-v',\n extension: 'ext-v',\n};\n\nconst CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour\n\ninterface CacheEntry {\n data: UpdateInfo;\n timestamp: number;\n}\n\nconst cache = new Map<string, CacheEntry>();\n\n/**\n * Compare two semver strings. Returns:\n * 1 if a > b, -1 if a < b, 0 if equal\n */\nexport function compareSemver(a: string, b: string): number {\n const pa = a.split('.').map(Number);\n const pb = b.split('.').map(Number);\n for (let i = 0; i < 3; i++) {\n const na = pa[i] ?? 0;\n const nb = pb[i] ?? 0;\n if (na > nb) return 1;\n if (na < nb) return -1;\n }\n return 0;\n}\n\n/**\n * Check if an update is available for a given component.\n * Uses GitHub Releases API with a 1-hour cache.\n *\n * @param component - 'backend' or 'extension'\n * @param currentVersion - Current version string (e.g. '1.0.0')\n * @param fetchFn - Optional fetch function (for environments where global fetch differs)\n */\nexport async function checkForUpdate(\n component: ComponentType,\n currentVersion: string,\n fetchFn: typeof fetch = globalThis.fetch,\n): Promise<UpdateInfo> {\n const cacheKey = `${component}:${currentVersion}`;\n const cached = cache.get(cacheKey);\n if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {\n return cached.data;\n }\n\n const noUpdate: UpdateInfo = {\n hasUpdate: false,\n currentVersion,\n latestVersion: currentVersion,\n releaseUrl: `https://github.com/${GITHUB_OWNER}/${GITHUB_REPO}/releases`,\n downloadUrls: {},\n publishedAt: '',\n };\n\n try {\n const prefix = TAG_PREFIXES[component];\n const response = await fetchFn(\n `https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/releases?per_page=10`,\n {\n headers: { Accept: 'application/vnd.github.v3+json' },\n signal: AbortSignal.timeout(5000),\n },\n );\n\n if (!response.ok) {\n cache.set(cacheKey, { data: noUpdate, timestamp: Date.now() });\n return noUpdate;\n }\n\n const releases = (await response.json()) as GitHubRelease[];\n\n // Find the latest non-draft, non-prerelease release matching our tag prefix\n const matching = releases.find(\n (r) => r.tag_name.startsWith(prefix) && !r.draft && !r.prerelease,\n );\n\n if (!matching) {\n cache.set(cacheKey, { data: noUpdate, timestamp: Date.now() });\n return noUpdate;\n }\n\n const latestVersion = matching.tag_name.replace(prefix, '');\n const hasUpdate = compareSemver(latestVersion, currentVersion) > 0;\n\n const downloadUrls: UpdateInfo['downloadUrls'] = {};\n for (const asset of matching.assets) {\n if (asset.name.includes('chrome')) {\n downloadUrls.chrome = asset.browser_download_url;\n } else if (asset.name.includes('firefox')) {\n downloadUrls.firefox = asset.browser_download_url;\n }\n }\n\n if (component === 'backend') {\n downloadUrls.npm = `https://www.npmjs.com/package/devmentorai-server`;\n }\n\n const result: UpdateInfo = {\n hasUpdate,\n currentVersion,\n latestVersion,\n releaseUrl: matching.html_url,\n downloadUrls,\n publishedAt: matching.published_at,\n };\n\n cache.set(cacheKey, { data: result, timestamp: Date.now() });\n return result;\n } catch {\n cache.set(cacheKey, { data: noUpdate, timestamp: Date.now() });\n return noUpdate;\n }\n}\n\n/**\n * Clear the update check cache (useful for testing or forced refresh).\n */\nexport function clearUpdateCache(): void {\n cache.clear();\n}\n","/**\n * Cross-Platform Path Utilities\n * \n * Provides consistent path handling across Windows, macOS, and Linux.\n * Uses the same pattern as db/index.ts for data directory location.\n */\n\nimport path from 'node:path';\nimport os from 'node:os';\nimport fs from 'node:fs';\n\n/** Base data directory: ~/.devmentorai */\nexport const DATA_DIR = path.join(os.homedir(), '.devmentorai');\n\n/** Images directory: ~/.devmentorai/images */\nexport const IMAGES_DIR = path.join(DATA_DIR, 'images');\n\n/** Logs directory: ~/.devmentorai/logs */\nexport const LOG_DIR = path.join(DATA_DIR, 'logs');\n\n/** Server log file: ~/.devmentorai/logs/server.log */\nexport const LOG_FILE = path.join(LOG_DIR, 'server.log');\n\n/** PID file: ~/.devmentorai/server.pid */\nexport const PID_FILE = path.join(DATA_DIR, 'server.pid');\n\n/** Config file: ~/.devmentorai/config.json */\nexport const CONFIG_FILE = path.join(DATA_DIR, 'config.json');\n\n/**\n * Ensure a directory exists, creating it if necessary\n */\nexport function ensureDir(dirPath: string): void {\n if (!fs.existsSync(dirPath)) {\n fs.mkdirSync(dirPath, { recursive: true });\n }\n}\n\n/**\n * Get the directory path for a session's images\n * @param sessionId - The session ID\n * @returns Absolute path to the session's images directory\n */\nexport function getSessionImagesDir(sessionId: string): string {\n return path.join(IMAGES_DIR, sessionId);\n}\n\n/**\n * Get the directory path for a message's images\n * @param sessionId - The session ID\n * @param messageId - The message ID\n * @returns Absolute path to the message's images directory\n */\nexport function getMessageImagesDir(sessionId: string, messageId: string): string {\n return path.join(IMAGES_DIR, sessionId, messageId);\n}\n\n/**\n * Get the file path for a thumbnail image\n * @param sessionId - The session ID\n * @param messageId - The message ID\n * @param index - The image index (0-based)\n * @returns Absolute path to the thumbnail file\n */\nexport function getThumbnailPath(sessionId: string, messageId: string, index: number): string {\n return path.join(getMessageImagesDir(sessionId, messageId), `thumb_${index}.jpg`);\n}\n\n/**\n * Convert an absolute path to a relative path from DATA_DIR\n * This is used for storing portable paths in the database\n * @param absolutePath - The absolute file path\n * @returns Relative path from DATA_DIR\n */\nexport function toRelativePath(absolutePath: string): string {\n return path.relative(DATA_DIR, absolutePath);\n}\n\n/**\n * Convert an absolute image path to a relative path from IMAGES_DIR\n * This is used for constructing image URLs\n * @param absolutePath - The absolute file path\n * @returns Relative path from IMAGES_DIR (e.g., \"session_xxx/msg_xxx/thumb_0.jpg\")\n */\nexport function toImageRelativePath(absolutePath: string): string {\n return path.relative(IMAGES_DIR, absolutePath);\n}\n\n/**\n * Convert a relative path (from DB) to an absolute path\n * @param relativePath - The relative path stored in DB\n * @returns Absolute file path\n */\nexport function toAbsolutePath(relativePath: string): string {\n return path.join(DATA_DIR, relativePath);\n}\n\n/**\n * Convert a file system path to a URL-safe path (always forward slashes)\n * @param fsPath - The file system path\n * @returns URL-safe path with forward slashes\n */\nexport function toUrlPath(fsPath: string): string {\n return fsPath.split(path.sep).join('/');\n}\n\n/**\n * Delete a directory and all its contents\n * @param dirPath - The directory to delete\n */\nexport function deleteDir(dirPath: string): void {\n if (fs.existsSync(dirPath)) {\n fs.rmSync(dirPath, { recursive: true, force: true });\n }\n}\n\n/**\n * Check if a file exists\n * @param filePath - The file path to check\n * @returns True if the file exists\n */\nexport function fileExists(filePath: string): boolean {\n return fs.existsSync(filePath);\n}\n\n/**\n * Get file stats if the file exists\n * @param filePath - The file path\n * @returns File stats or null if file doesn't exist\n */\nexport function getFileStats(filePath: string): fs.Stats | null {\n try {\n return fs.statSync(filePath);\n } catch {\n return null;\n }\n}\n\n// Initialize directories on module load\nensureDir(IMAGES_DIR);\nensureDir(LOG_DIR);\n","/**\n * Backend version - Single source of truth\n * This file is auto-updated by semantic-release\n */\nexport const BACKEND_VERSION = '1.2.2';\n"],"mappings":";;;;;;;;AAuHO,IAAM,iBAAiB;EAC5B,eAAe;EACf,cAAc;EACd,cAAc;EACd,oBAAoB;EACpB,mBAAmB;;;;AC9Ed,IAAM,kBAAkB;EAC7B,wBAAwB;EACxB,sBAAsB,IAAI,OAAO;;EACjC,sBAAsB,CAAC,aAAa,cAAc,YAAY;EAC9D,yBAAyB;EACzB,mBAAmB;;;;ACoRd,IAAM,sBAAsB;EACjC,aAAa;;EACb,aAAa;;EACb,WAAW;;EACX,UAAU;;EACV,QAAQ;;EACR,aAAa;;EACb,YAAY,OAAO;;EACnB,cAAc;;;;;AC1TT,IAAM,uBAA+D;EAC1E,QAAQ;IACN,MAAM;IACN,aAAa;IACb,MAAM;IACN,cAAc;IACd,OAAO;MACL,MAAM;MACN,aAAa;MACb,aAAa;MACb,QAAQ;;;;;;;;;;;;;;;;;;;;EAqBZ,SAAS;IACP,MAAM;IACN,aAAa;IACb,MAAM;IACN,cAAc;IACd,OAAO;MACL,MAAM;MACN,aAAa;MACb,aAAa;MACb,QAAQ;;;;;;;;;;;;;;;;;;;;EAqBZ,aAAa;IACX,MAAM;IACN,aAAa;IACb,MAAM;IACN,cAAc;IACd,OAAO;MACL,MAAM;MACN,aAAa;MACb,aAAa;MACb,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;EA0BZ,SAAS;IACP,MAAM;IACN,aAAa;IACb,MAAM;IACN,cAAc;IACd,OAAO;;;;AAOL,SAAU,eAAe,MAAiB;AAC9C,SAAO,qBAAqB,IAAI,GAAG,SAAS;AAC9C;AAKM,SAAU,gBAAgB,MAAiB;AAC/C,SAAO,qBAAqB,IAAI,GAAG,gBAAgB;AACrD;;;ACnIM,SAAU,WAAW,QAAe;AACxC,QAAM,YAAY,KAAK,IAAG,EAAG,SAAS,EAAE;AACxC,QA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