opensentinel 2.1.1
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/LICENSE +21 -0
- package/README.md +283 -0
- package/dist/bot-KJ26BG56.js +15 -0
- package/dist/bot-KJ26BG56.js.map +1 -0
- package/dist/charts-MMXM6BWW.js +241 -0
- package/dist/charts-MMXM6BWW.js.map +1 -0
- package/dist/chunk-4LVWXUNC.js +1079 -0
- package/dist/chunk-4LVWXUNC.js.map +1 -0
- package/dist/chunk-4TG2IG5K.js +5249 -0
- package/dist/chunk-4TG2IG5K.js.map +1 -0
- package/dist/chunk-6DRDKB45.js +251 -0
- package/dist/chunk-6DRDKB45.js.map +1 -0
- package/dist/chunk-6SNHU3CY.js +123 -0
- package/dist/chunk-6SNHU3CY.js.map +1 -0
- package/dist/chunk-CI6Q63MM.js +1613 -0
- package/dist/chunk-CI6Q63MM.js.map +1 -0
- package/dist/chunk-CQ4JURG7.js +57 -0
- package/dist/chunk-CQ4JURG7.js.map +1 -0
- package/dist/chunk-F6QUZQGI.js +51 -0
- package/dist/chunk-F6QUZQGI.js.map +1 -0
- package/dist/chunk-GK3E2I7A.js +216 -0
- package/dist/chunk-GK3E2I7A.js.map +1 -0
- package/dist/chunk-GUBEEYDW.js +211 -0
- package/dist/chunk-GUBEEYDW.js.map +1 -0
- package/dist/chunk-GVJVEWHI.js +29 -0
- package/dist/chunk-GVJVEWHI.js.map +1 -0
- package/dist/chunk-HH2HBTQM.js +806 -0
- package/dist/chunk-HH2HBTQM.js.map +1 -0
- package/dist/chunk-JXUP2X7V.js +129 -0
- package/dist/chunk-JXUP2X7V.js.map +1 -0
- package/dist/chunk-KHNYJY2Z.js +178 -0
- package/dist/chunk-KHNYJY2Z.js.map +1 -0
- package/dist/chunk-L3F43VPB.js +652 -0
- package/dist/chunk-L3F43VPB.js.map +1 -0
- package/dist/chunk-L3PDU3XN.js +803 -0
- package/dist/chunk-L3PDU3XN.js.map +1 -0
- package/dist/chunk-NSBPE2FW.js +17 -0
- package/dist/chunk-NSBPE2FW.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +52 -0
- package/dist/cli.js.map +1 -0
- package/dist/commands/setup.d.ts +9 -0
- package/dist/commands/setup.js +374 -0
- package/dist/commands/setup.js.map +1 -0
- package/dist/commands/start.d.ts +8 -0
- package/dist/commands/start.js +27 -0
- package/dist/commands/start.js.map +1 -0
- package/dist/commands/status.d.ts +8 -0
- package/dist/commands/status.js +57 -0
- package/dist/commands/status.js.map +1 -0
- package/dist/commands/stop.d.ts +8 -0
- package/dist/commands/stop.js +37 -0
- package/dist/commands/stop.js.map +1 -0
- package/dist/commands/utils.d.ts +50 -0
- package/dist/commands/utils.js +36 -0
- package/dist/commands/utils.js.map +1 -0
- package/dist/discord-ZOJFTVTB.js +49 -0
- package/dist/discord-ZOJFTVTB.js.map +1 -0
- package/dist/imessage-JFRB6EJ7.js +14 -0
- package/dist/imessage-JFRB6EJ7.js.map +1 -0
- package/dist/lib.d.ts +855 -0
- package/dist/lib.js +274 -0
- package/dist/lib.js.map +1 -0
- package/dist/mcp-LS7Q3Z5W.js +30 -0
- package/dist/mcp-LS7Q3Z5W.js.map +1 -0
- package/dist/scheduler-EZ7CZMCS.js +42 -0
- package/dist/scheduler-EZ7CZMCS.js.map +1 -0
- package/dist/signal-T3MCSULM.js +14 -0
- package/dist/signal-T3MCSULM.js.map +1 -0
- package/dist/slack-N2M4FHAJ.js +54 -0
- package/dist/slack-N2M4FHAJ.js.map +1 -0
- package/dist/src-K7GASHRH.js +430 -0
- package/dist/src-K7GASHRH.js.map +1 -0
- package/dist/tools-24GZHYRF.js +16 -0
- package/dist/tools-24GZHYRF.js.map +1 -0
- package/dist/whatsapp-VCRUPAO5.js +14 -0
- package/dist/whatsapp-VCRUPAO5.js.map +1 -0
- package/drizzle/0000_chilly_shinobi_shaw.sql +75 -0
- package/drizzle/0001_freezing_shape.sql +274 -0
- package/drizzle/meta/0000_snapshot.json +529 -0
- package/drizzle/meta/0001_snapshot.json +2576 -0
- package/drizzle/meta/_journal.json +20 -0
- package/package.json +98 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tools/shell.ts","../src/tools/files.ts","../src/tools/browser.ts","../src/tools/web-search.ts","../src/tools/image-analysis.ts","../src/config/env.ts","../src/tools/ocr.ts","../src/tools/screenshot.ts","../src/tools/file-generation/pdf.ts","../src/tools/file-generation/spreadsheet.ts","../src/tools/file-generation/diagrams.ts","../src/db/index.ts","../src/db/schema.ts","../src/core/agents/agent-manager.ts","../src/core/security/audit-logger.ts","../src/core/observability/metrics.ts","../src/tools/rendering/math-renderer.ts","../src/tools/rendering/code-highlighter.ts","../src/tools/rendering/markdown-renderer.ts","../src/tools/video-summarization.ts","../src/tools/patch.ts","../src/core/polls.ts","../src/core/skills/skill-registry.ts","../src/core/skills/skill-executor.ts","../src/core/hub/builtin-skills.ts","../src/core/hub/index.ts","../src/tools/index.ts"],"sourcesContent":["import { spawn } from \"child_process\";\nimport { getShellConfig, isWindows } from \"../utils/platform\";\n\n// Commands that are always allowed (Unix)\nconst ALLOWED_COMMANDS_UNIX = new Set([\n \"ls\",\n \"pwd\",\n \"cat\",\n \"head\",\n \"tail\",\n \"grep\",\n \"find\",\n \"wc\",\n \"sort\",\n \"uniq\",\n \"echo\",\n \"date\",\n \"whoami\",\n \"hostname\",\n \"uname\",\n \"df\",\n \"du\",\n \"free\",\n \"uptime\",\n \"ps\",\n \"top\",\n \"htop\",\n \"which\",\n \"whereis\",\n \"file\",\n \"stat\",\n \"md5sum\",\n \"sha256sum\",\n \"curl\",\n \"wget\",\n \"ping\",\n \"dig\",\n \"nslookup\",\n \"git\",\n \"npm\",\n \"bun\",\n \"node\",\n \"python\",\n \"python3\",\n \"pip\",\n \"pip3\",\n \"docker\",\n \"docker-compose\",\n \"mkdir\",\n \"cp\",\n \"mv\",\n \"touch\",\n \"tar\",\n \"gzip\",\n \"gunzip\",\n \"zip\",\n \"unzip\",\n \"ssh\",\n \"scp\",\n \"rsync\",\n]);\n\n// Commands that are always allowed (Windows)\nconst ALLOWED_COMMANDS_WINDOWS = new Set([\n \"dir\",\n \"cd\",\n \"type\",\n \"more\",\n \"find\",\n \"findstr\",\n \"sort\",\n \"echo\",\n \"date\",\n \"time\",\n \"whoami\",\n \"hostname\",\n \"systeminfo\",\n \"tasklist\",\n \"where\",\n \"curl\",\n \"ping\",\n \"nslookup\",\n \"ipconfig\",\n \"netstat\",\n \"git\",\n \"npm\",\n \"bun\",\n \"node\",\n \"python\",\n \"pip\",\n \"docker\",\n \"docker-compose\",\n \"mkdir\",\n \"copy\",\n \"xcopy\",\n \"move\",\n \"ren\",\n \"tar\",\n \"powershell\",\n \"pwsh\",\n // PowerShell cmdlets\n \"Get-ChildItem\",\n \"Get-Content\",\n \"Set-Location\",\n \"Get-Location\",\n \"Get-Date\",\n \"Get-Process\",\n \"Get-Service\",\n \"Test-Path\",\n \"New-Item\",\n \"Copy-Item\",\n \"Move-Item\",\n \"Remove-Item\",\n \"Invoke-WebRequest\",\n \"Invoke-RestMethod\",\n]);\n\n// Commands that are blocked (Unix)\nconst BLOCKED_COMMANDS_UNIX = new Set([\n \"rm\",\n \"rmdir\",\n \"dd\",\n \"mkfs\",\n \"fdisk\",\n \"parted\",\n \"shutdown\",\n \"reboot\",\n \"halt\",\n \"poweroff\",\n \"init\",\n \"kill\",\n \"killall\",\n \"pkill\",\n \":(){\",\n \"fork\",\n \"chmod\",\n \"chown\",\n \"passwd\",\n \"useradd\",\n \"userdel\",\n \"usermod\",\n \"groupadd\",\n \"su \",\n \"sudo\",\n]);\n\n// Commands that are blocked (Windows)\nconst BLOCKED_COMMANDS_WINDOWS = new Set([\n \"del\",\n \"erase\",\n \"rmdir\",\n \"rd\",\n \"format\",\n \"diskpart\",\n \"shutdown\",\n \"taskkill\",\n \"reg\",\n \"regedit\",\n \"net user\",\n \"net localgroup\",\n \"runas\",\n \"bcdedit\",\n \"bootrec\",\n \"sfc\",\n \"dism\",\n // PowerShell dangerous cmdlets\n \"Remove-Item -Recurse\",\n \"Format-Volume\",\n \"Stop-Process\",\n \"Stop-Computer\",\n \"Restart-Computer\",\n]);\n\nexport interface ShellResult {\n success: boolean;\n stdout: string;\n stderr: string;\n exitCode: number;\n command: string;\n durationMs: number;\n platform: string;\n}\n\nfunction isCommandAllowed(command: string): { allowed: boolean; reason?: string } {\n const trimmed = command.trim();\n const blockedCommands = isWindows ? BLOCKED_COMMANDS_WINDOWS : BLOCKED_COMMANDS_UNIX;\n\n // Check for blocked commands\n for (const blocked of blockedCommands) {\n if (trimmed.toLowerCase().includes(blocked.toLowerCase())) {\n return { allowed: false, reason: `Command contains blocked keyword: ${blocked}` };\n }\n }\n\n // Check for dangerous patterns (Unix)\n if (!isWindows) {\n if (trimmed.includes(\">\") && trimmed.includes(\"/etc\")) {\n return { allowed: false, reason: \"Cannot write to /etc directory\" };\n }\n if (trimmed.includes(\"sudo\")) {\n return { allowed: false, reason: \"sudo commands are not allowed\" };\n }\n }\n\n // Check for dangerous patterns (Windows)\n if (isWindows) {\n // Block writing to system directories\n if (\n trimmed.toLowerCase().includes(\"c:\\\\windows\") ||\n trimmed.toLowerCase().includes(\"c:\\\\program files\")\n ) {\n const hasWriteOp =\n trimmed.includes(\">\") ||\n trimmed.toLowerCase().includes(\"copy\") ||\n trimmed.toLowerCase().includes(\"move\");\n if (hasWriteOp) {\n return { allowed: false, reason: \"Cannot write to system directories\" };\n }\n }\n // Block registry modifications\n if (trimmed.toLowerCase().includes(\"hkey_\")) {\n return { allowed: false, reason: \"Registry modifications are not allowed\" };\n }\n }\n\n return { allowed: true };\n}\n\nexport async function executeCommand(\n command: string,\n cwd?: string,\n timeout = 30000\n): Promise<ShellResult> {\n const startTime = Date.now();\n const platformName = isWindows ? \"windows\" : \"unix\";\n\n // Validate command\n const validation = isCommandAllowed(command);\n if (!validation.allowed) {\n return {\n success: false,\n stdout: \"\",\n stderr: validation.reason || \"Command not allowed\",\n exitCode: 1,\n command,\n durationMs: Date.now() - startTime,\n platform: platformName,\n };\n }\n\n const { shell, args } = getShellConfig();\n\n return new Promise((resolve) => {\n const proc = spawn(shell, [...args, command], {\n cwd: cwd || process.cwd(),\n timeout,\n env: {\n ...process.env,\n HOME: process.env.HOME,\n USERPROFILE: process.env.USERPROFILE,\n },\n // Windows-specific options\n ...(isWindows && { windowsHide: true }),\n });\n\n let stdout = \"\";\n let stderr = \"\";\n\n proc.stdout.on(\"data\", (data) => {\n stdout += data.toString();\n });\n\n proc.stderr.on(\"data\", (data) => {\n stderr += data.toString();\n });\n\n proc.on(\"close\", (code) => {\n resolve({\n success: code === 0,\n stdout: stdout.slice(0, 10000), // Limit output size\n stderr: stderr.slice(0, 2000),\n exitCode: code || 0,\n command,\n durationMs: Date.now() - startTime,\n platform: platformName,\n });\n });\n\n proc.on(\"error\", (err) => {\n resolve({\n success: false,\n stdout: \"\",\n stderr: err.message,\n exitCode: 1,\n command,\n durationMs: Date.now() - startTime,\n platform: platformName,\n });\n });\n });\n}\n\n// Helper to check if a command would work on the current platform\nexport function isCommandAvailable(command: string): boolean {\n const firstWord = command.trim().split(/\\s+/)[0].toLowerCase();\n const allowedCommands = isWindows ? ALLOWED_COMMANDS_WINDOWS : ALLOWED_COMMANDS_UNIX;\n return allowedCommands.has(firstWord);\n}\n\n// Get platform-appropriate command equivalents\nexport function getPlatformCommand(unixCommand: string): string {\n if (!isWindows) return unixCommand;\n\n // Map common Unix commands to Windows equivalents\n const commandMap: Record<string, string> = {\n ls: \"dir\",\n cat: \"type\",\n pwd: \"cd\",\n cp: \"copy\",\n mv: \"move\",\n rm: \"del\",\n clear: \"cls\",\n grep: \"findstr\",\n touch: \"type nul >\",\n };\n\n const firstWord = unixCommand.trim().split(/\\s+/)[0];\n if (commandMap[firstWord]) {\n return unixCommand.replace(firstWord, commandMap[firstWord]);\n }\n\n return unixCommand;\n}\n","import { readdir, readFile, writeFile, stat, mkdir } from \"fs/promises\";\nimport { join, resolve, dirname } from \"path\";\nimport { glob } from \"glob\";\n\n// Allowed base directories for file operations\nconst ALLOWED_PATHS = [\n process.env.HOME || \"/home\",\n \"/tmp\",\n];\n\nfunction isPathAllowed(filePath: string): boolean {\n const resolved = resolve(filePath);\n return ALLOWED_PATHS.some((base) => resolved.startsWith(base));\n}\n\nexport interface FileInfo {\n name: string;\n path: string;\n isDirectory: boolean;\n size: number;\n modified: Date;\n}\n\nexport async function listDirectory(dirPath: string): Promise<FileInfo[]> {\n if (!isPathAllowed(dirPath)) {\n throw new Error(`Access denied: ${dirPath} is outside allowed directories`);\n }\n\n const entries = await readdir(dirPath, { withFileTypes: true });\n const files: FileInfo[] = [];\n\n for (const entry of entries) {\n const fullPath = join(dirPath, entry.name);\n try {\n const stats = await stat(fullPath);\n files.push({\n name: entry.name,\n path: fullPath,\n isDirectory: entry.isDirectory(),\n size: stats.size,\n modified: stats.mtime,\n });\n } catch {\n // Skip files we can't stat\n }\n }\n\n return files;\n}\n\nexport async function readFileContent(\n filePath: string,\n maxSize = 100000\n): Promise<string> {\n if (!isPathAllowed(filePath)) {\n throw new Error(`Access denied: ${filePath} is outside allowed directories`);\n }\n\n const stats = await stat(filePath);\n if (stats.size > maxSize) {\n throw new Error(\n `File too large: ${stats.size} bytes (max: ${maxSize} bytes)`\n );\n }\n\n return readFile(filePath, \"utf-8\");\n}\n\nexport async function writeFileContent(\n filePath: string,\n content: string\n): Promise<void> {\n if (!isPathAllowed(filePath)) {\n throw new Error(`Access denied: ${filePath} is outside allowed directories`);\n }\n\n // Create directory if it doesn't exist\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, content, \"utf-8\");\n}\n\nexport async function searchFiles(\n pattern: string,\n basePath?: string\n): Promise<string[]> {\n const searchBase = basePath || process.env.HOME || \"/home\";\n\n if (!isPathAllowed(searchBase)) {\n throw new Error(\n `Access denied: ${searchBase} is outside allowed directories`\n );\n }\n\n const files = await glob(pattern, {\n cwd: searchBase,\n absolute: true,\n nodir: false,\n ignore: [\"**/node_modules/**\", \"**/.git/**\"],\n });\n\n return files.slice(0, 100); // Limit results\n}\n\nexport async function getFileInfo(filePath: string): Promise<FileInfo> {\n if (!isPathAllowed(filePath)) {\n throw new Error(`Access denied: ${filePath} is outside allowed directories`);\n }\n\n const stats = await stat(filePath);\n return {\n name: filePath.split(\"/\").pop() || \"\",\n path: filePath,\n isDirectory: stats.isDirectory(),\n size: stats.size,\n modified: stats.mtime,\n };\n}\n","import { chromium, type Browser, type Page } from \"playwright\";\n\nlet browser: Browser | null = null;\nlet page: Page | null = null;\n\nexport async function getBrowser(): Promise<Browser> {\n if (!browser) {\n browser = await chromium.launch({\n headless: true,\n args: [\"--no-sandbox\", \"--disable-setuid-sandbox\"],\n });\n }\n return browser;\n}\n\nexport async function getPage(): Promise<Page> {\n const b = await getBrowser();\n if (!page || page.isClosed()) {\n page = await b.newPage();\n await page.setViewportSize({ width: 1280, height: 720 });\n }\n return page;\n}\n\nexport async function closeBrowser(): Promise<void> {\n if (page) {\n await page.close();\n page = null;\n }\n if (browser) {\n await browser.close();\n browser = null;\n }\n}\n\nexport interface BrowseResult {\n url: string;\n title: string;\n content: string;\n screenshot?: string; // Base64 encoded\n}\n\nexport async function navigateTo(url: string): Promise<BrowseResult> {\n const p = await getPage();\n\n await p.goto(url, { waitUntil: \"domcontentloaded\", timeout: 30000 });\n\n const title = await p.title();\n const content = await p.evaluate(() => {\n // Get main text content, removing scripts and styles\n const clone = document.body.cloneNode(true) as HTMLElement;\n clone.querySelectorAll(\"script, style, nav, footer, header\").forEach((el) => el.remove());\n return clone.innerText.slice(0, 5000);\n });\n\n return { url: p.url(), title, content };\n}\n\nexport async function takeScreenshot(): Promise<string> {\n const p = await getPage();\n const buffer = await p.screenshot({ type: \"png\" });\n return buffer.toString(\"base64\");\n}\n\nexport async function clickElement(selector: string): Promise<void> {\n const p = await getPage();\n await p.click(selector, { timeout: 5000 });\n}\n\nexport async function typeText(selector: string, text: string): Promise<void> {\n const p = await getPage();\n await p.fill(selector, text);\n}\n\nexport async function extractText(selector: string): Promise<string> {\n const p = await getPage();\n return p.textContent(selector) || \"\";\n}\n\nexport async function searchGoogle(query: string): Promise<BrowseResult> {\n const encodedQuery = encodeURIComponent(query);\n return navigateTo(`https://www.google.com/search?q=${encodedQuery}`);\n}\n\nexport async function extractLinks(): Promise<Array<{ text: string; href: string }>> {\n const p = await getPage();\n return p.evaluate(() => {\n const links: Array<{ text: string; href: string }> = [];\n document.querySelectorAll(\"a[href]\").forEach((a) => {\n const href = a.getAttribute(\"href\");\n const text = a.textContent?.trim();\n if (href && text && href.startsWith(\"http\")) {\n links.push({ text: text.slice(0, 100), href });\n }\n });\n return links.slice(0, 20);\n });\n}\n","import { navigateTo, extractLinks, type BrowseResult } from \"./browser\";\n\nexport interface SearchResult {\n title: string;\n url: string;\n snippet: string;\n}\n\n// Simple web search using DuckDuckGo HTML (no API key needed)\nexport async function webSearch(query: string): Promise<SearchResult[]> {\n const encodedQuery = encodeURIComponent(query);\n const result = await navigateTo(\n `https://html.duckduckgo.com/html/?q=${encodedQuery}`\n );\n\n // Parse DuckDuckGo results from page content\n const results: SearchResult[] = [];\n const lines = result.content.split(\"\\n\");\n\n let currentResult: Partial<SearchResult> = {};\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length > 10 && !trimmed.startsWith(\"DuckDuckGo\")) {\n if (!currentResult.title) {\n currentResult.title = trimmed.slice(0, 100);\n } else if (!currentResult.snippet) {\n currentResult.snippet = trimmed.slice(0, 200);\n if (currentResult.title && currentResult.snippet) {\n results.push({\n title: currentResult.title,\n url: \"\",\n snippet: currentResult.snippet,\n });\n currentResult = {};\n if (results.length >= 5) break;\n }\n }\n }\n }\n\n return results;\n}\n\n// Fetch and summarize a webpage\nexport async function fetchAndSummarize(url: string): Promise<string> {\n const result = await navigateTo(url);\n return `Title: ${result.title}\\n\\nContent:\\n${result.content}`;\n}\n\n// Research a topic by searching and reading top results\nexport async function research(\n query: string,\n maxPages = 3\n): Promise<{ query: string; findings: string[] }> {\n const searchResults = await webSearch(query);\n const findings: string[] = [];\n\n for (let i = 0; i < Math.min(maxPages, searchResults.length); i++) {\n const result = searchResults[i];\n if (result.url) {\n try {\n const content = await fetchAndSummarize(result.url);\n findings.push(`Source: ${result.title}\\n${content.slice(0, 1000)}`);\n } catch (error) {\n findings.push(`Source: ${result.title}\\n${result.snippet}`);\n }\n } else {\n findings.push(`${result.title}: ${result.snippet}`);\n }\n }\n\n return { query, findings };\n}\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport { env } from \"../config/env\";\nimport { readFile } from \"fs/promises\";\nimport { isPathAllowed } from \"../utils/paths\";\n\nconst anthropic = new Anthropic({\n apiKey: env.CLAUDE_API_KEY,\n});\n\nexport interface ImageAnalysisResult {\n success: boolean;\n analysis?: string;\n error?: string;\n}\n\n// Supported image MIME types\nconst SUPPORTED_TYPES: Record<string, string> = {\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".png\": \"image/png\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n};\n\nfunction getMimeType(filename: string): string | null {\n const ext = filename.toLowerCase().slice(filename.lastIndexOf(\".\"));\n return SUPPORTED_TYPES[ext] || null;\n}\n\n// Analyze image from URL\nexport async function analyzeImageUrl(\n imageUrl: string,\n prompt: string\n): Promise<ImageAnalysisResult> {\n try {\n const response = await anthropic.messages.create({\n model: \"claude-sonnet-4-20250514\",\n max_tokens: 1024,\n messages: [\n {\n role: \"user\",\n content: [\n {\n type: \"image\",\n source: {\n type: \"url\",\n url: imageUrl,\n },\n },\n {\n type: \"text\",\n text: prompt || \"Describe this image in detail.\",\n },\n ],\n },\n ],\n });\n\n const textContent = response.content.find((c) => c.type === \"text\");\n return {\n success: true,\n analysis: textContent?.type === \"text\" ? textContent.text : undefined,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n// Analyze image from local file\nexport async function analyzeImageFile(\n filePath: string,\n prompt: string\n): Promise<ImageAnalysisResult> {\n try {\n // Security check\n if (!isPathAllowed(filePath)) {\n return {\n success: false,\n error: \"Access to this path is not allowed\",\n };\n }\n\n const mimeType = getMimeType(filePath);\n if (!mimeType) {\n return {\n success: false,\n error: \"Unsupported image format. Supported: jpg, png, gif, webp\",\n };\n }\n\n const imageData = await readFile(filePath);\n const base64 = imageData.toString(\"base64\");\n\n const response = await anthropic.messages.create({\n model: \"claude-sonnet-4-20250514\",\n max_tokens: 1024,\n messages: [\n {\n role: \"user\",\n content: [\n {\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: mimeType as \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\",\n data: base64,\n },\n },\n {\n type: \"text\",\n text: prompt || \"Describe this image in detail.\",\n },\n ],\n },\n ],\n });\n\n const textContent = response.content.find((c) => c.type === \"text\");\n return {\n success: true,\n analysis: textContent?.type === \"text\" ? textContent.text : undefined,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n// Analyze image from buffer\nexport async function analyzeImageBuffer(\n imageBuffer: Buffer,\n mimeType: \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\",\n prompt: string\n): Promise<ImageAnalysisResult> {\n try {\n const base64 = imageBuffer.toString(\"base64\");\n\n const response = await anthropic.messages.create({\n model: \"claude-sonnet-4-20250514\",\n max_tokens: 1024,\n messages: [\n {\n role: \"user\",\n content: [\n {\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: mimeType,\n data: base64,\n },\n },\n {\n type: \"text\",\n text: prompt || \"Describe this image in detail.\",\n },\n ],\n },\n ],\n });\n\n const textContent = response.content.find((c) => c.type === \"text\");\n return {\n success: true,\n analysis: textContent?.type === \"text\" ? textContent.text : undefined,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n// Combined function for tool use\nexport async function analyzeImage(\n options: {\n imageUrl?: string;\n imagePath?: string;\n prompt: string;\n }\n): Promise<ImageAnalysisResult> {\n if (options.imageUrl) {\n return analyzeImageUrl(options.imageUrl, options.prompt);\n }\n\n if (options.imagePath) {\n return analyzeImageFile(options.imagePath, options.prompt);\n }\n\n return {\n success: false,\n error: \"Either imageUrl or imagePath must be provided\",\n };\n}\n\nexport default {\n analyzeImage,\n analyzeImageUrl,\n analyzeImageFile,\n analyzeImageBuffer,\n};\n","import { z } from \"zod\";\n\nconst envSchema = z.object({\n // Claude API\n CLAUDE_API_KEY: z.string().min(1, \"CLAUDE_API_KEY is required\"),\n\n // Telegram\n TELEGRAM_BOT_TOKEN: z.string().optional().default(\"\"),\n TELEGRAM_CHAT_ID: z.string().optional().default(\"\"),\n\n // OpenAI (Whisper STT)\n OPENAI_API_KEY: z.string().optional().default(\"\"),\n\n // ElevenLabs TTS\n ELEVENLABS_API_KEY: z.string().optional().default(\"\"),\n ELEVENLABS_VOICE_ID: z.string().optional().default(\"\"),\n\n // Database\n DATABASE_URL: z\n .string()\n .default(\"postgresql://sentinel:sentinel@localhost:5432/sentinel\"),\n\n // Redis\n REDIS_URL: z.string().default(\"redis://localhost:6379\"),\n\n // Discord (optional)\n DISCORD_BOT_TOKEN: z.string().optional(),\n DISCORD_CLIENT_ID: z.string().optional(),\n DISCORD_GUILD_ID: z.string().optional(),\n DISCORD_ALLOWED_USER_IDS: z.string().optional(), // Comma-separated list\n DISCORD_ALLOWED_ROLE_IDS: z.string().optional(), // Comma-separated list\n\n // Slack (optional)\n SLACK_BOT_TOKEN: z.string().optional(),\n SLACK_SIGNING_SECRET: z.string().optional(),\n SLACK_APP_TOKEN: z.string().optional(),\n SLACK_SOCKET_MODE: z.coerce.boolean().optional().default(false),\n SLACK_PORT: z.coerce.number().optional().default(3000),\n SLACK_ALLOWED_USER_IDS: z.string().optional(), // Comma-separated list\n SLACK_ALLOWED_CHANNEL_IDS: z.string().optional(), // Comma-separated list\n\n // Notion (optional)\n NOTION_API_KEY: z.string().optional(),\n NOTION_ROOT_PAGE_ID: z.string().optional(),\n\n // Email (optional)\n EMAIL_IMAP_HOST: z.string().optional(),\n EMAIL_IMAP_PORT: z.coerce.number().optional().default(993),\n EMAIL_IMAP_SECURE: z.coerce.boolean().optional().default(true),\n EMAIL_SMTP_HOST: z.string().optional(),\n EMAIL_SMTP_PORT: z.coerce.number().optional().default(587),\n EMAIL_SMTP_SECURE: z.coerce.boolean().optional().default(false),\n EMAIL_USER: z.string().optional(),\n EMAIL_PASSWORD: z.string().optional(),\n EMAIL_PROVIDER: z.enum([\"gmail\", \"outlook\", \"yahoo\", \"custom\"]).optional(),\n\n // GitHub (optional)\n GITHUB_TOKEN: z.string().optional(),\n GITHUB_WEBHOOK_SECRET: z.string().optional(),\n\n // Google Drive (optional)\n GOOGLE_DRIVE_CLIENT_ID: z.string().optional(),\n GOOGLE_DRIVE_CLIENT_SECRET: z.string().optional(),\n GOOGLE_DRIVE_REDIRECT_URI: z.string().optional(),\n GOOGLE_DRIVE_REFRESH_TOKEN: z.string().optional(),\n\n // Dropbox (optional)\n DROPBOX_APP_KEY: z.string().optional(),\n DROPBOX_APP_SECRET: z.string().optional(),\n DROPBOX_ACCESS_TOKEN: z.string().optional(),\n DROPBOX_REFRESH_TOKEN: z.string().optional(),\n\n // Finance (optional)\n ALPHA_VANTAGE_API_KEY: z.string().optional(),\n\n // Optional\n HUGGINGFACE_ACCESS_TOKEN: z.string().optional(),\n TWILIO_ACCOUNT_SID: z.string().optional(),\n TWILIO_AUTH_TOKEN: z.string().optional(),\n TWILIO_PHONE_NUMBER: z.string().optional(),\n\n // Home Assistant (optional)\n HOME_ASSISTANT_URL: z.string().url().optional(),\n HOME_ASSISTANT_TOKEN: z.string().optional(),\n\n // Spotify (optional)\n SPOTIFY_CLIENT_ID: z.string().optional(),\n SPOTIFY_CLIENT_SECRET: z.string().optional(),\n SPOTIFY_REDIRECT_URI: z.string().url().optional(),\n\n // MCP (Model Context Protocol)\n MCP_ENABLED: z.coerce.boolean().optional().default(true),\n MCP_CONFIG_PATH: z.string().optional().default(\"./mcp.json\"),\n\n // WhatsApp (optional)\n WHATSAPP_ENABLED: z.coerce.boolean().optional().default(false),\n WHATSAPP_AUTH_DIR: z.string().optional().default(\"./whatsapp-auth\"),\n WHATSAPP_ALLOWED_NUMBERS: z.string().optional(), // Comma-separated\n\n // Signal (optional)\n SIGNAL_ENABLED: z.coerce.boolean().optional().default(false),\n SIGNAL_PHONE_NUMBER: z.string().optional(),\n SIGNAL_CLI_PATH: z.string().optional().default(\"signal-cli\"),\n SIGNAL_ALLOWED_NUMBERS: z.string().optional(), // Comma-separated\n\n // iMessage (optional, macOS only)\n IMESSAGE_ENABLED: z.coerce.boolean().optional().default(false),\n IMESSAGE_MODE: z.enum([\"bluebubbles\", \"applescript\"]).optional().default(\"applescript\"),\n IMESSAGE_BLUEBUBBLES_URL: z.string().optional(),\n IMESSAGE_BLUEBUBBLES_PASSWORD: z.string().optional(),\n IMESSAGE_ALLOWED_NUMBERS: z.string().optional(), // Comma-separated\n\n // Server\n PORT: z.coerce.number().default(8030),\n NODE_ENV: z.enum([\"development\", \"production\", \"test\"]).default(\"development\"),\n});\n\nexport type Env = z.infer<typeof envSchema>;\n\n// Internal mutable store\nlet _env: Env | null = null;\n\n/**\n * Programmatic configuration for library use.\n * Call this before any module accesses `env`.\n * Config values are merged with process.env (config takes precedence).\n */\nexport function configure(config: Partial<Env> & { CLAUDE_API_KEY: string }): Env {\n const merged = { ...process.env, ...config };\n const result = envSchema.safeParse(merged);\n\n if (!result.success) {\n const errors = result.error.errors.map(\n (e) => `${e.path.join(\".\")}: ${e.message}`\n );\n throw new Error(\n `OpenSentinel configuration validation failed:\\n ${errors.join(\"\\n \")}`\n );\n }\n\n _env = result.data;\n return _env;\n}\n\n/**\n * Load config from process.env.\n * Called lazily on first access if configure() was not called.\n *\n * When used as a library, env vars may not be set at import time\n * (module-level singletons trigger this during static initialization).\n * In that case, we populate with defaults and partial values rather\n * than throwing — services will fail with clear errors when actually used.\n */\nfunction loadFromProcessEnv(): Env {\n const result = envSchema.safeParse(process.env);\n\n if (!result.success) {\n // If running as CLI (not library), throw so the user sees the error immediately\n if (process.env.__OPENSENTINEL_CLI__) {\n const errors = result.error.errors.map(\n (e) => `${e.path.join(\".\")}: ${e.message}`\n );\n throw new Error(\n `Environment validation failed:\\n ${errors.join(\"\\n \")}`\n );\n }\n\n // For library use: populate with whatever we have, fill missing with defaults\n // Services will fail individually when they try to use undefined API keys\n const lenientSchema = envSchema.extend({\n CLAUDE_API_KEY: z.string().default(\"\"),\n });\n const lenientResult = lenientSchema.safeParse(process.env);\n _env = (lenientResult.success ? lenientResult.data : {}) as Env;\n return _env;\n }\n\n _env = result.data;\n return _env;\n}\n\n/**\n * The env accessor. Lazy — loads from process.env on first access\n * if configure() was not called first.\n *\n * All 37+ consumer files keep using `env.SOME_PROP` unchanged.\n */\nexport const env: Env = new Proxy({} as Env, {\n get(_target, prop: string) {\n if (!_env) {\n loadFromProcessEnv();\n }\n return (_env as any)[prop];\n },\n has(_target, prop: string) {\n if (!_env) {\n loadFromProcessEnv();\n }\n return prop in (_env as any);\n },\n ownKeys() {\n if (!_env) {\n loadFromProcessEnv();\n }\n return Reflect.ownKeys(_env as any);\n },\n getOwnPropertyDescriptor(_target, prop) {\n if (!_env) {\n loadFromProcessEnv();\n }\n return Object.getOwnPropertyDescriptor(_env as any, prop);\n },\n});\n","import { readFile } from \"fs/promises\";\nimport { isPathAllowed } from \"../utils/paths\";\nimport { analyzeImageFile } from \"./image-analysis\";\n\nexport interface OCRResult {\n success: boolean;\n text?: string;\n confidence?: number;\n error?: string;\n}\n\n// Use Claude Vision for OCR (most reliable for complex documents)\nexport async function ocrWithVision(\n filePath: string,\n language?: string\n): Promise<OCRResult> {\n const prompt = language\n ? `Extract all text from this image. The text is in ${language}. Return only the extracted text, preserving the original formatting and layout as much as possible.`\n : `Extract all text from this image. Return only the extracted text, preserving the original formatting and layout as much as possible.`;\n\n const result = await analyzeImageFile(filePath, prompt);\n\n if (result.success && result.analysis) {\n return {\n success: true,\n text: result.analysis,\n };\n }\n\n return {\n success: false,\n error: result.error || \"Failed to extract text\",\n };\n}\n\n// Simple OCR fallback using pattern matching (for testing without external deps)\n// In production, this would use Tesseract.js\nexport async function ocrSimple(filePath: string): Promise<OCRResult> {\n // This is a placeholder - real implementation would use Tesseract.js\n // For now, fall back to Vision API\n return ocrWithVision(filePath);\n}\n\n// OCR for PDF files (extract text from each page)\nexport async function ocrPdf(\n filePath: string,\n pages?: string // e.g., \"1-5\" or \"1,3,5\"\n): Promise<OCRResult> {\n // For PDFs, we'll use Claude Vision on the file directly\n const prompt = `Extract all text from this PDF document. Return the text content, preserving the structure and formatting as much as possible. If there are multiple pages, separate them clearly.`;\n\n const result = await analyzeImageFile(filePath, prompt);\n\n if (result.success && result.analysis) {\n return {\n success: true,\n text: result.analysis,\n };\n }\n\n return {\n success: false,\n error: result.error || \"Failed to extract text from PDF\",\n };\n}\n\n// Main OCR function that determines the best approach\nexport async function performOCR(\n filePath: string,\n options?: {\n language?: string;\n useVision?: boolean;\n }\n): Promise<OCRResult> {\n // Security check\n if (!isPathAllowed(filePath)) {\n return {\n success: false,\n error: \"Access to this path is not allowed\",\n };\n }\n\n const ext = filePath.toLowerCase().slice(filePath.lastIndexOf(\".\"));\n\n // PDF handling\n if (ext === \".pdf\") {\n return ocrPdf(filePath);\n }\n\n // Image handling - use Vision API (most accurate)\n if ([\".jpg\", \".jpeg\", \".png\", \".gif\", \".webp\", \".bmp\", \".tiff\"].includes(ext)) {\n if (options?.useVision !== false) {\n return ocrWithVision(filePath, options?.language);\n }\n return ocrSimple(filePath);\n }\n\n return {\n success: false,\n error: `Unsupported file type: ${ext}`,\n };\n}\n\n// Extract structured data from document (tables, forms)\nexport async function extractStructuredData(\n filePath: string,\n dataType?: \"table\" | \"form\" | \"receipt\" | \"invoice\"\n): Promise<{\n success: boolean;\n data?: Record<string, unknown>;\n error?: string;\n}> {\n const prompts: Record<string, string> = {\n table: `Extract all tables from this image. Return the data as JSON arrays where each table is an array of rows, and each row is an array of cell values.`,\n form: `Extract all form fields from this image. Return as a JSON object where keys are field labels and values are the filled-in content.`,\n receipt: `Extract receipt information from this image. Return as JSON with: store_name, date, items (array with name, quantity, price), subtotal, tax, total.`,\n invoice: `Extract invoice information from this image. Return as JSON with: vendor, invoice_number, date, due_date, line_items (array), subtotal, tax, total, billing_address.`,\n };\n\n const prompt = dataType\n ? prompts[dataType]\n : `Extract any structured data from this image. Return as JSON.`;\n\n const result = await analyzeImageFile(filePath, prompt);\n\n if (result.success && result.analysis) {\n try {\n // Try to parse as JSON\n const jsonMatch = result.analysis.match(/```json\\n?([\\s\\S]*?)\\n?```/);\n if (jsonMatch) {\n return {\n success: true,\n data: JSON.parse(jsonMatch[1]),\n };\n }\n\n // Try direct parse\n const data = JSON.parse(result.analysis);\n return { success: true, data };\n } catch {\n // Return raw text if not JSON\n return {\n success: true,\n data: { rawText: result.analysis },\n };\n }\n }\n\n return {\n success: false,\n error: result.error || \"Failed to extract structured data\",\n };\n}\n\nexport default {\n performOCR,\n ocrWithVision,\n extractStructuredData,\n};\n","import { exec } from \"child_process\";\nimport { promisify } from \"util\";\nimport { writeFile, unlink } from \"fs/promises\";\nimport { join } from \"path\";\nimport { tmpdir } from \"os\";\nimport { randomBytes } from \"crypto\";\nimport { isWindows, isLinux } from \"../utils/platform\";\nimport { analyzeImageBuffer } from \"./image-analysis\";\n\nconst execAsync = promisify(exec);\n\nexport interface ScreenshotResult {\n success: boolean;\n imagePath?: string;\n imageBuffer?: Buffer;\n error?: string;\n}\n\nexport interface ScreenshotOptions {\n region?: \"full\" | \"active_window\" | { x: number; y: number; width: number; height: number };\n format?: \"png\" | \"jpg\";\n quality?: number; // 1-100 for jpg\n outputPath?: string;\n}\n\n// Generate temp file path\nfunction getTempPath(format: string): string {\n const id = randomBytes(8).toString(\"hex\");\n return join(tmpdir(), `sentinel-screenshot-${id}.${format}`);\n}\n\n// Take screenshot on Linux\nasync function screenshotLinux(options: ScreenshotOptions): Promise<ScreenshotResult> {\n const outputPath = options.outputPath || getTempPath(options.format || \"png\");\n\n try {\n let command: string;\n\n if (options.region === \"active_window\") {\n // Try gnome-screenshot first, fall back to scrot\n command = `gnome-screenshot -w -f \"${outputPath}\" 2>/dev/null || scrot -u \"${outputPath}\"`;\n } else if (typeof options.region === \"object\") {\n const { x, y, width, height } = options.region;\n // Use scrot with geometry\n command = `scrot -a ${x},${y},${width},${height} \"${outputPath}\" 2>/dev/null || import -window root -crop ${width}x${height}+${x}+${y} \"${outputPath}\"`;\n } else {\n // Full screen\n command = `gnome-screenshot -f \"${outputPath}\" 2>/dev/null || scrot \"${outputPath}\" 2>/dev/null || import -window root \"${outputPath}\"`;\n }\n\n await execAsync(command);\n\n return {\n success: true,\n imagePath: outputPath,\n };\n } catch (error) {\n return {\n success: false,\n error: `Screenshot failed: ${error instanceof Error ? error.message : String(error)}. Make sure scrot, gnome-screenshot, or ImageMagick is installed.`,\n };\n }\n}\n\n// Take screenshot on Windows\nasync function screenshotWindows(options: ScreenshotOptions): Promise<ScreenshotResult> {\n const outputPath = options.outputPath || getTempPath(options.format || \"png\");\n\n try {\n // Use PowerShell to take screenshot\n const script = `\n Add-Type -AssemblyName System.Windows.Forms\n Add-Type -AssemblyName System.Drawing\n\n $screen = [System.Windows.Forms.Screen]::PrimaryScreen\n $bitmap = New-Object System.Drawing.Bitmap($screen.Bounds.Width, $screen.Bounds.Height)\n $graphics = [System.Drawing.Graphics]::FromImage($bitmap)\n $graphics.CopyFromScreen($screen.Bounds.Location, [System.Drawing.Point]::Empty, $screen.Bounds.Size)\n $bitmap.Save(\"${outputPath.replace(/\\\\/g, \"\\\\\\\\\")}\")\n $graphics.Dispose()\n $bitmap.Dispose()\n `;\n\n const command = `powershell -NoProfile -NonInteractive -Command \"${script.replace(/\"/g, '\\\\\"').replace(/\\n/g, \" \")}\"`;\n\n await execAsync(command);\n\n return {\n success: true,\n imagePath: outputPath,\n };\n } catch (error) {\n return {\n success: false,\n error: `Screenshot failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n}\n\n// Main screenshot function\nexport async function takeScreenshot(\n options: ScreenshotOptions = {}\n): Promise<ScreenshotResult> {\n if (isLinux) {\n return screenshotLinux(options);\n }\n\n if (isWindows) {\n return screenshotWindows(options);\n }\n\n return {\n success: false,\n error: \"Screenshots are only supported on Linux and Windows\",\n };\n}\n\n// Take screenshot and return as buffer\nexport async function takeScreenshotBuffer(\n options: ScreenshotOptions = {}\n): Promise<{ success: boolean; buffer?: Buffer; error?: string }> {\n const result = await takeScreenshot(options);\n\n if (!result.success || !result.imagePath) {\n return { success: false, error: result.error };\n }\n\n try {\n const { readFile } = await import(\"fs/promises\");\n const buffer = await readFile(result.imagePath);\n\n // Clean up temp file\n if (!options.outputPath) {\n await unlink(result.imagePath).catch(() => {});\n }\n\n return { success: true, buffer };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n// Take screenshot and analyze with Vision\nexport async function screenshotAndAnalyze(\n prompt: string,\n options: ScreenshotOptions = {}\n): Promise<{\n success: boolean;\n analysis?: string;\n error?: string;\n}> {\n const result = await takeScreenshotBuffer(options);\n\n if (!result.success || !result.buffer) {\n return { success: false, error: result.error };\n }\n\n const analysisResult = await analyzeImageBuffer(\n result.buffer,\n \"image/png\",\n prompt\n );\n\n return {\n success: analysisResult.success,\n analysis: analysisResult.analysis,\n error: analysisResult.error,\n };\n}\n\n// Get screen information\nexport async function getScreenInfo(): Promise<{\n success: boolean;\n screens?: Array<{\n id: number;\n width: number;\n height: number;\n isPrimary: boolean;\n }>;\n error?: string;\n}> {\n try {\n if (isLinux) {\n const { stdout } = await execAsync(\"xrandr --query 2>/dev/null || echo 'xrandr not available'\");\n\n if (stdout.includes(\"not available\")) {\n return {\n success: true,\n screens: [{ id: 0, width: 1920, height: 1080, isPrimary: true }],\n };\n }\n\n const screens: Array<{ id: number; width: number; height: number; isPrimary: boolean }> = [];\n const lines = stdout.split(\"\\n\");\n let id = 0;\n\n for (const line of lines) {\n const match = line.match(/(\\d+)x(\\d+)\\+\\d+\\+\\d+/);\n if (match) {\n screens.push({\n id: id++,\n width: parseInt(match[1]),\n height: parseInt(match[2]),\n isPrimary: line.includes(\"primary\"),\n });\n }\n }\n\n return { success: true, screens };\n }\n\n if (isWindows) {\n const script = `\n Add-Type -AssemblyName System.Windows.Forms\n [System.Windows.Forms.Screen]::AllScreens | ForEach-Object {\n Write-Output \"$($_.Bounds.Width)x$($_.Bounds.Height),$($_.Primary)\"\n }\n `;\n\n const { stdout } = await execAsync(`powershell -NoProfile -Command \"${script.replace(/\"/g, '\\\\\"')}\"`);\n const screens = stdout.trim().split(\"\\n\").map((line, i) => {\n const [size, primary] = line.split(\",\");\n const [width, height] = size.split(\"x\").map(Number);\n return { id: i, width, height, isPrimary: primary === \"True\" };\n });\n\n return { success: true, screens };\n }\n\n return { success: false, error: \"Unsupported platform\" };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport default {\n takeScreenshot,\n takeScreenshotBuffer,\n screenshotAndAnalyze,\n getScreenInfo,\n};\n","import { createWriteStream } from \"fs\";\nimport { mkdir } from \"fs/promises\";\nimport { dirname, join } from \"path\";\nimport { tmpdir } from \"os\";\nimport { randomBytes } from \"crypto\";\nimport { isPathAllowed } from \"../../utils/paths\";\n\n// Note: PDFKit would need to be installed: bun add pdfkit @types/pdfkit\n// For now, we'll use a simpler approach with marked for HTML to PDF\n\nexport interface PDFOptions {\n title?: string;\n author?: string;\n format?: \"A4\" | \"Letter\" | \"Legal\";\n orientation?: \"portrait\" | \"landscape\";\n margins?: {\n top: number;\n bottom: number;\n left: number;\n right: number;\n };\n}\n\nexport interface PDFGenerationResult {\n success: boolean;\n filePath?: string;\n error?: string;\n}\n\nconst DEFAULT_OPTIONS: PDFOptions = {\n format: \"A4\",\n orientation: \"portrait\",\n margins: { top: 72, bottom: 72, left: 72, right: 72 },\n};\n\n// Generate temp file path\nfunction getTempPath(): string {\n const id = randomBytes(8).toString(\"hex\");\n return join(tmpdir(), `sentinel-doc-${id}.pdf`);\n}\n\n// Simple markdown to text conversion (for basic PDF)\nfunction markdownToText(markdown: string): string {\n return markdown\n // Remove code blocks\n .replace(/```[\\s\\S]*?```/g, (match) => {\n const code = match.replace(/```\\w*\\n?/g, \"\").trim();\n return `\\n${code}\\n`;\n })\n // Remove inline code\n .replace(/`([^`]+)`/g, \"$1\")\n // Convert headers\n .replace(/^### (.+)$/gm, \"\\n$1\\n\" + \"-\".repeat(30))\n .replace(/^## (.+)$/gm, \"\\n$1\\n\" + \"=\".repeat(40))\n .replace(/^# (.+)$/gm, \"\\n$1\\n\" + \"=\".repeat(50))\n // Convert bold/italic\n .replace(/\\*\\*([^*]+)\\*\\*/g, \"$1\")\n .replace(/\\*([^*]+)\\*/g, \"$1\")\n .replace(/__([^_]+)__/g, \"$1\")\n .replace(/_([^_]+)_/g, \"$1\")\n // Convert links\n .replace(/\\[([^\\]]+)\\]\\([^)]+\\)/g, \"$1\")\n // Convert lists\n .replace(/^[-*] /gm, \"• \")\n .replace(/^\\d+\\. /gm, \" \")\n // Clean up\n .replace(/\\n{3,}/g, \"\\n\\n\");\n}\n\n// Generate PDF from markdown content (simplified version without PDFKit)\nexport async function generatePDFFromMarkdown(\n markdown: string,\n outputPath?: string,\n options: PDFOptions = {}\n): Promise<PDFGenerationResult> {\n const finalOptions = { ...DEFAULT_OPTIONS, ...options };\n const filePath = outputPath || getTempPath();\n\n // Security check\n if (outputPath && !isPathAllowed(outputPath)) {\n return {\n success: false,\n error: \"Access to this path is not allowed\",\n };\n }\n\n try {\n // Ensure directory exists\n await mkdir(dirname(filePath), { recursive: true });\n\n // For now, generate a simple text file that could be converted to PDF\n // In production, you'd use PDFKit or Puppeteer\n const { writeFile } = await import(\"fs/promises\");\n\n const textContent = markdownToText(markdown);\n const header = `${finalOptions.title || \"Document\"}\\n${\"=\".repeat(50)}\\n\\n`;\n const footer = `\\n\\n${\"=\".repeat(50)}\\nGenerated by OpenSentinel`;\n\n // Generate as .txt for now (PDF requires PDFKit)\n const txtPath = filePath.replace(\".pdf\", \".txt\");\n await writeFile(txtPath, header + textContent + footer, \"utf-8\");\n\n return {\n success: true,\n filePath: txtPath,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n// Generate PDF from HTML (requires browser/puppeteer)\nexport async function generatePDFFromHTML(\n html: string,\n outputPath?: string,\n options: PDFOptions = {}\n): Promise<PDFGenerationResult> {\n const filePath = outputPath || getTempPath();\n\n // Security check\n if (outputPath && !isPathAllowed(outputPath)) {\n return {\n success: false,\n error: \"Access to this path is not allowed\",\n };\n }\n\n try {\n // Ensure directory exists\n await mkdir(dirname(filePath), { recursive: true });\n\n // Try to use Playwright if available\n try {\n const { chromium } = await import(\"playwright\");\n const browser = await chromium.launch({ headless: true });\n const page = await browser.newPage();\n\n await page.setContent(html, { waitUntil: \"networkidle\" });\n\n await page.pdf({\n path: filePath,\n format: options.format || \"A4\",\n landscape: options.orientation === \"landscape\",\n margin: options.margins\n ? {\n top: `${options.margins.top}px`,\n bottom: `${options.margins.bottom}px`,\n left: `${options.margins.left}px`,\n right: `${options.margins.right}px`,\n }\n : undefined,\n });\n\n await browser.close();\n\n return { success: true, filePath };\n } catch {\n // Fallback: save as HTML\n const { writeFile } = await import(\"fs/promises\");\n const htmlPath = filePath.replace(\".pdf\", \".html\");\n await writeFile(htmlPath, html, \"utf-8\");\n\n return {\n success: true,\n filePath: htmlPath,\n };\n }\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n// Main function for tool use\nexport async function generatePDF(\n content: string,\n filename: string,\n options?: PDFOptions & { contentType?: \"markdown\" | \"html\" }\n): Promise<PDFGenerationResult> {\n const outputPath = isPathAllowed(filename) ? filename : join(tmpdir(), filename);\n const contentType = options?.contentType || \"markdown\";\n\n if (contentType === \"html\") {\n return generatePDFFromHTML(content, outputPath, options);\n }\n\n return generatePDFFromMarkdown(content, outputPath, options);\n}\n\nexport default {\n generatePDF,\n generatePDFFromMarkdown,\n generatePDFFromHTML,\n};\n","import { join } from \"path\";\nimport { tmpdir } from \"os\";\nimport { randomBytes } from \"crypto\";\nimport { writeFile, mkdir } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { isPathAllowed } from \"../../utils/paths\";\n\nexport interface SpreadsheetOptions {\n sheetName?: string;\n headers?: string[];\n columnWidths?: number[];\n freezeHeader?: boolean;\n}\n\nexport interface SpreadsheetResult {\n success: boolean;\n filePath?: string;\n error?: string;\n}\n\n// Generate temp file path\nfunction getTempPath(extension: string): string {\n const id = randomBytes(8).toString(\"hex\");\n return join(tmpdir(), `sentinel-spreadsheet-${id}.${extension}`);\n}\n\n// Convert data to CSV format\nfunction dataToCSV(\n data: unknown[][],\n headers?: string[]\n): string {\n const rows: string[] = [];\n\n if (headers) {\n rows.push(headers.map(escapeCSVField).join(\",\"));\n }\n\n for (const row of data) {\n rows.push(row.map((cell) => escapeCSVField(String(cell ?? \"\"))).join(\",\"));\n }\n\n return rows.join(\"\\n\");\n}\n\n// Escape CSV field\nfunction escapeCSVField(field: string): string {\n if (field.includes(\",\") || field.includes('\"') || field.includes(\"\\n\")) {\n return `\"${field.replace(/\"/g, '\"\"')}\"`;\n }\n return field;\n}\n\n// Generate CSV file\nexport async function generateCSV(\n data: unknown[][],\n filename?: string,\n options: SpreadsheetOptions = {}\n): Promise<SpreadsheetResult> {\n const filePath = filename\n ? isPathAllowed(filename)\n ? filename\n : join(tmpdir(), filename)\n : getTempPath(\"csv\");\n\n try {\n await mkdir(dirname(filePath), { recursive: true });\n\n const csvContent = dataToCSV(data, options.headers);\n await writeFile(filePath, csvContent, \"utf-8\");\n\n return { success: true, filePath };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n// Generate Excel file (requires exceljs)\nexport async function generateExcel(\n data: unknown[][],\n filename?: string,\n options: SpreadsheetOptions = {}\n): Promise<SpreadsheetResult> {\n const filePath = filename\n ? isPathAllowed(filename)\n ? filename\n : join(tmpdir(), filename)\n : getTempPath(\"xlsx\");\n\n try {\n await mkdir(dirname(filePath), { recursive: true });\n\n // Try to use ExcelJS if available\n try {\n const ExcelJS = await import(\"exceljs\");\n const workbook = new ExcelJS.Workbook();\n const worksheet = workbook.addWorksheet(options.sheetName || \"Sheet1\");\n\n // Add headers if provided\n if (options.headers) {\n const headerRow = worksheet.addRow(options.headers);\n headerRow.font = { bold: true };\n headerRow.fill = {\n type: \"pattern\",\n pattern: \"solid\",\n fgColor: { argb: \"FFE0E0E0\" },\n };\n }\n\n // Add data rows\n for (const row of data) {\n worksheet.addRow(row);\n }\n\n // Set column widths\n if (options.columnWidths) {\n options.columnWidths.forEach((width, index) => {\n const col = worksheet.getColumn(index + 1);\n col.width = width;\n });\n } else {\n // Auto-fit columns (estimate)\n worksheet.columns.forEach((column) => {\n let maxLength = 10;\n column.eachCell?.({ includeEmpty: true }, (cell) => {\n const cellValue = cell.value?.toString() || \"\";\n maxLength = Math.max(maxLength, cellValue.length + 2);\n });\n column.width = Math.min(maxLength, 50);\n });\n }\n\n // Freeze header row\n if (options.freezeHeader && options.headers) {\n worksheet.views = [{ state: \"frozen\", ySplit: 1 }];\n }\n\n await workbook.xlsx.writeFile(filePath);\n\n return { success: true, filePath };\n } catch {\n // Fallback: generate CSV instead\n console.log(\n \"[Spreadsheet] ExcelJS not available, falling back to CSV\"\n );\n const csvPath = filePath.replace(\".xlsx\", \".csv\");\n return generateCSV(data, csvPath, options);\n }\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n// Generate spreadsheet from JSON array\nexport async function generateSpreadsheetFromJSON(\n jsonData: Record<string, unknown>[],\n filename?: string,\n options: SpreadsheetOptions = {}\n): Promise<SpreadsheetResult> {\n if (jsonData.length === 0) {\n return { success: false, error: \"No data provided\" };\n }\n\n // Extract headers from first object\n const headers = options.headers || Object.keys(jsonData[0]);\n\n // Convert to 2D array\n const data = jsonData.map((item) =>\n headers.map((header) => item[header] ?? \"\")\n );\n\n const ext = filename?.endsWith(\".csv\") ? \"csv\" : \"xlsx\";\n\n if (ext === \"csv\") {\n return generateCSV(data, filename, { ...options, headers });\n }\n\n return generateExcel(data, filename, { ...options, headers });\n}\n\n// Main function for tool use\nexport async function generateSpreadsheet(\n data: unknown[][] | Record<string, unknown>[],\n filename: string,\n options?: SpreadsheetOptions\n): Promise<SpreadsheetResult> {\n // Check if data is JSON array or 2D array\n if (Array.isArray(data) && data.length > 0 && !Array.isArray(data[0])) {\n return generateSpreadsheetFromJSON(\n data as Record<string, unknown>[],\n filename,\n options\n );\n }\n\n const ext = filename.endsWith(\".csv\") ? \"csv\" : \"xlsx\";\n\n if (ext === \"csv\") {\n return generateCSV(data as unknown[][], filename, options);\n }\n\n return generateExcel(data as unknown[][], filename, options);\n}\n\nexport default {\n generateCSV,\n generateExcel,\n generateSpreadsheet,\n generateSpreadsheetFromJSON,\n};\n","import { join } from \"path\";\nimport { tmpdir } from \"os\";\nimport { randomBytes } from \"crypto\";\nimport { writeFile, mkdir } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { isPathAllowed } from \"../../utils/paths\";\n\nexport type DiagramType =\n | \"flowchart\"\n | \"sequence\"\n | \"class\"\n | \"state\"\n | \"er\"\n | \"gantt\"\n | \"mindmap\";\n\nexport interface DiagramResult {\n success: boolean;\n filePath?: string;\n mermaidCode?: string;\n error?: string;\n}\n\n// Generate temp file path\nfunction getTempPath(): string {\n const id = randomBytes(8).toString(\"hex\");\n return join(tmpdir(), `sentinel-diagram-${id}.md`);\n}\n\n// Flowchart helpers\nexport interface FlowchartNode {\n id: string;\n label: string;\n shape?: \"box\" | \"round\" | \"diamond\" | \"circle\" | \"stadium\";\n}\n\nexport interface FlowchartEdge {\n from: string;\n to: string;\n label?: string;\n style?: \"solid\" | \"dotted\" | \"thick\";\n}\n\n// Generate flowchart\nexport function generateFlowchartCode(\n nodes: FlowchartNode[],\n edges: FlowchartEdge[],\n direction: \"TB\" | \"BT\" | \"LR\" | \"RL\" = \"TB\"\n): string {\n let code = `flowchart ${direction}\\n`;\n\n // Add nodes with shapes\n for (const node of nodes) {\n let shape: string;\n switch (node.shape) {\n case \"round\":\n shape = `(${node.label})`;\n break;\n case \"diamond\":\n shape = `{${node.label}}`;\n break;\n case \"circle\":\n shape = `((${node.label}))`;\n break;\n case \"stadium\":\n shape = `([${node.label}])`;\n break;\n default:\n shape = `[${node.label}]`;\n }\n code += ` ${node.id}${shape}\\n`;\n }\n\n // Add edges\n for (const edge of edges) {\n let arrow: string;\n switch (edge.style) {\n case \"dotted\":\n arrow = edge.label ? `-. ${edge.label} .->` : \"-.->\";\n break;\n case \"thick\":\n arrow = edge.label ? `== ${edge.label} ==>` : \"==>\";\n break;\n default:\n arrow = edge.label ? `-- ${edge.label} -->` : \"-->\";\n }\n code += ` ${edge.from} ${arrow} ${edge.to}\\n`;\n }\n\n return code;\n}\n\n// Sequence diagram helpers\nexport interface SequenceMessage {\n from: string;\n to: string;\n message: string;\n type?: \"solid\" | \"dotted\" | \"async\";\n}\n\nexport function generateSequenceCode(\n participants: string[],\n messages: SequenceMessage[],\n title?: string\n): string {\n let code = \"sequenceDiagram\\n\";\n\n if (title) {\n code += ` title ${title}\\n`;\n }\n\n // Add participants\n for (const participant of participants) {\n code += ` participant ${participant}\\n`;\n }\n\n // Add messages\n for (const msg of messages) {\n let arrow: string;\n switch (msg.type) {\n case \"dotted\":\n arrow = \"-->>\";\n break;\n case \"async\":\n arrow = \"--)\";\n break;\n default:\n arrow = \"->>\";\n }\n code += ` ${msg.from}${arrow}${msg.to}: ${msg.message}\\n`;\n }\n\n return code;\n}\n\n// Class diagram helpers\nexport interface ClassDefinition {\n name: string;\n attributes?: string[];\n methods?: string[];\n}\n\nexport interface ClassRelation {\n from: string;\n to: string;\n type: \"inheritance\" | \"composition\" | \"aggregation\" | \"association\" | \"dependency\";\n label?: string;\n}\n\nexport function generateClassCode(\n classes: ClassDefinition[],\n relations: ClassRelation[]\n): string {\n let code = \"classDiagram\\n\";\n\n // Add classes\n for (const cls of classes) {\n code += ` class ${cls.name} {\\n`;\n if (cls.attributes) {\n for (const attr of cls.attributes) {\n code += ` ${attr}\\n`;\n }\n }\n if (cls.methods) {\n for (const method of cls.methods) {\n code += ` ${method}\\n`;\n }\n }\n code += ` }\\n`;\n }\n\n // Add relations\n for (const rel of relations) {\n let arrow: string;\n switch (rel.type) {\n case \"inheritance\":\n arrow = \"<|--\";\n break;\n case \"composition\":\n arrow = \"*--\";\n break;\n case \"aggregation\":\n arrow = \"o--\";\n break;\n case \"dependency\":\n arrow = \"<..\";\n break;\n default:\n arrow = \"--\";\n }\n const label = rel.label ? ` : ${rel.label}` : \"\";\n code += ` ${rel.from} ${arrow} ${rel.to}${label}\\n`;\n }\n\n return code;\n}\n\n// State diagram helpers\nexport interface StateTransition {\n from: string;\n to: string;\n trigger?: string;\n}\n\nexport function generateStateCode(\n states: string[],\n transitions: StateTransition[],\n initialState?: string,\n finalStates?: string[]\n): string {\n let code = \"stateDiagram-v2\\n\";\n\n // Initial state\n if (initialState) {\n code += ` [*] --> ${initialState}\\n`;\n }\n\n // State definitions (optional, for complex states)\n for (const state of states) {\n if (!state.includes(\":\")) {\n code += ` ${state}\\n`;\n } else {\n const [name, description] = state.split(\":\");\n code += ` ${name} : ${description.trim()}\\n`;\n }\n }\n\n // Transitions\n for (const trans of transitions) {\n const label = trans.trigger ? ` : ${trans.trigger}` : \"\";\n code += ` ${trans.from} --> ${trans.to}${label}\\n`;\n }\n\n // Final states\n if (finalStates) {\n for (const finalState of finalStates) {\n code += ` ${finalState} --> [*]\\n`;\n }\n }\n\n return code;\n}\n\n// ER diagram helpers\nexport interface EREntity {\n name: string;\n attributes: Array<{\n name: string;\n type: string;\n key?: \"PK\" | \"FK\";\n }>;\n}\n\nexport interface ERRelation {\n from: string;\n to: string;\n fromCardinality: \"one\" | \"zero-or-one\" | \"zero-or-more\" | \"one-or-more\";\n toCardinality: \"one\" | \"zero-or-one\" | \"zero-or-more\" | \"one-or-more\";\n label?: string;\n}\n\nexport function generateERCode(\n entities: EREntity[],\n relations: ERRelation[]\n): string {\n let code = \"erDiagram\\n\";\n\n // Add entities\n for (const entity of entities) {\n code += ` ${entity.name} {\\n`;\n for (const attr of entity.attributes) {\n const keyStr = attr.key ? ` ${attr.key}` : \"\";\n code += ` ${attr.type} ${attr.name}${keyStr}\\n`;\n }\n code += ` }\\n`;\n }\n\n // Add relations\n for (const rel of relations) {\n const fromCard = cardinalitySymbol(rel.fromCardinality);\n const toCard = cardinalitySymbol(rel.toCardinality);\n const label = rel.label ? ` : \"${rel.label}\"` : \"\";\n code += ` ${rel.from} ${fromCard}--${toCard} ${rel.to}${label}\\n`;\n }\n\n return code;\n}\n\nfunction cardinalitySymbol(cardinality: string): string {\n switch (cardinality) {\n case \"one\":\n return \"||\";\n case \"zero-or-one\":\n return \"|o\";\n case \"zero-or-more\":\n return \"}o\";\n case \"one-or-more\":\n return \"}|\";\n default:\n return \"||\";\n }\n}\n\n// Gantt chart helpers\nexport interface GanttTask {\n name: string;\n start: string; // date string or \"after taskId\"\n duration: string; // e.g., \"5d\", \"1w\"\n section?: string;\n status?: \"done\" | \"active\" | \"crit\";\n}\n\nexport function generateGanttCode(\n title: string,\n tasks: GanttTask[],\n dateFormat: string = \"YYYY-MM-DD\"\n): string {\n let code = \"gantt\\n\";\n code += ` title ${title}\\n`;\n code += ` dateFormat ${dateFormat}\\n`;\n\n let currentSection = \"\";\n\n for (const task of tasks) {\n if (task.section && task.section !== currentSection) {\n code += ` section ${task.section}\\n`;\n currentSection = task.section;\n }\n\n const status = task.status ? `${task.status}, ` : \"\";\n code += ` ${task.name} :${status}${task.start}, ${task.duration}\\n`;\n }\n\n return code;\n}\n\n// Mindmap helpers\nexport interface MindmapNode {\n text: string;\n children?: MindmapNode[];\n}\n\nexport function generateMindmapCode(root: MindmapNode): string {\n let code = \"mindmap\\n\";\n code += ` root((${root.text}))\\n`;\n\n function addChildren(node: MindmapNode, depth: number): void {\n if (!node.children) return;\n const indent = \" \".repeat(depth);\n for (const child of node.children) {\n code += `${indent}${child.text}\\n`;\n addChildren(child, depth + 1);\n }\n }\n\n addChildren(root, 2);\n return code;\n}\n\n// Main function: generate diagram from Mermaid code\nexport async function generateDiagram(\n mermaidCode: string,\n filename?: string\n): Promise<DiagramResult> {\n const filePath = filename\n ? isPathAllowed(filename)\n ? filename\n : join(tmpdir(), filename)\n : getTempPath();\n\n try {\n await mkdir(dirname(filePath), { recursive: true });\n\n // Wrap in markdown code block\n const content = `# Diagram\\n\\n\\`\\`\\`mermaid\\n${mermaidCode}\\n\\`\\`\\`\\n`;\n\n await writeFile(filePath, content, \"utf-8\");\n\n return {\n success: true,\n filePath,\n mermaidCode,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n// Generate diagram from structured input\nexport async function generateStructuredDiagram(\n type: DiagramType,\n data: unknown,\n filename?: string\n): Promise<DiagramResult> {\n let mermaidCode: string;\n\n try {\n switch (type) {\n case \"flowchart\": {\n const { nodes, edges, direction } = data as {\n nodes: FlowchartNode[];\n edges: FlowchartEdge[];\n direction?: \"TB\" | \"BT\" | \"LR\" | \"RL\";\n };\n mermaidCode = generateFlowchartCode(nodes, edges, direction);\n break;\n }\n case \"sequence\": {\n const { participants, messages, title } = data as {\n participants: string[];\n messages: SequenceMessage[];\n title?: string;\n };\n mermaidCode = generateSequenceCode(participants, messages, title);\n break;\n }\n case \"class\": {\n const { classes, relations } = data as {\n classes: ClassDefinition[];\n relations: ClassRelation[];\n };\n mermaidCode = generateClassCode(classes, relations);\n break;\n }\n case \"state\": {\n const { states, transitions, initialState, finalStates } = data as {\n states: string[];\n transitions: StateTransition[];\n initialState?: string;\n finalStates?: string[];\n };\n mermaidCode = generateStateCode(states, transitions, initialState, finalStates);\n break;\n }\n case \"er\": {\n const { entities, relations } = data as {\n entities: EREntity[];\n relations: ERRelation[];\n };\n mermaidCode = generateERCode(entities, relations);\n break;\n }\n case \"gantt\": {\n const { title, tasks, dateFormat } = data as {\n title: string;\n tasks: GanttTask[];\n dateFormat?: string;\n };\n mermaidCode = generateGanttCode(title, tasks, dateFormat);\n break;\n }\n case \"mindmap\": {\n const { root } = data as { root: MindmapNode };\n mermaidCode = generateMindmapCode(root);\n break;\n }\n default:\n return { success: false, error: `Unsupported diagram type: ${type}` };\n }\n\n return generateDiagram(mermaidCode, filename);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport default {\n generateDiagram,\n generateStructuredDiagram,\n generateFlowchartCode,\n generateSequenceCode,\n generateClassCode,\n generateStateCode,\n generateERCode,\n generateGanttCode,\n generateMindmapCode,\n};\n","import { drizzle } from \"drizzle-orm/postgres-js\";\nimport postgres from \"postgres\";\nimport { env } from \"../config/env\";\nimport * as schema from \"./schema\";\n\n// Lazy database connection — created on first access\nlet _client: ReturnType<typeof postgres> | null = null;\nlet _db: ReturnType<typeof drizzle> | null = null;\n\nfunction getDb() {\n if (!_db) {\n _client = postgres(env.DATABASE_URL);\n _db = drizzle(_client, { schema });\n }\n return _db;\n}\n\n// Proxy preserves the `db.select()`, `db.insert()`, `db.execute()` access pattern\n// so all existing consumer files work unchanged.\nexport const db: ReturnType<typeof drizzle<typeof schema>> = new Proxy(\n {} as any,\n {\n get(_target, prop) {\n const instance = getDb();\n const value = (instance as any)[prop];\n if (typeof value === \"function\") {\n return value.bind(instance);\n }\n return value;\n },\n }\n);\n\nexport * from \"./schema\";\n","import {\n pgTable,\n text,\n timestamp,\n uuid,\n integer,\n jsonb,\n boolean,\n vector,\n index,\n} from \"drizzle-orm/pg-core\";\n\n// Users table\nexport const users = pgTable(\"users\", {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n telegramId: text(\"telegram_id\").unique(),\n name: text(\"name\"),\n preferences: jsonb(\"preferences\").$type<{\n timezone?: string;\n language?: string;\n verbosity?: \"terse\" | \"normal\" | \"detailed\";\n persona?: \"formal\" | \"casual\" | \"snarky\";\n }>(),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n updatedAt: timestamp(\"updated_at\").defaultNow().notNull(),\n});\n\n// Conversations table\nexport const conversations = pgTable(\"conversations\", {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n userId: uuid(\"user_id\").references(() => users.id),\n title: text(\"title\"),\n source: text(\"source\").notNull().default(\"telegram\"), // telegram, web, api\n metadata: jsonb(\"metadata\"),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n updatedAt: timestamp(\"updated_at\").defaultNow().notNull(),\n});\n\n// Messages table\nexport const messages = pgTable(\n \"messages\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n conversationId: uuid(\"conversation_id\")\n .references(() => conversations.id)\n .notNull(),\n role: text(\"role\").notNull().$type<\"user\" | \"assistant\" | \"system\">(),\n content: text(\"content\").notNull(),\n tokenCount: integer(\"token_count\"),\n metadata: jsonb(\"metadata\"),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n },\n (table) => [index(\"messages_conversation_idx\").on(table.conversationId)]\n);\n\n// Memories table with vector embeddings for RAG\nexport const memories = pgTable(\n \"memories\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n userId: uuid(\"user_id\").references(() => users.id),\n type: text(\"type\")\n .notNull()\n .$type<\"episodic\" | \"semantic\" | \"procedural\">(),\n content: text(\"content\").notNull(),\n embedding: vector(\"embedding\", { dimensions: 1536 }), // OpenAI embedding size\n importance: integer(\"importance\").default(5), // 1-10 scale\n source: text(\"source\"), // Where this memory came from\n metadata: jsonb(\"metadata\"),\n lastAccessed: timestamp(\"last_accessed\").defaultNow(),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n },\n (table) => [index(\"memories_user_idx\").on(table.userId)]\n);\n\n// Scheduled tasks table\nexport const scheduledTasks = pgTable(\"scheduled_tasks\", {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n userId: uuid(\"user_id\").references(() => users.id),\n name: text(\"name\").notNull(),\n description: text(\"description\"),\n cronExpression: text(\"cron_expression\"),\n nextRunAt: timestamp(\"next_run_at\"),\n lastRunAt: timestamp(\"last_run_at\"),\n enabled: boolean(\"enabled\").default(true),\n action: jsonb(\"action\").$type<{\n type: \"message\" | \"command\" | \"webhook\";\n payload: Record<string, unknown>;\n }>(),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n});\n\n// Tool execution logs\nexport const toolLogs = pgTable(\n \"tool_logs\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n conversationId: uuid(\"conversation_id\").references(() => conversations.id),\n toolName: text(\"tool_name\").notNull(),\n input: jsonb(\"input\"),\n output: jsonb(\"output\"),\n success: boolean(\"success\").notNull(),\n durationMs: integer(\"duration_ms\"),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n },\n (table) => [index(\"tool_logs_conversation_idx\").on(table.conversationId)]\n);\n\n// ============================================\n// SECURITY TABLES (Phase 1)\n// ============================================\n\n// Sessions table for session management\nexport const sessions = pgTable(\n \"sessions\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n userId: uuid(\"user_id\")\n .references(() => users.id)\n .notNull(),\n token: text(\"token\").notNull().unique(),\n deviceInfo: jsonb(\"device_info\").$type<{\n userAgent?: string;\n platform?: string;\n browser?: string;\n }>(),\n ipAddress: text(\"ip_address\"),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n expiresAt: timestamp(\"expires_at\").notNull(),\n lastActiveAt: timestamp(\"last_active_at\").defaultNow(),\n },\n (table) => [index(\"sessions_user_idx\").on(table.userId)]\n);\n\n// Audit logs table for tracking all actions\nexport const auditLogs = pgTable(\n \"audit_logs\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n userId: uuid(\"user_id\").references(() => users.id),\n sessionId: uuid(\"session_id\").references(() => sessions.id),\n action: text(\"action\").notNull(), // 'tool_use', 'login', 'settings_change', etc.\n resource: text(\"resource\"), // 'shell', 'file', 'memory', etc.\n resourceId: text(\"resource_id\"), // ID of the affected resource\n details: jsonb(\"details\"),\n ipAddress: text(\"ip_address\"),\n userAgent: text(\"user_agent\"),\n success: boolean(\"success\").default(true),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n },\n (table) => [\n index(\"audit_logs_user_idx\").on(table.userId),\n index(\"audit_logs_action_idx\").on(table.action),\n index(\"audit_logs_created_idx\").on(table.createdAt),\n ]\n);\n\n// API keys table for programmatic access\nexport const apiKeys = pgTable(\n \"api_keys\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n userId: uuid(\"user_id\")\n .references(() => users.id)\n .notNull(),\n name: text(\"name\").notNull(),\n keyHash: text(\"key_hash\").notNull(), // bcrypt hash of the key\n keyPrefix: text(\"key_prefix\").notNull(), // First 8 chars for identification (e.g., \"mb_live_\")\n permissions: jsonb(\"permissions\").$type<string[]>(), // ['chat:basic', 'tools:shell', etc.]\n lastUsedAt: timestamp(\"last_used_at\"),\n expiresAt: timestamp(\"expires_at\"),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n revokedAt: timestamp(\"revoked_at\"),\n },\n (table) => [index(\"api_keys_user_idx\").on(table.userId)]\n);\n\n// Rate limits table for tracking request rates\nexport const rateLimits = pgTable(\n \"rate_limits\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n identifier: text(\"identifier\").notNull(), // userId, IP, or API key prefix\n endpoint: text(\"endpoint\").notNull(), // 'api/chat', 'tool/shell', etc.\n windowStart: timestamp(\"window_start\").notNull(),\n requestCount: integer(\"request_count\").default(0),\n lastRequest: timestamp(\"last_request\"),\n },\n (table) => [\n index(\"rate_limits_identifier_endpoint_idx\").on(\n table.identifier,\n table.endpoint\n ),\n ]\n);\n\n// ============================================\n// OBSERVABILITY TABLES (Phase 1)\n// ============================================\n\n// Metrics table for performance tracking\nexport const metrics = pgTable(\n \"metrics\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n name: text(\"name\").notNull(), // 'response_latency', 'token_usage', 'tool_duration', etc.\n value: integer(\"value\").notNull(),\n unit: text(\"unit\"), // 'ms', 'tokens', 'bytes', etc.\n tags: jsonb(\"tags\").$type<Record<string, string>>(), // { tool: 'shell', status: 'success' }\n timestamp: timestamp(\"timestamp\").defaultNow().notNull(),\n },\n (table) => [\n index(\"metrics_name_timestamp_idx\").on(table.name, table.timestamp),\n ]\n);\n\n// Error logs table for centralized error tracking\nexport const errorLogs = pgTable(\n \"error_logs\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n source: text(\"source\").notNull(), // 'brain', 'tool', 'telegram', 'api', 'scheduler'\n errorType: text(\"error_type\").notNull(), // 'ApiError', 'ValidationError', etc.\n errorCode: text(\"error_code\"), // Application-specific error codes\n message: text(\"message\").notNull(),\n stack: text(\"stack\"),\n context: jsonb(\"context\"), // Additional context like request data\n userId: uuid(\"user_id\").references(() => users.id),\n conversationId: uuid(\"conversation_id\").references(() => conversations.id),\n resolved: boolean(\"resolved\").default(false),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n },\n (table) => [\n index(\"error_logs_source_idx\").on(table.source),\n index(\"error_logs_created_idx\").on(table.createdAt),\n ]\n);\n\n// ============================================\n// MOLT SYSTEM TABLES (Phase 2)\n// ============================================\n\n// Usage patterns for evolution tracking\nexport const usagePatterns = pgTable(\n \"usage_patterns\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n userId: uuid(\"user_id\")\n .references(() => users.id)\n .notNull(),\n patternType: text(\"pattern_type\").notNull(), // 'tool_usage', 'topic', 'time_of_day', 'complexity'\n patternKey: text(\"pattern_key\").notNull(), // e.g., 'shell', 'morning', 'coding'\n patternData: jsonb(\"pattern_data\"),\n confidence: integer(\"confidence\").default(0), // 0-100\n firstSeen: timestamp(\"first_seen\").defaultNow().notNull(),\n lastSeen: timestamp(\"last_seen\").defaultNow(),\n occurrences: integer(\"occurrences\").default(1),\n },\n (table) => [\n index(\"usage_patterns_user_idx\").on(table.userId),\n index(\"usage_patterns_type_idx\").on(table.patternType),\n ]\n);\n\n// Achievements definitions\nexport const achievements = pgTable(\"achievements\", {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n code: text(\"code\").notNull().unique(), // 'first_tool_use', 'power_user', 'researcher'\n name: text(\"name\").notNull(),\n description: text(\"description\"),\n iconEmoji: text(\"icon_emoji\"), // Emoji to display\n category: text(\"category\"), // 'exploration', 'productivity', 'mastery'\n criteria: jsonb(\"criteria\").$type<{\n type: string; // 'count', 'streak', 'threshold'\n metric: string; // 'tool_uses', 'conversations', 'memories'\n threshold: number;\n conditions?: Record<string, unknown>;\n }>(),\n points: integer(\"points\").default(10),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n});\n\n// User achievements (unlocked)\nexport const userAchievements = pgTable(\n \"user_achievements\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n userId: uuid(\"user_id\")\n .references(() => users.id)\n .notNull(),\n achievementId: uuid(\"achievement_id\")\n .references(() => achievements.id)\n .notNull(),\n unlockedAt: timestamp(\"unlocked_at\").defaultNow().notNull(),\n progress: integer(\"progress\").default(100), // For progressive achievements\n notified: boolean(\"notified\").default(false),\n },\n (table) => [index(\"user_achievements_user_idx\").on(table.userId)]\n);\n\n// Molt transformation modes\nexport const moltModes = pgTable(\n \"molt_modes\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n userId: uuid(\"user_id\")\n .references(() => users.id)\n .notNull(),\n mode: text(\"mode\")\n .notNull()\n .$type<\"productivity\" | \"creative\" | \"research\" | \"learning\">(),\n activatedAt: timestamp(\"activated_at\").defaultNow().notNull(),\n deactivatedAt: timestamp(\"deactivated_at\"),\n metadata: jsonb(\"metadata\"),\n },\n (table) => [index(\"molt_modes_user_idx\").on(table.userId)]\n);\n\n// Archived memories (for memory shedding)\nexport const archivedMemories = pgTable(\n \"archived_memories\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n originalMemoryId: uuid(\"original_memory_id\").notNull(),\n userId: uuid(\"user_id\").references(() => users.id),\n type: text(\"type\")\n .notNull()\n .$type<\"episodic\" | \"semantic\" | \"procedural\">(),\n content: text(\"content\").notNull(),\n reason: text(\"reason\"), // 'stale', 'duplicate', 'low_importance', 'user_request'\n originalCreatedAt: timestamp(\"original_created_at\"),\n archivedAt: timestamp(\"archived_at\").defaultNow().notNull(),\n },\n (table) => [index(\"archived_memories_user_idx\").on(table.userId)]\n);\n\n// ============================================\n// CALENDAR & TRIGGERS TABLES (Phase 3)\n// ============================================\n\nexport const calendarTriggers = pgTable(\n \"calendar_triggers\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n userId: uuid(\"user_id\")\n .references(() => users.id)\n .notNull(),\n name: text(\"name\").notNull(),\n calendarSource: text(\"calendar_source\").notNull(), // 'google', 'outlook', 'ical'\n calendarId: text(\"calendar_id\"),\n triggerType: text(\"trigger_type\").notNull(), // 'event_start', 'event_end', 'daily_briefing'\n offsetMinutes: integer(\"offset_minutes\").default(0), // Trigger X minutes before/after\n action: jsonb(\"action\").$type<{\n type: \"message\" | \"tool\" | \"webhook\";\n payload: Record<string, unknown>;\n }>(),\n enabled: boolean(\"enabled\").default(true),\n lastTriggered: timestamp(\"last_triggered\"),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n },\n (table) => [index(\"calendar_triggers_user_idx\").on(table.userId)]\n);\n\n// ============================================\n// SUB-AGENT TABLES (Phase 4)\n// ============================================\n\nexport const subAgents = pgTable(\n \"sub_agents\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n parentConversationId: uuid(\"parent_conversation_id\").references(\n () => conversations.id\n ),\n userId: uuid(\"user_id\")\n .references(() => users.id)\n .notNull(),\n type: text(\"type\")\n .notNull()\n .$type<\"research\" | \"coding\" | \"writing\" | \"analysis\">(),\n name: text(\"name\").notNull(),\n status: text(\"status\")\n .notNull()\n .$type<\"pending\" | \"running\" | \"completed\" | \"failed\" | \"cancelled\">(),\n objective: text(\"objective\").notNull(),\n context: jsonb(\"context\"),\n result: jsonb(\"result\"),\n tokenBudget: integer(\"token_budget\").default(50000),\n tokensUsed: integer(\"tokens_used\").default(0),\n timeBudgetMs: integer(\"time_budget_ms\").default(3600000), // 1 hour default\n startedAt: timestamp(\"started_at\"),\n completedAt: timestamp(\"completed_at\"),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n },\n (table) => [\n index(\"sub_agents_user_idx\").on(table.userId),\n index(\"sub_agents_status_idx\").on(table.status),\n ]\n);\n\nexport const agentMessages = pgTable(\n \"agent_messages\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n agentId: uuid(\"agent_id\")\n .references(() => subAgents.id)\n .notNull(),\n role: text(\"role\")\n .notNull()\n .$type<\"user\" | \"assistant\" | \"system\" | \"tool_result\">(),\n content: text(\"content\").notNull(),\n metadata: jsonb(\"metadata\"),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n },\n (table) => [index(\"agent_messages_agent_idx\").on(table.agentId)]\n);\n\nexport const agentProgress = pgTable(\n \"agent_progress\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n agentId: uuid(\"agent_id\")\n .references(() => subAgents.id)\n .notNull(),\n step: integer(\"step\").notNull(),\n description: text(\"description\").notNull(),\n status: text(\"status\")\n .notNull()\n .$type<\"pending\" | \"running\" | \"completed\" | \"failed\">(),\n output: jsonb(\"output\"),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n },\n (table) => [index(\"agent_progress_agent_idx\").on(table.agentId)]\n);\n\n// ============================================\n// PERSONALITY TABLES (Phase 5)\n// ============================================\n\nexport const personas = pgTable(\n \"personas\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n userId: uuid(\"user_id\").references(() => users.id), // null = system persona\n name: text(\"name\").notNull(),\n description: text(\"description\"),\n basePrompt: text(\"base_prompt\").notNull(),\n isDefault: boolean(\"is_default\").default(false),\n isSystem: boolean(\"is_system\").default(false), // Built-in personas\n settings: jsonb(\"settings\").$type<{\n verbosity: \"terse\" | \"normal\" | \"detailed\";\n humor: \"off\" | \"subtle\" | \"full\";\n formality: \"formal\" | \"casual\" | \"professional\";\n emoji: boolean;\n proactivity: \"minimal\" | \"moderate\" | \"proactive\";\n }>(),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n },\n (table) => [index(\"personas_user_idx\").on(table.userId)]\n);\n\n// ============================================\n// ENTERPRISE TABLES (Phase 6)\n// ============================================\n\nexport const organizations = pgTable(\"organizations\", {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n name: text(\"name\").notNull(),\n slug: text(\"slug\").unique(),\n settings: jsonb(\"settings\"),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n updatedAt: timestamp(\"updated_at\").defaultNow(),\n});\n\nexport const organizationMembers = pgTable(\n \"organization_members\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n organizationId: uuid(\"organization_id\")\n .references(() => organizations.id)\n .notNull(),\n userId: uuid(\"user_id\")\n .references(() => users.id)\n .notNull(),\n role: text(\"role\").notNull().$type<\"owner\" | \"admin\" | \"member\" | \"viewer\">(),\n joinedAt: timestamp(\"joined_at\").defaultNow().notNull(),\n },\n (table) => [\n index(\"org_members_org_idx\").on(table.organizationId),\n index(\"org_members_user_idx\").on(table.userId),\n ]\n);\n\nexport const sharedMemories = pgTable(\n \"shared_memories\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n organizationId: uuid(\"organization_id\")\n .references(() => organizations.id)\n .notNull(),\n memoryId: uuid(\"memory_id\")\n .references(() => memories.id)\n .notNull(),\n sharedBy: uuid(\"shared_by\")\n .references(() => users.id)\n .notNull(),\n sharedAt: timestamp(\"shared_at\").defaultNow().notNull(),\n },\n (table) => [index(\"shared_memories_org_idx\").on(table.organizationId)]\n);\n\nexport const usageQuotas = pgTable(\n \"usage_quotas\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n userId: uuid(\"user_id\").references(() => users.id),\n organizationId: uuid(\"organization_id\").references(() => organizations.id),\n quotaType: text(\"quota_type\").notNull(), // 'tokens_daily', 'tokens_monthly', 'agents_concurrent'\n limitValue: integer(\"limit_value\").notNull(),\n currentValue: integer(\"current_value\").default(0),\n resetAt: timestamp(\"reset_at\"),\n updatedAt: timestamp(\"updated_at\").defaultNow(),\n },\n (table) => [\n index(\"usage_quotas_user_idx\").on(table.userId),\n index(\"usage_quotas_org_idx\").on(table.organizationId),\n ]\n);\n\n// ============================================\n// DOCUMENT KNOWLEDGE BASE TABLES\n// ============================================\n\nexport const documents = pgTable(\n \"documents\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n name: text(\"name\").notNull(),\n filename: text(\"filename\"),\n mimeType: text(\"mime_type\"),\n fileSize: integer(\"file_size\"),\n source: text(\"source\"), // 'upload', 'url', 'api'\n sourceUrl: text(\"source_url\"),\n metadata: jsonb(\"metadata\"),\n status: text(\"status\")\n .notNull()\n .$type<\"pending\" | \"processing\" | \"completed\" | \"failed\">()\n .default(\"pending\"),\n errorMessage: text(\"error_message\"),\n chunkCount: integer(\"chunk_count\").default(0),\n totalTokens: integer(\"total_tokens\").default(0),\n userId: uuid(\"user_id\").references(() => users.id),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n updatedAt: timestamp(\"updated_at\").defaultNow().notNull(),\n processedAt: timestamp(\"processed_at\"),\n },\n (table) => [\n index(\"documents_user_idx\").on(table.userId),\n index(\"documents_status_idx\").on(table.status),\n ]\n);\n\nexport const documentChunks = pgTable(\n \"document_chunks\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n documentId: uuid(\"document_id\")\n .references(() => documents.id, { onDelete: \"cascade\" })\n .notNull(),\n chunkIndex: integer(\"chunk_index\").notNull(),\n content: text(\"content\").notNull(),\n embedding: vector(\"embedding\", { dimensions: 1536 }),\n tokenCount: integer(\"token_count\"),\n metadata: jsonb(\"metadata\"),\n createdAt: timestamp(\"created_at\").defaultNow().notNull(),\n },\n (table) => [\n index(\"document_chunks_document_idx\").on(table.documentId),\n ]\n);\n\n// ============================================\n// TYPE EXPORTS\n// ============================================\n\nexport type User = typeof users.$inferSelect;\nexport type NewUser = typeof users.$inferInsert;\nexport type Conversation = typeof conversations.$inferSelect;\nexport type NewConversation = typeof conversations.$inferInsert;\nexport type Message = typeof messages.$inferSelect;\nexport type NewMessage = typeof messages.$inferInsert;\nexport type Memory = typeof memories.$inferSelect;\nexport type NewMemory = typeof memories.$inferInsert;\n\n// Security types\nexport type Session = typeof sessions.$inferSelect;\nexport type NewSession = typeof sessions.$inferInsert;\nexport type AuditLog = typeof auditLogs.$inferSelect;\nexport type NewAuditLog = typeof auditLogs.$inferInsert;\nexport type ApiKey = typeof apiKeys.$inferSelect;\nexport type NewApiKey = typeof apiKeys.$inferInsert;\n\n// Observability types\nexport type Metric = typeof metrics.$inferSelect;\nexport type NewMetric = typeof metrics.$inferInsert;\nexport type ErrorLog = typeof errorLogs.$inferSelect;\nexport type NewErrorLog = typeof errorLogs.$inferInsert;\n\n// Molt system types\nexport type UsagePattern = typeof usagePatterns.$inferSelect;\nexport type NewUsagePattern = typeof usagePatterns.$inferInsert;\nexport type Achievement = typeof achievements.$inferSelect;\nexport type NewAchievement = typeof achievements.$inferInsert;\nexport type UserAchievement = typeof userAchievements.$inferSelect;\nexport type MoltMode = typeof moltModes.$inferSelect;\nexport type NewMoltMode = typeof moltModes.$inferInsert;\n\n// Sub-agent types\nexport type SubAgent = typeof subAgents.$inferSelect;\nexport type NewSubAgent = typeof subAgents.$inferInsert;\nexport type AgentMessage = typeof agentMessages.$inferSelect;\nexport type AgentProgress = typeof agentProgress.$inferSelect;\n\n// Personality types\nexport type Persona = typeof personas.$inferSelect;\nexport type NewPersona = typeof personas.$inferInsert;\n\n// Enterprise types\nexport type Organization = typeof organizations.$inferSelect;\nexport type NewOrganization = typeof organizations.$inferInsert;\nexport type OrganizationMember = typeof organizationMembers.$inferSelect;\n\n// Document knowledge base types\nexport type Document = typeof documents.$inferSelect;\nexport type NewDocument = typeof documents.$inferInsert;\nexport type DocumentChunk = typeof documentChunks.$inferSelect;\nexport type NewDocumentChunk = typeof documentChunks.$inferInsert;\n","import { db } from \"../../db\";\nimport {\n subAgents,\n agentMessages,\n agentProgress,\n NewSubAgent,\n} from \"../../db/schema\";\nimport { eq, and, desc } from \"drizzle-orm\";\nimport { Queue, Job } from \"bullmq\";\nimport Redis from \"ioredis\";\nimport { env } from \"../../config/env\";\nimport {\n AgentConfig,\n AgentStatus,\n AgentResult,\n AgentProgress,\n Agent,\n AgentMessage,\n} from \"./agent-types\";\nimport { audit } from \"../security/audit-logger\";\nimport { metric } from \"../observability/metrics\";\n\n// Redis connection for agent queue\nconst connection = new Redis(env.REDIS_URL, {\n maxRetriesPerRequest: null,\n});\n\n// Agent task queue\nconst agentQueue = new Queue(\"sentinel-agents\", { connection });\n\nconst DEFAULT_TOKEN_BUDGET = 50000;\nconst DEFAULT_TIME_BUDGET_MS = 3600000; // 1 hour\n\nexport interface SpawnAgentOptions extends AgentConfig {\n userId: string;\n parentConversationId?: string;\n name?: string;\n}\n\n// Spawn a new agent\nexport async function spawnAgent(options: SpawnAgentOptions): Promise<string> {\n const {\n userId,\n type,\n objective,\n context,\n tokenBudget = DEFAULT_TOKEN_BUDGET,\n timeBudgetMs = DEFAULT_TIME_BUDGET_MS,\n parentConversationId,\n name,\n } = options;\n\n // Create agent record\n const [agent] = await db\n .insert(subAgents)\n .values({\n userId,\n type,\n name: name || `${type.charAt(0).toUpperCase() + type.slice(1)} Agent`,\n status: \"pending\",\n objective,\n context,\n tokenBudget,\n timeBudgetMs,\n parentConversationId,\n })\n .returning();\n\n // Queue the agent job\n await agentQueue.add(\n \"agent-task\",\n {\n agentId: agent.id,\n userId,\n type,\n objective,\n context,\n tokenBudget,\n timeBudgetMs,\n },\n {\n attempts: 1, // Don't retry agent tasks\n removeOnComplete: true,\n removeOnFail: 100,\n }\n );\n\n // Log audit\n await audit.agentSpawn(userId, agent.id, type);\n\n // Record metric\n metric.agentOperation(\"spawn\", type);\n\n return agent.id;\n}\n\n// Get agent by ID\nexport async function getAgent(agentId: string): Promise<Agent | null> {\n const [agent] = await db\n .select()\n .from(subAgents)\n .where(eq(subAgents.id, agentId))\n .limit(1);\n\n if (!agent) return null;\n\n // Get messages\n const messages = await db\n .select()\n .from(agentMessages)\n .where(eq(agentMessages.agentId, agentId))\n .orderBy(agentMessages.createdAt);\n\n // Get progress\n const progress = await db\n .select()\n .from(agentProgress)\n .where(eq(agentProgress.agentId, agentId))\n .orderBy(agentProgress.step);\n\n return {\n id: agent.id,\n userId: agent.userId,\n type: agent.type as Agent[\"type\"],\n name: agent.name,\n status: agent.status as AgentStatus,\n objective: agent.objective,\n context: agent.context as Record<string, unknown> | undefined,\n tokenBudget: agent.tokenBudget || DEFAULT_TOKEN_BUDGET,\n tokensUsed: agent.tokensUsed || 0,\n timeBudgetMs: agent.timeBudgetMs || DEFAULT_TIME_BUDGET_MS,\n startedAt: agent.startedAt || undefined,\n completedAt: agent.completedAt || undefined,\n createdAt: agent.createdAt,\n messages: messages.map((m) => ({\n role: m.role as AgentMessage[\"role\"],\n content: m.content,\n metadata: m.metadata as Record<string, unknown> | undefined,\n timestamp: m.createdAt,\n })),\n progress: progress.map((p) => ({\n step: p.step,\n description: p.description,\n status: p.status as AgentProgress[\"status\"],\n output: p.output as unknown,\n timestamp: p.createdAt,\n })),\n result: agent.result as AgentResult | undefined,\n };\n}\n\n// Get user's agents\nexport async function getUserAgents(\n userId: string,\n status?: AgentStatus,\n limit: number = 20\n): Promise<Agent[]> {\n let query = db\n .select()\n .from(subAgents)\n .where(eq(subAgents.userId, userId));\n\n if (status) {\n query = db\n .select()\n .from(subAgents)\n .where(and(eq(subAgents.userId, userId), eq(subAgents.status, status)));\n }\n\n const agents = await query.orderBy(desc(subAgents.createdAt)).limit(limit);\n\n return Promise.all(agents.map((a) => getAgent(a.id) as Promise<Agent>));\n}\n\n// Update agent status\nexport async function updateAgentStatus(\n agentId: string,\n status: AgentStatus,\n result?: AgentResult\n): Promise<void> {\n const updates: Record<string, unknown> = { status };\n\n if (status === \"running\") {\n updates.startedAt = new Date();\n }\n\n if (status === \"completed\" || status === \"failed\" || status === \"cancelled\") {\n updates.completedAt = new Date();\n if (result) {\n updates.result = result;\n updates.tokensUsed = result.tokensUsed;\n }\n }\n\n await db.update(subAgents).set(updates).where(eq(subAgents.id, agentId));\n}\n\n// Add message to agent\nexport async function addAgentMessage(\n agentId: string,\n message: Omit<AgentMessage, \"timestamp\">\n): Promise<void> {\n await db.insert(agentMessages).values({\n agentId,\n role: message.role,\n content: message.content,\n metadata: message.metadata,\n });\n}\n\n// Add progress update\nexport async function addAgentProgress(\n agentId: string,\n step: number,\n description: string,\n status: AgentProgress[\"status\"] = \"running\",\n output?: unknown\n): Promise<void> {\n await db.insert(agentProgress).values({\n agentId,\n step,\n description,\n status,\n output: output as Record<string, unknown>,\n });\n}\n\n// Cancel an agent\nexport async function cancelAgent(agentId: string): Promise<boolean> {\n const agent = await getAgent(agentId);\n\n if (!agent) return false;\n\n if (agent.status === \"completed\" || agent.status === \"failed\") {\n return false; // Already finished\n }\n\n await updateAgentStatus(agentId, \"cancelled\", {\n success: false,\n error: \"Agent cancelled by user\",\n tokensUsed: agent.tokensUsed,\n durationMs: agent.startedAt\n ? Date.now() - agent.startedAt.getTime()\n : 0,\n });\n\n return true;\n}\n\n// Get running agents count for user\nexport async function getRunningAgentCount(userId: string): Promise<number> {\n const running = await db\n .select()\n .from(subAgents)\n .where(\n and(\n eq(subAgents.userId, userId),\n eq(subAgents.status, \"running\")\n )\n );\n\n return running.length;\n}\n\n// Check if agent should stop (timeout or cancellation)\nexport async function shouldAgentStop(agentId: string): Promise<{\n stop: boolean;\n reason?: string;\n}> {\n const agent = await getAgent(agentId);\n\n if (!agent) {\n return { stop: true, reason: \"Agent not found\" };\n }\n\n if (agent.status === \"cancelled\") {\n return { stop: true, reason: \"Agent cancelled\" };\n }\n\n if (agent.tokensUsed >= agent.tokenBudget) {\n return { stop: true, reason: \"Token budget exceeded\" };\n }\n\n if (agent.startedAt) {\n const elapsed = Date.now() - agent.startedAt.getTime();\n if (elapsed >= agent.timeBudgetMs) {\n return { stop: true, reason: \"Time budget exceeded\" };\n }\n }\n\n return { stop: false };\n}\n\n// Update tokens used\nexport async function updateAgentTokens(\n agentId: string,\n tokensUsed: number\n): Promise<void> {\n await db\n .update(subAgents)\n .set({ tokensUsed })\n .where(eq(subAgents.id, agentId));\n}\n\n// Get agent queue\nexport { agentQueue };\n\nexport default {\n spawnAgent,\n getAgent,\n getUserAgents,\n updateAgentStatus,\n addAgentMessage,\n addAgentProgress,\n cancelAgent,\n getRunningAgentCount,\n shouldAgentStop,\n updateAgentTokens,\n};\n","import { db } from \"../../db\";\nimport { auditLogs, NewAuditLog } from \"../../db/schema\";\nimport { eq, and, gte, lte, desc } from \"drizzle-orm\";\n\nexport type AuditAction =\n | \"login\"\n | \"logout\"\n | \"session_create\"\n | \"session_invalidate\"\n | \"api_key_create\"\n | \"api_key_revoke\"\n | \"tool_use\"\n | \"chat_message\"\n | \"memory_create\"\n | \"memory_delete\"\n | \"memory_archive\"\n | \"settings_change\"\n | \"mode_change\"\n | \"agent_spawn\"\n | \"agent_complete\"\n | \"file_read\"\n | \"file_write\"\n | \"shell_execute\"\n | \"web_browse\"\n | \"error\";\n\nexport type AuditResource =\n | \"session\"\n | \"api_key\"\n | \"tool\"\n | \"chat\"\n | \"memory\"\n | \"settings\"\n | \"mode\"\n | \"agent\"\n | \"file\"\n | \"shell\"\n | \"browser\";\n\nexport interface AuditLogEntry {\n userId?: string;\n sessionId?: string;\n action: AuditAction;\n resource?: AuditResource;\n resourceId?: string;\n details?: Record<string, unknown>;\n ipAddress?: string;\n userAgent?: string;\n success?: boolean;\n}\n\nexport async function logAudit(entry: AuditLogEntry): Promise<string> {\n const [log] = await db\n .insert(auditLogs)\n .values({\n userId: entry.userId,\n sessionId: entry.sessionId,\n action: entry.action,\n resource: entry.resource,\n resourceId: entry.resourceId,\n details: entry.details,\n ipAddress: entry.ipAddress,\n userAgent: entry.userAgent,\n success: entry.success ?? true,\n })\n .returning();\n\n return log.id;\n}\n\nexport interface AuditQueryOptions {\n userId?: string;\n action?: AuditAction;\n resource?: AuditResource;\n startDate?: Date;\n endDate?: Date;\n limit?: number;\n offset?: number;\n}\n\nexport async function queryAuditLogs(options: AuditQueryOptions = {}) {\n const {\n userId,\n action,\n resource,\n startDate,\n endDate,\n limit = 100,\n offset = 0,\n } = options;\n\n let query = db.select().from(auditLogs);\n\n const conditions = [];\n\n if (userId) {\n conditions.push(eq(auditLogs.userId, userId));\n }\n\n if (action) {\n conditions.push(eq(auditLogs.action, action));\n }\n\n if (resource) {\n conditions.push(eq(auditLogs.resource, resource));\n }\n\n if (startDate) {\n conditions.push(gte(auditLogs.createdAt, startDate));\n }\n\n if (endDate) {\n conditions.push(lte(auditLogs.createdAt, endDate));\n }\n\n if (conditions.length > 0) {\n query = query.where(and(...conditions)) as typeof query;\n }\n\n const logs = await query\n .orderBy(desc(auditLogs.createdAt))\n .limit(limit)\n .offset(offset);\n\n return logs;\n}\n\nexport async function getRecentUserActivity(\n userId: string,\n hours = 24\n): Promise<typeof auditLogs.$inferSelect[]> {\n const since = new Date(Date.now() - hours * 60 * 60 * 1000);\n\n return db\n .select()\n .from(auditLogs)\n .where(and(eq(auditLogs.userId, userId), gte(auditLogs.createdAt, since)))\n .orderBy(desc(auditLogs.createdAt))\n .limit(100);\n}\n\nexport async function countActionsByType(\n userId: string,\n startDate: Date,\n endDate: Date\n): Promise<Record<string, number>> {\n const logs = await db\n .select()\n .from(auditLogs)\n .where(\n and(\n eq(auditLogs.userId, userId),\n gte(auditLogs.createdAt, startDate),\n lte(auditLogs.createdAt, endDate)\n )\n );\n\n const counts: Record<string, number> = {};\n for (const log of logs) {\n counts[log.action] = (counts[log.action] || 0) + 1;\n }\n\n return counts;\n}\n\n// Convenience functions for common audit events\nexport const audit = {\n login: (userId: string, ipAddress?: string, userAgent?: string) =>\n logAudit({\n userId,\n action: \"login\",\n resource: \"session\",\n ipAddress,\n userAgent,\n }),\n\n logout: (userId: string, sessionId: string) =>\n logAudit({\n userId,\n sessionId,\n action: \"logout\",\n resource: \"session\",\n }),\n\n toolUse: (\n userId: string,\n toolName: string,\n input: Record<string, unknown>,\n success: boolean\n ) =>\n logAudit({\n userId,\n action: \"tool_use\",\n resource: \"tool\",\n resourceId: toolName,\n details: { input },\n success,\n }),\n\n shellExecute: (\n userId: string,\n command: string,\n exitCode: number,\n durationMs: number\n ) =>\n logAudit({\n userId,\n action: \"shell_execute\",\n resource: \"shell\",\n details: { command, exitCode, durationMs },\n success: exitCode === 0,\n }),\n\n fileAccess: (\n userId: string,\n action: \"file_read\" | \"file_write\",\n filePath: string\n ) =>\n logAudit({\n userId,\n action,\n resource: \"file\",\n resourceId: filePath,\n }),\n\n memoryCreate: (userId: string, memoryId: string, memoryType: string) =>\n logAudit({\n userId,\n action: \"memory_create\",\n resource: \"memory\",\n resourceId: memoryId,\n details: { type: memoryType },\n }),\n\n modeChange: (\n userId: string,\n fromMode: string | null,\n toMode: string\n ) =>\n logAudit({\n userId,\n action: \"mode_change\",\n resource: \"mode\",\n details: { fromMode, toMode },\n }),\n\n agentSpawn: (userId: string, agentId: string, agentType: string) =>\n logAudit({\n userId,\n action: \"agent_spawn\",\n resource: \"agent\",\n resourceId: agentId,\n details: { type: agentType },\n }),\n\n error: (\n userId: string | undefined,\n errorType: string,\n message: string,\n context?: Record<string, unknown>\n ) =>\n logAudit({\n userId,\n action: \"error\",\n details: { errorType, message, ...context },\n success: false,\n }),\n};\n","import { db } from \"../../db\";\nimport { metrics, NewMetric } from \"../../db/schema\";\nimport { eq, and, gte, lte, desc, sql } from \"drizzle-orm\";\n\nexport type MetricName =\n | \"response_latency\"\n | \"token_usage_input\"\n | \"token_usage_output\"\n | \"tool_duration\"\n | \"tool_success\"\n | \"tool_failure\"\n | \"api_request\"\n | \"telegram_message\"\n | \"memory_search\"\n | \"memory_store\"\n | \"agent_spawn\"\n | \"agent_complete\"\n | \"plugin_enable\"\n | \"plugin_disable\"\n | \"plugin_load\"\n | \"plugin_unload\"\n | \"plugin_tool_execute\"\n | \"error_count\";\n\nexport type MetricUnit = \"ms\" | \"tokens\" | \"count\" | \"bytes\" | \"percent\";\n\nexport interface MetricEntry {\n name: MetricName;\n value: number;\n unit?: MetricUnit;\n tags?: Record<string, string>;\n}\n\n// In-memory buffer for batching metrics\nlet metricBuffer: MetricEntry[] = [];\nlet flushTimer: Timer | null = null;\nconst FLUSH_INTERVAL = 5000; // 5 seconds\nconst MAX_BUFFER_SIZE = 100;\n\nexport async function recordMetric(entry: MetricEntry): Promise<void> {\n metricBuffer.push(entry);\n\n // Flush if buffer is full\n if (metricBuffer.length >= MAX_BUFFER_SIZE) {\n await flushMetrics();\n } else if (!flushTimer) {\n // Start flush timer\n flushTimer = setTimeout(flushMetrics, FLUSH_INTERVAL);\n }\n}\n\nexport async function flushMetrics(): Promise<void> {\n if (flushTimer) {\n clearTimeout(flushTimer);\n flushTimer = null;\n }\n\n if (metricBuffer.length === 0) return;\n\n const toInsert = metricBuffer;\n metricBuffer = [];\n\n try {\n await db.insert(metrics).values(\n toInsert.map((m) => ({\n name: m.name,\n value: m.value,\n unit: m.unit,\n tags: m.tags,\n }))\n );\n } catch (error) {\n console.error(\"[Metrics] Failed to flush metrics:\", error);\n // Put metrics back in buffer for retry\n metricBuffer = [...toInsert, ...metricBuffer].slice(0, MAX_BUFFER_SIZE * 2);\n }\n}\n\n// Convenience functions\nexport const metric = {\n latency: (value: number, tags?: Record<string, string>) =>\n recordMetric({ name: \"response_latency\", value, unit: \"ms\", tags }),\n\n tokens: (input: number, output: number, tags?: Record<string, string>) => {\n recordMetric({ name: \"token_usage_input\", value: input, unit: \"tokens\", tags });\n recordMetric({ name: \"token_usage_output\", value: output, unit: \"tokens\", tags });\n },\n\n toolDuration: (toolName: string, durationMs: number, success: boolean) => {\n recordMetric({\n name: \"tool_duration\",\n value: durationMs,\n unit: \"ms\",\n tags: { tool: toolName },\n });\n recordMetric({\n name: success ? \"tool_success\" : \"tool_failure\",\n value: 1,\n unit: \"count\",\n tags: { tool: toolName },\n });\n },\n\n apiRequest: (endpoint: string, statusCode: number) =>\n recordMetric({\n name: \"api_request\",\n value: 1,\n unit: \"count\",\n tags: { endpoint, status: String(statusCode) },\n }),\n\n telegramMessage: () =>\n recordMetric({ name: \"telegram_message\", value: 1, unit: \"count\" }),\n\n memoryOperation: (operation: \"search\" | \"store\", durationMs: number) =>\n recordMetric({\n name: operation === \"search\" ? \"memory_search\" : \"memory_store\",\n value: durationMs,\n unit: \"ms\",\n }),\n\n agentOperation: (operation: \"spawn\" | \"complete\", agentType: string) =>\n recordMetric({\n name: operation === \"spawn\" ? \"agent_spawn\" : \"agent_complete\",\n value: 1,\n unit: \"count\",\n tags: { type: agentType },\n }),\n\n pluginOperation: (operation: \"enable\" | \"disable\" | \"load\" | \"unload\" | \"tool_execute\", pluginId: string) =>\n recordMetric({\n name: `plugin_${operation}` as MetricName,\n value: 1,\n unit: \"count\",\n tags: { plugin: pluginId },\n }),\n\n error: (source: string) =>\n recordMetric({\n name: \"error_count\",\n value: 1,\n unit: \"count\",\n tags: { source },\n }),\n};\n\n// Query functions\nexport interface MetricQuery {\n name?: MetricName;\n startDate?: Date;\n endDate?: Date;\n tags?: Record<string, string>;\n}\n\nexport async function queryMetrics(query: MetricQuery = {}) {\n const { name, startDate, endDate } = query;\n\n let conditions = [];\n\n if (name) {\n conditions.push(eq(metrics.name, name));\n }\n\n if (startDate) {\n conditions.push(gte(metrics.timestamp, startDate));\n }\n\n if (endDate) {\n conditions.push(lte(metrics.timestamp, endDate));\n }\n\n let q = db.select().from(metrics);\n\n if (conditions.length > 0) {\n q = q.where(and(...conditions)) as typeof q;\n }\n\n return q.orderBy(desc(metrics.timestamp)).limit(1000);\n}\n\nexport interface AggregatedMetric {\n name: string;\n count: number;\n sum: number;\n avg: number;\n min: number;\n max: number;\n p50?: number;\n p95?: number;\n p99?: number;\n}\n\nexport async function getMetricAggregates(\n name: MetricName,\n startDate: Date,\n endDate: Date\n): Promise<AggregatedMetric> {\n const results = await db\n .select()\n .from(metrics)\n .where(\n and(\n eq(metrics.name, name),\n gte(metrics.timestamp, startDate),\n lte(metrics.timestamp, endDate)\n )\n )\n .orderBy(metrics.value);\n\n if (results.length === 0) {\n return {\n name,\n count: 0,\n sum: 0,\n avg: 0,\n min: 0,\n max: 0,\n };\n }\n\n const values = results.map((r) => r.value);\n const sum = values.reduce((a, b) => a + b, 0);\n\n return {\n name,\n count: values.length,\n sum,\n avg: sum / values.length,\n min: values[0],\n max: values[values.length - 1],\n p50: values[Math.floor(values.length * 0.5)],\n p95: values[Math.floor(values.length * 0.95)],\n p99: values[Math.floor(values.length * 0.99)],\n };\n}\n\nexport async function getMetricTimeSeries(\n name: MetricName,\n startDate: Date,\n endDate: Date,\n bucketMinutes: number = 60\n): Promise<Array<{ bucket: Date; count: number; avg: number }>> {\n const results = await db\n .select()\n .from(metrics)\n .where(\n and(\n eq(metrics.name, name),\n gte(metrics.timestamp, startDate),\n lte(metrics.timestamp, endDate)\n )\n )\n .orderBy(metrics.timestamp);\n\n // Group into time buckets\n const bucketMs = bucketMinutes * 60 * 1000;\n const buckets = new Map<number, number[]>();\n\n for (const result of results) {\n const bucketTime = Math.floor(result.timestamp.getTime() / bucketMs) * bucketMs;\n if (!buckets.has(bucketTime)) {\n buckets.set(bucketTime, []);\n }\n buckets.get(bucketTime)!.push(result.value);\n }\n\n return Array.from(buckets.entries())\n .map(([time, values]) => ({\n bucket: new Date(time),\n count: values.length,\n avg: values.reduce((a, b) => a + b, 0) / values.length,\n }))\n .sort((a, b) => a.bucket.getTime() - b.bucket.getTime());\n}\n\n// System status metrics\nexport function getSystemMetrics(): {\n memoryUsage: NodeJS.MemoryUsage;\n uptime: number;\n platform: string;\n} {\n return {\n memoryUsage: process.memoryUsage(),\n uptime: process.uptime(),\n platform: process.platform,\n };\n}\n\n// Cleanup old metrics\nexport async function cleanupOldMetrics(daysToKeep: number = 30): Promise<number> {\n const cutoff = new Date(Date.now() - daysToKeep * 24 * 60 * 60 * 1000);\n await db.delete(metrics).where(lte(metrics.timestamp, cutoff));\n return 0; // Cleanup completed\n}\n\n// Ensure metrics are flushed on shutdown\nprocess.on(\"beforeExit\", async () => {\n await flushMetrics();\n});\n","import { join } from \"path\";\nimport { tmpdir } from \"os\";\nimport { randomBytes } from \"crypto\";\nimport { writeFile, mkdir } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { isPathAllowed } from \"../../utils/paths\";\n\nexport interface MathRenderResult {\n success: boolean;\n svg?: string;\n html?: string;\n filePath?: string;\n error?: string;\n}\n\nexport interface MathRenderOptions {\n displayMode?: boolean; // true for block math, false for inline\n fontSize?: number;\n color?: string;\n backgroundColor?: string;\n}\n\n// Generate temp file path\nfunction getTempPath(extension: string): string {\n const id = randomBytes(8).toString(\"hex\");\n return join(tmpdir(), `sentinel-math-${id}.${extension}`);\n}\n\n// Convert LaTeX to SVG using basic transformation\n// Note: For production, use KaTeX or MathJax server-side rendering\nexport function latexToSvg(latex: string, options: MathRenderOptions = {}): string {\n const { displayMode = true, fontSize = 20, color = \"black\" } = options;\n\n // This is a simplified renderer - in production use KaTeX or MathJax\n // For now, return an SVG with the LaTeX as text\n const escaped = escapeXml(latex);\n const width = Math.max(200, latex.length * 10);\n const height = displayMode ? 60 : 30;\n\n return `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\" viewBox=\"0 0 ${width} ${height}\">\n <style>\n .math { font-family: \"Times New Roman\", serif; font-size: ${fontSize}px; fill: ${color}; }\n </style>\n <text x=\"10\" y=\"${height / 2 + 5}\" class=\"math\">${escaped}</text>\n</svg>`;\n}\n\n// Convert LaTeX to HTML (for web display)\nexport function latexToHtml(latex: string, options: MathRenderOptions = {}): string {\n const { displayMode = true } = options;\n const escaped = escapeHtml(latex);\n\n if (displayMode) {\n return `<div class=\"math-block\">\\\\[${escaped}\\\\]</div>`;\n }\n return `<span class=\"math-inline\">\\\\(${escaped}\\\\)</span>`;\n}\n\n// Escape XML special characters\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n\n// Escape HTML special characters\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n\n// Common math symbols and their LaTeX\nexport const MATH_SYMBOLS = {\n // Greek letters\n alpha: \"\\\\alpha\",\n beta: \"\\\\beta\",\n gamma: \"\\\\gamma\",\n delta: \"\\\\delta\",\n epsilon: \"\\\\epsilon\",\n theta: \"\\\\theta\",\n lambda: \"\\\\lambda\",\n pi: \"\\\\pi\",\n sigma: \"\\\\sigma\",\n omega: \"\\\\omega\",\n\n // Operators\n sum: \"\\\\sum\",\n prod: \"\\\\prod\",\n int: \"\\\\int\",\n sqrt: \"\\\\sqrt\",\n frac: \"\\\\frac\",\n lim: \"\\\\lim\",\n\n // Relations\n leq: \"\\\\leq\",\n geq: \"\\\\geq\",\n neq: \"\\\\neq\",\n approx: \"\\\\approx\",\n equiv: \"\\\\equiv\",\n\n // Arrows\n rightarrow: \"\\\\rightarrow\",\n leftarrow: \"\\\\leftarrow\",\n leftrightarrow: \"\\\\leftrightarrow\",\n implies: \"\\\\implies\",\n\n // Sets\n in: \"\\\\in\",\n notin: \"\\\\notin\",\n subset: \"\\\\subset\",\n supset: \"\\\\supset\",\n cup: \"\\\\cup\",\n cap: \"\\\\cap\",\n emptyset: \"\\\\emptyset\",\n\n // Others\n infty: \"\\\\infty\",\n partial: \"\\\\partial\",\n nabla: \"\\\\nabla\",\n forall: \"\\\\forall\",\n exists: \"\\\\exists\",\n};\n\n// Render LaTeX expression\nexport async function renderMath(\n latex: string,\n filename?: string,\n options: MathRenderOptions = {}\n): Promise<MathRenderResult> {\n try {\n const svg = latexToSvg(latex, options);\n const html = latexToHtml(latex, options);\n\n if (filename) {\n const filePath = isPathAllowed(filename) ? filename : join(tmpdir(), filename);\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, svg, \"utf-8\");\n\n return { success: true, svg, html, filePath };\n }\n\n return { success: true, svg, html };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n// Render multiple math expressions as a document\nexport async function renderMathDocument(\n expressions: Array<{ latex: string; label?: string }>,\n filename?: string\n): Promise<MathRenderResult> {\n try {\n let html = `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"UTF-8\">\n <title>Math Document</title>\n <style>\n body { font-family: Georgia, serif; max-width: 800px; margin: 0 auto; padding: 20px; }\n .math-block { text-align: center; margin: 20px 0; padding: 10px; background: #f5f5f5; }\n .math-inline { padding: 0 4px; }\n .label { color: #666; font-size: 14px; margin-top: 5px; }\n </style>\n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js\"></script>\n</head>\n<body>\n <h1>Mathematical Expressions</h1>\n`;\n\n for (const expr of expressions) {\n const mathHtml = latexToHtml(expr.latex, { displayMode: true });\n html += ` <div class=\"expression\">\\n ${mathHtml}\\n`;\n if (expr.label) {\n html += ` <div class=\"label\">${escapeHtml(expr.label)}</div>\\n`;\n }\n html += ` </div>\\n`;\n }\n\n html += `</body>\\n</html>`;\n\n if (filename) {\n const filePath = isPathAllowed(filename) ? filename : join(tmpdir(), filename);\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, html, \"utf-8\");\n\n return { success: true, html, filePath };\n }\n\n return { success: true, html };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport default {\n renderMath,\n renderMathDocument,\n latexToSvg,\n latexToHtml,\n MATH_SYMBOLS,\n};\n","import { join } from \"path\";\nimport { tmpdir } from \"os\";\nimport { randomBytes } from \"crypto\";\nimport { writeFile, mkdir } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { isPathAllowed } from \"../../utils/paths\";\n\nexport interface CodeHighlightResult {\n success: boolean;\n html?: string;\n filePath?: string;\n error?: string;\n}\n\nexport interface CodeHighlightOptions {\n language?: string;\n theme?: \"light\" | \"dark\" | \"github\" | \"monokai\";\n lineNumbers?: boolean;\n highlightLines?: number[];\n title?: string;\n}\n\n// Language-specific keyword sets\nconst LANGUAGE_KEYWORDS: Record<string, { keywords: string[]; types: string[]; builtins: string[] }> = {\n typescript: {\n keywords: [\n \"async\", \"await\", \"break\", \"case\", \"catch\", \"class\", \"const\", \"continue\",\n \"debugger\", \"default\", \"delete\", \"do\", \"else\", \"enum\", \"export\", \"extends\",\n \"false\", \"finally\", \"for\", \"function\", \"if\", \"import\", \"in\", \"instanceof\",\n \"let\", \"new\", \"null\", \"return\", \"static\", \"super\", \"switch\", \"this\",\n \"throw\", \"true\", \"try\", \"typeof\", \"var\", \"void\", \"while\", \"with\", \"yield\",\n \"interface\", \"type\", \"implements\", \"private\", \"public\", \"protected\", \"readonly\",\n ],\n types: [\"string\", \"number\", \"boolean\", \"any\", \"void\", \"never\", \"unknown\", \"object\", \"Array\", \"Promise\"],\n builtins: [\"console\", \"Math\", \"JSON\", \"Date\", \"Object\", \"Array\", \"String\", \"Number\", \"Boolean\", \"Error\"],\n },\n javascript: {\n keywords: [\n \"async\", \"await\", \"break\", \"case\", \"catch\", \"class\", \"const\", \"continue\",\n \"debugger\", \"default\", \"delete\", \"do\", \"else\", \"export\", \"extends\",\n \"false\", \"finally\", \"for\", \"function\", \"if\", \"import\", \"in\", \"instanceof\",\n \"let\", \"new\", \"null\", \"return\", \"static\", \"super\", \"switch\", \"this\",\n \"throw\", \"true\", \"try\", \"typeof\", \"var\", \"void\", \"while\", \"with\", \"yield\",\n ],\n types: [],\n builtins: [\"console\", \"Math\", \"JSON\", \"Date\", \"Object\", \"Array\", \"String\", \"Number\", \"Boolean\", \"Error\", \"Promise\"],\n },\n python: {\n keywords: [\n \"False\", \"None\", \"True\", \"and\", \"as\", \"assert\", \"async\", \"await\", \"break\",\n \"class\", \"continue\", \"def\", \"del\", \"elif\", \"else\", \"except\", \"finally\",\n \"for\", \"from\", \"global\", \"if\", \"import\", \"in\", \"is\", \"lambda\", \"nonlocal\",\n \"not\", \"or\", \"pass\", \"raise\", \"return\", \"try\", \"while\", \"with\", \"yield\",\n ],\n types: [\"int\", \"float\", \"str\", \"bool\", \"list\", \"dict\", \"tuple\", \"set\", \"bytes\"],\n builtins: [\"print\", \"len\", \"range\", \"type\", \"isinstance\", \"open\", \"input\", \"map\", \"filter\", \"zip\", \"enumerate\"],\n },\n go: {\n keywords: [\n \"break\", \"case\", \"chan\", \"const\", \"continue\", \"default\", \"defer\", \"else\",\n \"fallthrough\", \"for\", \"func\", \"go\", \"goto\", \"if\", \"import\", \"interface\",\n \"map\", \"package\", \"range\", \"return\", \"select\", \"struct\", \"switch\", \"type\", \"var\",\n ],\n types: [\"string\", \"int\", \"int8\", \"int16\", \"int32\", \"int64\", \"uint\", \"float32\", \"float64\", \"bool\", \"byte\", \"rune\", \"error\"],\n builtins: [\"append\", \"cap\", \"close\", \"copy\", \"delete\", \"len\", \"make\", \"new\", \"panic\", \"print\", \"println\", \"recover\"],\n },\n rust: {\n keywords: [\n \"as\", \"async\", \"await\", \"break\", \"const\", \"continue\", \"crate\", \"dyn\", \"else\",\n \"enum\", \"extern\", \"false\", \"fn\", \"for\", \"if\", \"impl\", \"in\", \"let\", \"loop\",\n \"match\", \"mod\", \"move\", \"mut\", \"pub\", \"ref\", \"return\", \"self\", \"Self\",\n \"static\", \"struct\", \"super\", \"trait\", \"true\", \"type\", \"unsafe\", \"use\", \"where\", \"while\",\n ],\n types: [\"i8\", \"i16\", \"i32\", \"i64\", \"i128\", \"u8\", \"u16\", \"u32\", \"u64\", \"u128\", \"f32\", \"f64\", \"bool\", \"char\", \"str\", \"String\", \"Vec\", \"Option\", \"Result\"],\n builtins: [\"println!\", \"print!\", \"format!\", \"vec!\", \"panic!\", \"assert!\", \"dbg!\"],\n },\n};\n\n// Theme color schemes\nconst THEMES: Record<string, {\n background: string;\n text: string;\n keyword: string;\n string: string;\n comment: string;\n number: string;\n type: string;\n builtin: string;\n lineNumber: string;\n highlight: string;\n}> = {\n light: {\n background: \"#ffffff\",\n text: \"#333333\",\n keyword: \"#0000ff\",\n string: \"#a31515\",\n comment: \"#008000\",\n number: \"#098658\",\n type: \"#267f99\",\n builtin: \"#795e26\",\n lineNumber: \"#999999\",\n highlight: \"#fffbdd\",\n },\n dark: {\n background: \"#1e1e1e\",\n text: \"#d4d4d4\",\n keyword: \"#569cd6\",\n string: \"#ce9178\",\n comment: \"#6a9955\",\n number: \"#b5cea8\",\n type: \"#4ec9b0\",\n builtin: \"#dcdcaa\",\n lineNumber: \"#858585\",\n highlight: \"#264f78\",\n },\n github: {\n background: \"#f6f8fa\",\n text: \"#24292e\",\n keyword: \"#d73a49\",\n string: \"#032f62\",\n comment: \"#6a737d\",\n number: \"#005cc5\",\n type: \"#6f42c1\",\n builtin: \"#e36209\",\n lineNumber: \"#959da5\",\n highlight: \"#fffbdd\",\n },\n monokai: {\n background: \"#272822\",\n text: \"#f8f8f2\",\n keyword: \"#f92672\",\n string: \"#e6db74\",\n comment: \"#75715e\",\n number: \"#ae81ff\",\n type: \"#66d9ef\",\n builtin: \"#a6e22e\",\n lineNumber: \"#8f908a\",\n highlight: \"#49483e\",\n },\n};\n\n// Simple tokenizer for syntax highlighting\nfunction tokenize(code: string, language: string): Array<{ type: string; value: string }> {\n const tokens: Array<{ type: string; value: string }> = [];\n const langConfig = LANGUAGE_KEYWORDS[language] || LANGUAGE_KEYWORDS.javascript;\n\n // Simple regex-based tokenization\n const patterns = [\n { type: \"comment\", regex: /\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?\\*\\/|#[^\\n]*/g },\n { type: \"string\", regex: /\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'|`(?:[^`\\\\]|\\\\.)*`/g },\n { type: \"number\", regex: /\\b\\d+\\.?\\d*\\b/g },\n { type: \"word\", regex: /\\b[a-zA-Z_]\\w*\\b/g },\n { type: \"operator\", regex: /[+\\-*/%=<>!&|^~?:]+/g },\n { type: \"punctuation\", regex: /[{}[\\]();,\\.]/g },\n { type: \"whitespace\", regex: /\\s+/g },\n ];\n\n let remaining = code;\n let position = 0;\n\n while (remaining.length > 0) {\n let matched = false;\n\n for (const { type, regex } of patterns) {\n regex.lastIndex = 0;\n const match = regex.exec(remaining);\n\n if (match && match.index === 0) {\n let tokenType = type;\n\n // Classify words\n if (type === \"word\") {\n if (langConfig.keywords.includes(match[0])) {\n tokenType = \"keyword\";\n } else if (langConfig.types.includes(match[0])) {\n tokenType = \"type\";\n } else if (langConfig.builtins.includes(match[0])) {\n tokenType = \"builtin\";\n }\n }\n\n tokens.push({ type: tokenType, value: match[0] });\n remaining = remaining.slice(match[0].length);\n position += match[0].length;\n matched = true;\n break;\n }\n }\n\n if (!matched) {\n // Unknown character, add as text\n tokens.push({ type: \"text\", value: remaining[0] });\n remaining = remaining.slice(1);\n position++;\n }\n }\n\n return tokens;\n}\n\n// Escape HTML\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n\n// Generate highlighted HTML\nexport function highlightCode(\n code: string,\n options: CodeHighlightOptions = {}\n): string {\n const {\n language = \"javascript\",\n theme = \"dark\",\n lineNumbers = true,\n highlightLines = [],\n title,\n } = options;\n\n const themeColors = THEMES[theme] || THEMES.dark;\n const tokens = tokenize(code, language);\n\n // Build highlighted code\n let highlightedCode = \"\";\n for (const token of tokens) {\n if (token.type === \"whitespace\") {\n highlightedCode += escapeHtml(token.value);\n } else {\n const color = themeColors[token.type as keyof typeof themeColors] || themeColors.text;\n highlightedCode += `<span style=\"color: ${color}\">${escapeHtml(token.value)}</span>`;\n }\n }\n\n // Split into lines\n const lines = highlightedCode.split(\"\\n\");\n\n // Build HTML\n let html = `<div class=\"code-block\" style=\"background: ${themeColors.background}; border-radius: 6px; overflow: hidden; font-family: 'Consolas', 'Monaco', monospace; font-size: 14px;\">`;\n\n if (title) {\n html += `<div style=\"background: ${theme === \"dark\" || theme === \"monokai\" ? \"#333\" : \"#e1e4e8\"}; padding: 8px 12px; color: ${themeColors.text}; border-bottom: 1px solid ${theme === \"dark\" || theme === \"monokai\" ? \"#444\" : \"#d1d5da\"};\">${escapeHtml(title)}</div>`;\n }\n\n html += `<pre style=\"margin: 0; padding: 12px; overflow-x: auto;\"><code>`;\n\n for (let i = 0; i < lines.length; i++) {\n const lineNum = i + 1;\n const isHighlighted = highlightLines.includes(lineNum);\n const lineStyle = isHighlighted ? `background: ${themeColors.highlight};` : \"\";\n\n html += `<div style=\"display: flex; ${lineStyle}\">`;\n\n if (lineNumbers) {\n html += `<span style=\"color: ${themeColors.lineNumber}; user-select: none; text-align: right; padding-right: 12px; min-width: 30px;\">${lineNum}</span>`;\n }\n\n html += `<span style=\"color: ${themeColors.text}; flex: 1;\">${lines[i] || \" \"}</span>`;\n html += `</div>`;\n }\n\n html += `</code></pre></div>`;\n\n return html;\n}\n\n// Render code to file\nexport async function renderCode(\n code: string,\n filename?: string,\n options: CodeHighlightOptions = {}\n): Promise<CodeHighlightResult> {\n try {\n const html = highlightCode(code, options);\n\n if (filename) {\n const filePath = isPathAllowed(filename) ? filename : join(tmpdir(), filename);\n await mkdir(dirname(filePath), { recursive: true });\n\n // Wrap in full HTML document\n const fullHtml = `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"UTF-8\">\n <title>${options.title || \"Code\"}</title>\n</head>\n<body style=\"margin: 20px;\">\n${html}\n</body>\n</html>`;\n\n await writeFile(filePath, fullHtml, \"utf-8\");\n return { success: true, html, filePath };\n }\n\n return { success: true, html };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n// Get supported languages\nexport function getSupportedLanguages(): string[] {\n return Object.keys(LANGUAGE_KEYWORDS);\n}\n\n// Get available themes\nexport function getAvailableThemes(): string[] {\n return Object.keys(THEMES);\n}\n\nexport default {\n highlightCode,\n renderCode,\n getSupportedLanguages,\n getAvailableThemes,\n};\n","import { join } from \"path\";\nimport { tmpdir } from \"os\";\nimport { randomBytes } from \"crypto\";\nimport { writeFile, mkdir } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { isPathAllowed } from \"../../utils/paths\";\nimport { highlightCode } from \"./code-highlighter\";\n\nexport interface MarkdownRenderResult {\n success: boolean;\n html?: string;\n filePath?: string;\n error?: string;\n}\n\nexport interface MarkdownRenderOptions {\n theme?: \"light\" | \"dark\" | \"github\";\n syntaxHighlight?: boolean;\n tableOfContents?: boolean;\n sanitize?: boolean;\n}\n\n// Default CSS themes\nconst THEMES: Record<string, string> = {\n light: `\n body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif; line-height: 1.6; color: #24292e; max-width: 800px; margin: 0 auto; padding: 20px; }\n h1, h2, h3, h4, h5, h6 { margin-top: 24px; margin-bottom: 16px; font-weight: 600; line-height: 1.25; }\n h1 { font-size: 2em; border-bottom: 1px solid #eaecef; padding-bottom: 0.3em; }\n h2 { font-size: 1.5em; border-bottom: 1px solid #eaecef; padding-bottom: 0.3em; }\n h3 { font-size: 1.25em; }\n p { margin-bottom: 16px; }\n a { color: #0366d6; text-decoration: none; }\n a:hover { text-decoration: underline; }\n code { background: #f6f8fa; padding: 0.2em 0.4em; border-radius: 3px; font-family: 'SFMono-Regular', Consolas, monospace; font-size: 85%; }\n pre { background: #f6f8fa; padding: 16px; border-radius: 6px; overflow-x: auto; }\n pre code { background: transparent; padding: 0; }\n blockquote { border-left: 4px solid #dfe2e5; color: #6a737d; margin: 0; padding: 0 16px; }\n table { border-collapse: collapse; width: 100%; margin-bottom: 16px; }\n th, td { border: 1px solid #dfe2e5; padding: 6px 13px; }\n th { background: #f6f8fa; font-weight: 600; }\n tr:nth-child(even) { background: #f6f8fa; }\n ul, ol { padding-left: 2em; margin-bottom: 16px; }\n li { margin-bottom: 4px; }\n hr { border: none; border-top: 1px solid #eaecef; margin: 24px 0; }\n img { max-width: 100%; height: auto; }\n .task-list { list-style: none; padding-left: 0; }\n .task-list-item input { margin-right: 8px; }\n `,\n dark: `\n body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif; line-height: 1.6; color: #c9d1d9; background: #0d1117; max-width: 800px; margin: 0 auto; padding: 20px; }\n h1, h2, h3, h4, h5, h6 { margin-top: 24px; margin-bottom: 16px; font-weight: 600; line-height: 1.25; color: #c9d1d9; }\n h1 { font-size: 2em; border-bottom: 1px solid #21262d; padding-bottom: 0.3em; }\n h2 { font-size: 1.5em; border-bottom: 1px solid #21262d; padding-bottom: 0.3em; }\n h3 { font-size: 1.25em; }\n p { margin-bottom: 16px; }\n a { color: #58a6ff; text-decoration: none; }\n a:hover { text-decoration: underline; }\n code { background: #161b22; padding: 0.2em 0.4em; border-radius: 3px; font-family: 'SFMono-Regular', Consolas, monospace; font-size: 85%; }\n pre { background: #161b22; padding: 16px; border-radius: 6px; overflow-x: auto; }\n pre code { background: transparent; padding: 0; }\n blockquote { border-left: 4px solid #30363d; color: #8b949e; margin: 0; padding: 0 16px; }\n table { border-collapse: collapse; width: 100%; margin-bottom: 16px; }\n th, td { border: 1px solid #30363d; padding: 6px 13px; }\n th { background: #161b22; font-weight: 600; }\n tr:nth-child(even) { background: #161b22; }\n ul, ol { padding-left: 2em; margin-bottom: 16px; }\n li { margin-bottom: 4px; }\n hr { border: none; border-top: 1px solid #21262d; margin: 24px 0; }\n img { max-width: 100%; height: auto; }\n .task-list { list-style: none; padding-left: 0; }\n .task-list-item input { margin-right: 8px; }\n `,\n github: `\n body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif; line-height: 1.6; color: #24292e; max-width: 980px; margin: 0 auto; padding: 45px; }\n h1, h2, h3, h4, h5, h6 { margin-top: 24px; margin-bottom: 16px; font-weight: 600; line-height: 1.25; }\n h1 { font-size: 2em; border-bottom: 1px solid #eaecef; padding-bottom: 0.3em; }\n h2 { font-size: 1.5em; border-bottom: 1px solid #eaecef; padding-bottom: 0.3em; }\n h3 { font-size: 1.25em; }\n p { margin-bottom: 16px; }\n a { color: #0366d6; text-decoration: none; }\n a:hover { text-decoration: underline; }\n code { background: rgba(27,31,35,0.05); padding: 0.2em 0.4em; border-radius: 3px; font-family: 'SFMono-Regular', Consolas, monospace; font-size: 85%; }\n pre { background: #f6f8fa; padding: 16px; border-radius: 6px; overflow-x: auto; line-height: 1.45; }\n pre code { background: transparent; padding: 0; font-size: 100%; }\n blockquote { border-left: 4px solid #dfe2e5; color: #6a737d; margin: 0 0 16px 0; padding: 0 16px; }\n table { border-collapse: collapse; width: 100%; margin-bottom: 16px; }\n th, td { border: 1px solid #dfe2e5; padding: 6px 13px; }\n th { background: #f6f8fa; font-weight: 600; }\n tr:nth-child(even) { background: #f6f8fa; }\n ul, ol { padding-left: 2em; margin-bottom: 16px; }\n li { margin-bottom: 4px; }\n hr { border: none; height: 4px; background: #e1e4e8; margin: 24px 0; }\n img { max-width: 100%; height: auto; box-sizing: border-box; }\n .task-list { list-style: none; padding-left: 0; }\n .task-list-item input { margin-right: 8px; }\n `,\n};\n\n// Escape HTML\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n\n// Parse and render markdown to HTML\nexport function markdownToHtml(\n markdown: string,\n options: MarkdownRenderOptions = {}\n): string {\n const { syntaxHighlight = true } = options;\n\n let html = markdown;\n\n // Code blocks with syntax highlighting\n html = html.replace(/```(\\w*)\\n([\\s\\S]*?)```/g, (_, lang, code) => {\n if (syntaxHighlight && lang) {\n return highlightCode(code.trim(), { language: lang, theme: \"github\" });\n }\n return `<pre><code class=\"language-${lang}\">${escapeHtml(code.trim())}</code></pre>`;\n });\n\n // Inline code\n html = html.replace(/`([^`]+)`/g, \"<code>$1</code>\");\n\n // Headers\n html = html.replace(/^######\\s+(.+)$/gm, \"<h6>$1</h6>\");\n html = html.replace(/^#####\\s+(.+)$/gm, \"<h5>$1</h5>\");\n html = html.replace(/^####\\s+(.+)$/gm, \"<h4>$1</h4>\");\n html = html.replace(/^###\\s+(.+)$/gm, \"<h3>$1</h3>\");\n html = html.replace(/^##\\s+(.+)$/gm, \"<h2>$1</h2>\");\n html = html.replace(/^#\\s+(.+)$/gm, \"<h1>$1</h1>\");\n\n // Bold and italic\n html = html.replace(/\\*\\*\\*([^*]+)\\*\\*\\*/g, \"<strong><em>$1</em></strong>\");\n html = html.replace(/\\*\\*([^*]+)\\*\\*/g, \"<strong>$1</strong>\");\n html = html.replace(/\\*([^*]+)\\*/g, \"<em>$1</em>\");\n html = html.replace(/___([^_]+)___/g, \"<strong><em>$1</em></strong>\");\n html = html.replace(/__([^_]+)__/g, \"<strong>$1</strong>\");\n html = html.replace(/_([^_]+)_/g, \"<em>$1</em>\");\n\n // Strikethrough\n html = html.replace(/~~([^~]+)~~/g, \"<del>$1</del>\");\n\n // Links\n html = html.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, '<a href=\"$2\">$1</a>');\n\n // Images\n html = html.replace(/!\\[([^\\]]*)\\]\\(([^)]+)\\)/g, '<img src=\"$2\" alt=\"$1\">');\n\n // Blockquotes\n html = html.replace(/^>\\s+(.+)$/gm, \"<blockquote>$1</blockquote>\");\n // Merge consecutive blockquotes\n html = html.replace(/<\\/blockquote>\\n<blockquote>/g, \"\\n\");\n\n // Horizontal rules\n html = html.replace(/^---+$/gm, \"<hr>\");\n html = html.replace(/^\\*\\*\\*+$/gm, \"<hr>\");\n\n // Task lists\n html = html.replace(\n /^[-*]\\s+\\[x\\]\\s+(.+)$/gm,\n '<li class=\"task-list-item\"><input type=\"checkbox\" checked disabled> $1</li>'\n );\n html = html.replace(\n /^[-*]\\s+\\[\\s*\\]\\s+(.+)$/gm,\n '<li class=\"task-list-item\"><input type=\"checkbox\" disabled> $1</li>'\n );\n\n // Unordered lists\n html = html.replace(/^[-*]\\s+(.+)$/gm, \"<li>$1</li>\");\n // Wrap consecutive list items\n html = html.replace(/(<li>[\\s\\S]*?<\\/li>)\\n(?=<li>)/g, \"$1\");\n html = html.replace(/(<li>[\\s\\S]*?<\\/li>)(?!\\n<li>)/g, \"<ul>$1</ul>\");\n\n // Ordered lists\n html = html.replace(/^\\d+\\.\\s+(.+)$/gm, \"<li>$1</li>\");\n\n // Tables\n html = html.replace(\n /^\\|(.+)\\|\\n\\|[-:| ]+\\|\\n((?:\\|.+\\|\\n?)+)/gm,\n (_, headerRow, bodyRows) => {\n const headers = headerRow\n .split(\"|\")\n .filter((h: string) => h.trim())\n .map((h: string) => `<th>${h.trim()}</th>`)\n .join(\"\");\n\n const rows = bodyRows\n .trim()\n .split(\"\\n\")\n .map((row: string) => {\n const cells = row\n .split(\"|\")\n .filter((c: string) => c.trim())\n .map((c: string) => `<td>${c.trim()}</td>`)\n .join(\"\");\n return `<tr>${cells}</tr>`;\n })\n .join(\"\");\n\n return `<table><thead><tr>${headers}</tr></thead><tbody>${rows}</tbody></table>`;\n }\n );\n\n // Paragraphs (wrap remaining text blocks)\n html = html.replace(/^(?!<[a-z]|$)(.+)$/gm, \"<p>$1</p>\");\n\n // Clean up empty paragraphs\n html = html.replace(/<p>\\s*<\\/p>/g, \"\");\n\n return html;\n}\n\n// Render markdown to complete HTML document\nexport async function renderMarkdown(\n markdown: string,\n filename?: string,\n options: MarkdownRenderOptions = {}\n): Promise<MarkdownRenderResult> {\n const { theme = \"github\", tableOfContents = false } = options;\n\n try {\n const bodyHtml = markdownToHtml(markdown, options);\n\n // Generate table of contents if requested\n let tocHtml = \"\";\n if (tableOfContents) {\n const headings = markdown.match(/^#{1,3}\\s+.+$/gm) || [];\n if (headings.length > 0) {\n tocHtml = '<nav class=\"toc\"><h2>Table of Contents</h2><ul>';\n for (const heading of headings) {\n const level = (heading.match(/^#+/) || [\"\"])[0].length;\n const text = heading.replace(/^#+\\s+/, \"\");\n const id = text.toLowerCase().replace(/\\s+/g, \"-\").replace(/[^\\w-]/g, \"\");\n tocHtml += `<li style=\"margin-left: ${(level - 1) * 20}px\"><a href=\"#${id}\">${escapeHtml(text)}</a></li>`;\n }\n tocHtml += \"</ul></nav>\";\n }\n }\n\n const fullHtml = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n <style>${THEMES[theme] || THEMES.github}</style>\n</head>\n<body>\n${tocHtml}\n${bodyHtml}\n</body>\n</html>`;\n\n if (filename) {\n const filePath = isPathAllowed(filename) ? filename : join(tmpdir(), filename);\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, fullHtml, \"utf-8\");\n\n return { success: true, html: fullHtml, filePath };\n }\n\n return { success: true, html: fullHtml };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport default {\n markdownToHtml,\n renderMarkdown,\n};\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport OpenAI from \"openai\";\nimport { env } from \"../config/env\";\nimport { isPathAllowed, getSafeExtension } from \"../utils/paths\";\nimport { readFile, writeFile, unlink, mkdir, stat, readdir } from \"fs/promises\";\nimport { existsSync } from \"fs\";\nimport { join, dirname, basename } from \"path\";\nimport { spawn } from \"child_process\";\nimport { tmpdir } from \"os\";\nimport { randomUUID } from \"crypto\";\n\nconst anthropic = new Anthropic({\n apiKey: env.CLAUDE_API_KEY,\n});\n\nconst openai = new OpenAI({\n apiKey: env.OPENAI_API_KEY,\n});\n\n// Supported video formats\nconst SUPPORTED_VIDEO_FORMATS = [\".mp4\", \".avi\", \".mkv\", \".mov\", \".webm\", \".m4v\", \".flv\", \".wmv\"];\n\n// Frame extraction settings\nconst DEFAULT_FRAME_COUNT = 8; // Number of keyframes to extract\nconst MAX_FRAME_COUNT = 20;\nconst FRAME_QUALITY = 90; // JPEG quality 1-100\n\nexport interface VideoSummarizationResult {\n success: boolean;\n summary?: VideoSummary;\n error?: string;\n}\n\nexport interface VideoSummary {\n title: string;\n duration: number; // in seconds\n overview: string;\n keyMoments: KeyMoment[];\n transcript?: string;\n topics: string[];\n sentiment: \"positive\" | \"neutral\" | \"negative\" | \"mixed\";\n contentType: VideoContentType;\n metadata: VideoMetadata;\n}\n\nexport interface KeyMoment {\n timestamp: number; // in seconds\n description: string;\n frameAnalysis?: string;\n}\n\nexport interface VideoMetadata {\n width: number;\n height: number;\n frameRate: number;\n codec: string;\n bitrate?: number;\n fileSize: number;\n hasAudio: boolean;\n}\n\nexport type VideoContentType =\n | \"tutorial\"\n | \"presentation\"\n | \"interview\"\n | \"documentary\"\n | \"entertainment\"\n | \"news\"\n | \"meeting\"\n | \"lecture\"\n | \"vlog\"\n | \"other\";\n\nexport interface VideoSummarizationOptions {\n frameCount?: number;\n includeTranscript?: boolean;\n analysisDepth?: \"quick\" | \"standard\" | \"detailed\";\n language?: string;\n focusAreas?: string[]; // Specific aspects to focus on\n}\n\n// Execute ffmpeg/ffprobe commands\nasync function execCommand(command: string, args: string[]): Promise<{ stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n const proc = spawn(command, args);\n let stdout = \"\";\n let stderr = \"\";\n\n proc.stdout.on(\"data\", (data) => {\n stdout += data.toString();\n });\n\n proc.stderr.on(\"data\", (data) => {\n stderr += data.toString();\n });\n\n proc.on(\"close\", (code) => {\n if (code === 0) {\n resolve({ stdout, stderr });\n } else {\n reject(new Error(`${command} exited with code ${code}: ${stderr}`));\n }\n });\n\n proc.on(\"error\", (error) => {\n reject(error);\n });\n });\n}\n\n// Get video metadata using ffprobe\nasync function getVideoMetadata(videoPath: string): Promise<VideoMetadata> {\n try {\n const { stdout } = await execCommand(\"ffprobe\", [\n \"-v\", \"quiet\",\n \"-print_format\", \"json\",\n \"-show_format\",\n \"-show_streams\",\n videoPath,\n ]);\n\n const probeData = JSON.parse(stdout);\n const videoStream = probeData.streams?.find((s: { codec_type: string }) => s.codec_type === \"video\");\n const audioStream = probeData.streams?.find((s: { codec_type: string }) => s.codec_type === \"audio\");\n const format = probeData.format || {};\n\n const fileStat = await stat(videoPath);\n\n return {\n width: videoStream?.width || 0,\n height: videoStream?.height || 0,\n frameRate: videoStream?.r_frame_rate ? parseFrameRate(videoStream.r_frame_rate) : 0,\n codec: videoStream?.codec_name || \"unknown\",\n bitrate: format.bit_rate ? parseInt(format.bit_rate, 10) : undefined,\n fileSize: fileStat.size,\n hasAudio: !!audioStream,\n };\n } catch (error) {\n // Return minimal metadata on error\n const fileStat = await stat(videoPath);\n return {\n width: 0,\n height: 0,\n frameRate: 0,\n codec: \"unknown\",\n fileSize: fileStat.size,\n hasAudio: false,\n };\n }\n}\n\n// Parse frame rate string (e.g., \"30/1\" or \"29.97\")\nfunction parseFrameRate(frameRateStr: string): number {\n if (frameRateStr.includes(\"/\")) {\n const [num, den] = frameRateStr.split(\"/\").map(Number);\n return den > 0 ? num / den : 0;\n }\n return parseFloat(frameRateStr) || 0;\n}\n\n// Get video duration using ffprobe\nasync function getVideoDuration(videoPath: string): Promise<number> {\n try {\n const { stdout } = await execCommand(\"ffprobe\", [\n \"-v\", \"error\",\n \"-show_entries\", \"format=duration\",\n \"-of\", \"default=noprint_wrappers=1:nokey=1\",\n videoPath,\n ]);\n\n return parseFloat(stdout.trim()) || 0;\n } catch {\n return 0;\n }\n}\n\n// Extract frames from video at specific intervals\nasync function extractFrames(\n videoPath: string,\n outputDir: string,\n frameCount: number\n): Promise<string[]> {\n const duration = await getVideoDuration(videoPath);\n if (duration <= 0) {\n throw new Error(\"Could not determine video duration\");\n }\n\n // Calculate frame timestamps (evenly distributed)\n const actualFrameCount = Math.min(frameCount, MAX_FRAME_COUNT);\n const interval = duration / (actualFrameCount + 1);\n const framePaths: string[] = [];\n\n // Create output directory\n await mkdir(outputDir, { recursive: true });\n\n // Extract frames at calculated timestamps\n for (let i = 1; i <= actualFrameCount; i++) {\n const timestamp = interval * i;\n const outputPath = join(outputDir, `frame_${String(i).padStart(3, \"0\")}.jpg`);\n\n try {\n await execCommand(\"ffmpeg\", [\n \"-ss\", timestamp.toString(),\n \"-i\", videoPath,\n \"-vframes\", \"1\",\n \"-q:v\", String(Math.max(1, 31 - Math.floor(FRAME_QUALITY / 3.5))),\n \"-y\",\n outputPath,\n ]);\n\n if (existsSync(outputPath)) {\n framePaths.push(outputPath);\n }\n } catch {\n // Continue with other frames if one fails\n console.warn(`Failed to extract frame at ${timestamp}s`);\n }\n }\n\n return framePaths;\n}\n\n// Extract audio from video for transcription\nasync function extractAudio(videoPath: string, outputPath: string): Promise<boolean> {\n try {\n await execCommand(\"ffmpeg\", [\n \"-i\", videoPath,\n \"-vn\",\n \"-acodec\", \"libmp3lame\",\n \"-ar\", \"16000\",\n \"-ac\", \"1\",\n \"-y\",\n outputPath,\n ]);\n\n return existsSync(outputPath);\n } catch {\n return false;\n }\n}\n\n// Transcribe audio using OpenAI Whisper\nasync function transcribeAudio(\n audioPath: string,\n language?: string\n): Promise<string | null> {\n try {\n const audioBuffer = await readFile(audioPath);\n const uint8Array = new Uint8Array(audioBuffer);\n const file = new File([uint8Array], \"audio.mp3\", { type: \"audio/mpeg\" });\n\n const response = await openai.audio.transcriptions.create({\n file,\n model: \"whisper-1\",\n language: language || \"en\",\n response_format: \"text\",\n });\n\n return response;\n } catch (error) {\n console.error(\"Transcription error:\", error);\n return null;\n }\n}\n\n// Analyze a single frame using Claude Vision\nasync function analyzeFrame(\n framePath: string,\n timestamp: number,\n context: string\n): Promise<string> {\n try {\n const imageData = await readFile(framePath);\n const base64 = imageData.toString(\"base64\");\n\n const response = await anthropic.messages.create({\n model: \"claude-sonnet-4-20250514\",\n max_tokens: 500,\n messages: [\n {\n role: \"user\",\n content: [\n {\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: \"image/jpeg\",\n data: base64,\n },\n },\n {\n type: \"text\",\n text: `Analyze this video frame from timestamp ${formatTimestamp(timestamp)}. Context: ${context}. Describe what's happening, any text visible, key visual elements, and the apparent activity or scene.`,\n },\n ],\n },\n ],\n });\n\n const textContent = response.content.find((c) => c.type === \"text\");\n return textContent?.type === \"text\" ? textContent.text : \"Unable to analyze frame\";\n } catch (error) {\n return `Frame analysis failed: ${error instanceof Error ? error.message : \"Unknown error\"}`;\n }\n}\n\n// Analyze multiple frames together for efficiency\nasync function analyzeFramesBatch(\n framePaths: string[],\n duration: number\n): Promise<KeyMoment[]> {\n const keyMoments: KeyMoment[] = [];\n const interval = duration / (framePaths.length + 1);\n\n // Process frames in parallel batches of 4\n const batchSize = 4;\n for (let i = 0; i < framePaths.length; i += batchSize) {\n const batch = framePaths.slice(i, i + batchSize);\n const batchPromises = batch.map(async (framePath, batchIndex) => {\n const frameIndex = i + batchIndex;\n const timestamp = interval * (frameIndex + 1);\n const analysis = await analyzeFrame(\n framePath,\n timestamp,\n `Frame ${frameIndex + 1} of ${framePaths.length} from a video`\n );\n\n return {\n timestamp,\n description: analysis.slice(0, 500), // Limit description length\n frameAnalysis: analysis,\n };\n });\n\n const batchResults = await Promise.all(batchPromises);\n keyMoments.push(...batchResults);\n }\n\n return keyMoments;\n}\n\n// Format timestamp for display\nfunction formatTimestamp(seconds: number): string {\n const hours = Math.floor(seconds / 3600);\n const minutes = Math.floor((seconds % 3600) / 60);\n const secs = Math.floor(seconds % 60);\n\n if (hours > 0) {\n return `${hours}:${String(minutes).padStart(2, \"0\")}:${String(secs).padStart(2, \"0\")}`;\n }\n return `${minutes}:${String(secs).padStart(2, \"0\")}`;\n}\n\n// Generate comprehensive summary using Claude\nasync function generateSummary(\n keyMoments: KeyMoment[],\n transcript: string | null,\n metadata: VideoMetadata,\n duration: number,\n options: VideoSummarizationOptions\n): Promise<Omit<VideoSummary, \"keyMoments\" | \"metadata\" | \"duration\">> {\n const frameDescriptions = keyMoments\n .map((m) => `[${formatTimestamp(m.timestamp)}] ${m.description}`)\n .join(\"\\n\");\n\n const prompt = `Analyze this video based on the following information:\n\n## Frame Analysis (${keyMoments.length} keyframes):\n${frameDescriptions}\n\n${transcript ? `## Transcript:\\n${transcript.slice(0, 10000)}` : \"## No audio transcript available\"}\n\n## Video Info:\n- Duration: ${formatTimestamp(duration)}\n- Resolution: ${metadata.width}x${metadata.height}\n- Has Audio: ${metadata.hasAudio}\n\n${options.focusAreas?.length ? `## Focus Areas: ${options.focusAreas.join(\", \")}` : \"\"}\n\nBased on this information, provide a comprehensive analysis in JSON format:\n{\n \"title\": \"A descriptive title for the video\",\n \"overview\": \"A 2-3 paragraph summary of the video content\",\n \"topics\": [\"topic1\", \"topic2\", \"topic3\"],\n \"contentType\": \"one of: tutorial, presentation, interview, documentary, entertainment, news, meeting, lecture, vlog, other\",\n \"sentiment\": \"one of: positive, neutral, negative, mixed\"\n}\n\n${options.analysisDepth === \"detailed\" ? \"Provide extra detail in the overview.\" : \"\"}\n${options.analysisDepth === \"quick\" ? \"Keep the overview brief, 1-2 sentences.\" : \"\"}`;\n\n try {\n const response = await anthropic.messages.create({\n model: \"claude-sonnet-4-20250514\",\n max_tokens: 2000,\n messages: [\n {\n role: \"user\",\n content: prompt,\n },\n ],\n });\n\n const textContent = response.content.find((c) => c.type === \"text\");\n const responseText = textContent?.type === \"text\" ? textContent.text : \"\";\n\n // Extract JSON from response\n const jsonMatch = responseText.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n const parsed = JSON.parse(jsonMatch[0]);\n return {\n title: parsed.title || \"Untitled Video\",\n overview: parsed.overview || \"No overview available\",\n topics: parsed.topics || [],\n contentType: parsed.contentType || \"other\",\n sentiment: parsed.sentiment || \"neutral\",\n transcript: transcript || undefined,\n };\n }\n } catch (error) {\n console.error(\"Summary generation error:\", error);\n }\n\n // Fallback summary\n return {\n title: \"Video Analysis\",\n overview: `This video is ${formatTimestamp(duration)} long and contains ${keyMoments.length} analyzed segments.`,\n topics: [],\n contentType: \"other\",\n sentiment: \"neutral\",\n transcript: transcript || undefined,\n };\n}\n\n// Clean up temporary files\nasync function cleanup(tempDir: string): Promise<void> {\n try {\n const files = await readdir(tempDir);\n await Promise.all(files.map((f) => unlink(join(tempDir, f))));\n await unlink(tempDir).catch(() => {}); // Remove directory\n } catch {\n // Ignore cleanup errors\n }\n}\n\n// Main video summarization function\nexport async function summarizeVideo(\n videoPath: string,\n options: VideoSummarizationOptions = {}\n): Promise<VideoSummarizationResult> {\n // Validate path\n if (!isPathAllowed(videoPath)) {\n return {\n success: false,\n error: \"Access to this path is not allowed\",\n };\n }\n\n // Check file exists\n if (!existsSync(videoPath)) {\n return {\n success: false,\n error: \"Video file not found\",\n };\n }\n\n // Validate format\n const ext = getSafeExtension(videoPath);\n if (!SUPPORTED_VIDEO_FORMATS.includes(ext)) {\n return {\n success: false,\n error: `Unsupported video format: ${ext}. Supported: ${SUPPORTED_VIDEO_FORMATS.join(\", \")}`,\n };\n }\n\n const tempDir = join(tmpdir(), `sentinel-video-${randomUUID()}`);\n\n try {\n await mkdir(tempDir, { recursive: true });\n\n // Get video metadata\n const metadata = await getVideoMetadata(videoPath);\n const duration = await getVideoDuration(videoPath);\n\n if (duration <= 0) {\n return {\n success: false,\n error: \"Could not determine video duration\",\n };\n }\n\n // Extract frames\n const frameCount = options.frameCount || DEFAULT_FRAME_COUNT;\n const framePaths = await extractFrames(videoPath, tempDir, frameCount);\n\n if (framePaths.length === 0) {\n return {\n success: false,\n error: \"Failed to extract frames from video\",\n };\n }\n\n // Transcribe audio if requested and available\n let transcript: string | null = null;\n if (options.includeTranscript !== false && metadata.hasAudio) {\n const audioPath = join(tempDir, \"audio.mp3\");\n const audioExtracted = await extractAudio(videoPath, audioPath);\n\n if (audioExtracted) {\n transcript = await transcribeAudio(audioPath, options.language);\n }\n }\n\n // Analyze frames\n const keyMoments = await analyzeFramesBatch(framePaths, duration);\n\n // Generate comprehensive summary\n const summaryData = await generateSummary(\n keyMoments,\n transcript,\n metadata,\n duration,\n options\n );\n\n // Build final summary\n const summary: VideoSummary = {\n ...summaryData,\n duration,\n keyMoments,\n metadata,\n };\n\n // Cleanup temp files\n await cleanup(tempDir);\n\n return {\n success: true,\n summary,\n };\n } catch (error) {\n // Cleanup on error\n await cleanup(tempDir);\n\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n// Quick summary (fewer frames, no transcript)\nexport async function quickSummarizeVideo(\n videoPath: string\n): Promise<VideoSummarizationResult> {\n return summarizeVideo(videoPath, {\n frameCount: 4,\n includeTranscript: false,\n analysisDepth: \"quick\",\n });\n}\n\n// Detailed summary (more frames, full transcript)\nexport async function detailedSummarizeVideo(\n videoPath: string,\n language?: string\n): Promise<VideoSummarizationResult> {\n return summarizeVideo(videoPath, {\n frameCount: 16,\n includeTranscript: true,\n analysisDepth: \"detailed\",\n language,\n });\n}\n\n// Extract key moments only (no full summary)\nexport async function extractKeyMoments(\n videoPath: string,\n frameCount: number = 8\n): Promise<{ success: boolean; moments?: KeyMoment[]; error?: string }> {\n if (!isPathAllowed(videoPath)) {\n return { success: false, error: \"Access to this path is not allowed\" };\n }\n\n if (!existsSync(videoPath)) {\n return { success: false, error: \"Video file not found\" };\n }\n\n const tempDir = join(tmpdir(), `sentinel-video-${randomUUID()}`);\n\n try {\n await mkdir(tempDir, { recursive: true });\n const duration = await getVideoDuration(videoPath);\n const framePaths = await extractFrames(videoPath, tempDir, frameCount);\n const moments = await analyzeFramesBatch(framePaths, duration);\n\n await cleanup(tempDir);\n\n return { success: true, moments };\n } catch (error) {\n await cleanup(tempDir);\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n// Get video information without full analysis\nexport async function getVideoInfo(\n videoPath: string\n): Promise<{ success: boolean; info?: VideoMetadata & { duration: number }; error?: string }> {\n if (!isPathAllowed(videoPath)) {\n return { success: false, error: \"Access to this path is not allowed\" };\n }\n\n if (!existsSync(videoPath)) {\n return { success: false, error: \"Video file not found\" };\n }\n\n try {\n const metadata = await getVideoMetadata(videoPath);\n const duration = await getVideoDuration(videoPath);\n\n return {\n success: true,\n info: { ...metadata, duration },\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport default {\n summarizeVideo,\n quickSummarizeVideo,\n detailedSummarizeVideo,\n extractKeyMoments,\n getVideoInfo,\n SUPPORTED_VIDEO_FORMATS,\n};\n","// Apply unified diff patches to files\n\nimport { readFile, writeFile, copyFile } from \"fs/promises\";\nimport { existsSync } from \"fs\";\n\ninterface PatchResult {\n applied: boolean;\n linesChanged: number;\n backup?: string;\n error?: string;\n}\n\ninterface HunkHeader {\n oldStart: number;\n oldCount: number;\n newStart: number;\n newCount: number;\n}\n\nfunction parseHunkHeader(line: string): HunkHeader | null {\n const match = line.match(/^@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/);\n if (!match) return null;\n return {\n oldStart: parseInt(match[1], 10),\n oldCount: match[2] !== undefined ? parseInt(match[2], 10) : 1,\n newStart: parseInt(match[3], 10),\n newCount: match[4] !== undefined ? parseInt(match[4], 10) : 1,\n };\n}\n\ninterface Hunk {\n header: HunkHeader;\n lines: string[];\n}\n\nfunction parseUnifiedDiff(patch: string): Hunk[] {\n const lines = patch.split(\"\\n\");\n const hunks: Hunk[] = [];\n let currentHunk: Hunk | null = null;\n\n for (const line of lines) {\n // Skip file headers\n if (line.startsWith(\"---\") || line.startsWith(\"+++\") || line.startsWith(\"diff \")) {\n continue;\n }\n\n const hunkHeader = parseHunkHeader(line);\n if (hunkHeader) {\n if (currentHunk) hunks.push(currentHunk);\n currentHunk = { header: hunkHeader, lines: [] };\n continue;\n }\n\n if (currentHunk && (line.startsWith(\"+\") || line.startsWith(\"-\") || line.startsWith(\" \") || line === \"\")) {\n currentHunk.lines.push(line);\n }\n }\n\n if (currentHunk) hunks.push(currentHunk);\n return hunks;\n}\n\nfunction applyHunks(originalLines: string[], hunks: Hunk[]): string[] | null {\n const result = [...originalLines];\n let offset = 0;\n\n for (const hunk of hunks) {\n const startLine = hunk.header.oldStart - 1 + offset;\n const oldLines: string[] = [];\n const newLines: string[] = [];\n\n for (const line of hunk.lines) {\n if (line.startsWith(\"-\")) {\n oldLines.push(line.substring(1));\n } else if (line.startsWith(\"+\")) {\n newLines.push(line.substring(1));\n } else if (line.startsWith(\" \")) {\n oldLines.push(line.substring(1));\n newLines.push(line.substring(1));\n } else if (line === \"\") {\n // Empty context line\n oldLines.push(\"\");\n newLines.push(\"\");\n }\n }\n\n // Verify context matches\n for (let i = 0; i < oldLines.length; i++) {\n const resultIdx = startLine + i;\n if (resultIdx >= result.length) break;\n if (result[resultIdx] !== oldLines[i]) {\n // Try fuzzy match (ignore trailing whitespace)\n if (result[resultIdx]?.trimEnd() !== oldLines[i]?.trimEnd()) {\n return null; // Context mismatch\n }\n }\n }\n\n // Apply the replacement\n result.splice(startLine, oldLines.length, ...newLines);\n offset += newLines.length - oldLines.length;\n }\n\n return result;\n}\n\nexport async function applyPatch(\n filePath: string,\n patchContent: string,\n createBackup: boolean = true\n): Promise<PatchResult> {\n try {\n // Read original file\n if (!existsSync(filePath)) {\n return { applied: false, linesChanged: 0, error: `File not found: ${filePath}` };\n }\n\n const original = await readFile(filePath, \"utf-8\");\n const originalLines = original.split(\"\\n\");\n\n // Parse the patch\n const hunks = parseUnifiedDiff(patchContent);\n if (hunks.length === 0) {\n return { applied: false, linesChanged: 0, error: \"No valid hunks found in patch\" };\n }\n\n // Apply hunks\n const patched = applyHunks(originalLines, hunks);\n if (!patched) {\n return { applied: false, linesChanged: 0, error: \"Patch context does not match file content\" };\n }\n\n // Create backup if requested\n let backupPath: string | undefined;\n if (createBackup) {\n backupPath = `${filePath}.bak`;\n await copyFile(filePath, backupPath);\n }\n\n // Write patched content\n await writeFile(filePath, patched.join(\"\\n\"), \"utf-8\");\n\n // Count changed lines\n const linesChanged = Math.abs(patched.length - originalLines.length) +\n hunks.reduce((sum, h) => sum + h.lines.filter((l) => l.startsWith(\"+\") || l.startsWith(\"-\")).length, 0);\n\n return {\n applied: true,\n linesChanged,\n backup: backupPath,\n };\n } catch (error) {\n return {\n applied: false,\n linesChanged: 0,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n","// Cross-platform poll creation and voting system\n\nimport { randomUUID } from \"crypto\";\n\nexport interface PollOption {\n text: string;\n votes: Set<string>; // user IDs\n}\n\nexport interface Poll {\n id: string;\n question: string;\n options: PollOption[];\n multiSelect: boolean;\n createdBy: string;\n createdAt: Date;\n closesAt?: Date;\n closed: boolean;\n channelType: string;\n channelId: string;\n messageRef?: string; // platform message ID for updating\n}\n\nexport interface PollResults {\n id: string;\n question: string;\n totalVotes: number;\n options: Array<{\n text: string;\n votes: number;\n percentage: number;\n voters: string[];\n }>;\n closed: boolean;\n}\n\n// Store polls in memory\nconst polls: Map<string, Poll> = new Map();\n\n// Auto-close timers\nconst closeTimers: Map<string, ReturnType<typeof setTimeout>> = new Map();\n\nexport class PollManager {\n createPoll(params: {\n question: string;\n options: string[];\n multiSelect?: boolean;\n duration?: number; // minutes\n channelType: string;\n channelId: string;\n createdBy: string;\n }): Poll {\n const id = randomUUID().slice(0, 8);\n\n const poll: Poll = {\n id,\n question: params.question,\n options: params.options.map((text) => ({\n text,\n votes: new Set(),\n })),\n multiSelect: params.multiSelect ?? false,\n createdBy: params.createdBy,\n createdAt: new Date(),\n closed: false,\n channelType: params.channelType,\n channelId: params.channelId,\n };\n\n if (params.duration) {\n poll.closesAt = new Date(Date.now() + params.duration * 60 * 1000);\n const timer = setTimeout(() => {\n this.closePoll(id);\n }, params.duration * 60 * 1000);\n closeTimers.set(id, timer);\n }\n\n polls.set(id, poll);\n return poll;\n }\n\n vote(\n pollId: string,\n optionIndex: number,\n userId: string\n ): { success: boolean; error?: string } {\n const poll = polls.get(pollId);\n if (!poll) return { success: false, error: \"Poll not found\" };\n if (poll.closed) return { success: false, error: \"Poll is closed\" };\n if (optionIndex < 0 || optionIndex >= poll.options.length) {\n return { success: false, error: \"Invalid option index\" };\n }\n\n // If not multi-select, remove existing votes\n if (!poll.multiSelect) {\n for (const option of poll.options) {\n option.votes.delete(userId);\n }\n }\n\n // Toggle vote\n const option = poll.options[optionIndex];\n if (option.votes.has(userId)) {\n option.votes.delete(userId);\n } else {\n option.votes.add(userId);\n }\n\n return { success: true };\n }\n\n closePoll(pollId: string): PollResults | null {\n const poll = polls.get(pollId);\n if (!poll) return null;\n\n poll.closed = true;\n\n // Clear auto-close timer\n const timer = closeTimers.get(pollId);\n if (timer) {\n clearTimeout(timer);\n closeTimers.delete(pollId);\n }\n\n return this.getPollResults(pollId);\n }\n\n getPollResults(pollId: string): PollResults | null {\n const poll = polls.get(pollId);\n if (!poll) return null;\n\n const totalVoters = new Set<string>();\n for (const option of poll.options) {\n for (const voter of option.votes) {\n totalVoters.add(voter);\n }\n }\n\n const totalVotes = totalVoters.size;\n\n return {\n id: poll.id,\n question: poll.question,\n totalVotes,\n options: poll.options.map((opt) => ({\n text: opt.text,\n votes: opt.votes.size,\n percentage: totalVotes > 0 ? Math.round((opt.votes.size / totalVotes) * 100) : 0,\n voters: [...opt.votes],\n })),\n closed: poll.closed,\n };\n }\n\n getPoll(pollId: string): Poll | undefined {\n return polls.get(pollId);\n }\n\n getActivePolls(channelId?: string): Poll[] {\n const active: Poll[] = [];\n for (const poll of polls.values()) {\n if (!poll.closed && (!channelId || poll.channelId === channelId)) {\n active.push(poll);\n }\n }\n return active;\n }\n\n deletePoll(pollId: string): boolean {\n const timer = closeTimers.get(pollId);\n if (timer) {\n clearTimeout(timer);\n closeTimers.delete(pollId);\n }\n return polls.delete(pollId);\n }\n\n formatPollMessage(pollId: string): string {\n const results = this.getPollResults(pollId);\n if (!results) return \"Poll not found\";\n\n const poll = polls.get(pollId)!;\n const lines: string[] = [];\n\n lines.push(`\\ud83d\\udcca **${results.question}**`);\n if (poll.multiSelect) lines.push(\"_(Multiple choices allowed)_\");\n lines.push(\"\");\n\n for (let i = 0; i < results.options.length; i++) {\n const opt = results.options[i];\n const bar = \"\\u2588\".repeat(Math.max(1, Math.round(opt.percentage / 5)));\n const emoji = `${i + 1}\\ufe0f\\u20e3`;\n lines.push(`${emoji} ${opt.text}`);\n lines.push(` ${bar} ${opt.votes} vote${opt.votes !== 1 ? \"s\" : \"\"} (${opt.percentage}%)`);\n }\n\n lines.push(\"\");\n lines.push(`\\ud83d\\udc65 ${results.totalVotes} total voter${results.totalVotes !== 1 ? \"s\" : \"\"}`);\n\n if (results.closed) {\n lines.push(\"\\ud83d\\udd12 _Poll closed_\");\n } else if (poll.closesAt) {\n const remaining = Math.max(0, Math.round((poll.closesAt.getTime() - Date.now()) / 60000));\n lines.push(`\\u23f0 Closes in ${remaining} minute${remaining !== 1 ? \"s\" : \"\"}`);\n }\n\n return lines.join(\"\\n\");\n }\n}\n\n// Singleton\nexport const pollManager = new PollManager();\n","// Skill registry — storage and retrieval for user-teachable skills\n\nimport { randomUUID } from \"crypto\";\n\nexport interface Skill {\n id: string;\n name: string;\n description: string;\n trigger: string; // slash command or keyword\n instructions: string; // system prompt for Claude\n tools: string[]; // allowed tool subset\n createdBy: string;\n createdAt: Date;\n updatedAt: Date;\n isPublic: boolean;\n tags: string[];\n usageCount: number;\n}\n\n// In-memory skill store (backed by Map, can be migrated to DB)\nconst skills: Map<string, Skill> = new Map();\n\nexport class SkillRegistry {\n registerSkill(params: {\n name: string;\n description: string;\n trigger?: string;\n instructions: string;\n tools?: string[];\n createdBy: string;\n isPublic?: boolean;\n tags?: string[];\n }): Skill {\n const id = randomUUID().slice(0, 8);\n const trigger = params.trigger ?? `/${params.name.toLowerCase().replace(/\\s+/g, \"-\")}`;\n\n const skill: Skill = {\n id,\n name: params.name,\n description: params.description,\n trigger,\n instructions: params.instructions,\n tools: params.tools ?? [],\n createdBy: params.createdBy,\n createdAt: new Date(),\n updatedAt: new Date(),\n isPublic: params.isPublic ?? false,\n tags: params.tags ?? [],\n usageCount: 0,\n };\n\n skills.set(id, skill);\n return skill;\n }\n\n getSkill(nameOrId: string): Skill | undefined {\n // Direct ID lookup\n if (skills.has(nameOrId)) return skills.get(nameOrId);\n\n // Search by name or trigger\n for (const skill of skills.values()) {\n if (\n skill.name.toLowerCase() === nameOrId.toLowerCase() ||\n skill.trigger.toLowerCase() === nameOrId.toLowerCase() ||\n skill.trigger.toLowerCase() === `/${nameOrId.toLowerCase()}`\n ) {\n return skill;\n }\n }\n return undefined;\n }\n\n listSkills(userId?: string): Skill[] {\n const result: Skill[] = [];\n for (const skill of skills.values()) {\n if (!userId || skill.isPublic || skill.createdBy === userId) {\n result.push(skill);\n }\n }\n return result.sort((a, b) => b.usageCount - a.usageCount);\n }\n\n deleteSkill(id: string, userId?: string): boolean {\n const skill = skills.get(id);\n if (!skill) return false;\n if (userId && skill.createdBy !== userId) return false;\n return skills.delete(id);\n }\n\n updateSkill(\n id: string,\n updates: Partial<Pick<Skill, \"name\" | \"description\" | \"trigger\" | \"instructions\" | \"tools\" | \"isPublic\" | \"tags\">>\n ): Skill | null {\n const skill = skills.get(id);\n if (!skill) return null;\n\n Object.assign(skill, updates, { updatedAt: new Date() });\n return skill;\n }\n\n incrementUsage(id: string): void {\n const skill = skills.get(id);\n if (skill) skill.usageCount++;\n }\n\n exportSkill(id: string): string | null {\n const skill = skills.get(id);\n if (!skill) return null;\n\n return JSON.stringify(\n {\n name: skill.name,\n description: skill.description,\n trigger: skill.trigger,\n instructions: skill.instructions,\n tools: skill.tools,\n tags: skill.tags,\n isPublic: skill.isPublic,\n exportedAt: new Date().toISOString(),\n },\n null,\n 2\n );\n }\n\n importSkill(json: string, userId: string): Skill | null {\n try {\n const data = JSON.parse(json);\n if (!data.name || !data.instructions) return null;\n\n return this.registerSkill({\n name: data.name,\n description: data.description ?? \"\",\n trigger: data.trigger,\n instructions: data.instructions,\n tools: data.tools,\n createdBy: userId,\n isPublic: data.isPublic ?? false,\n tags: data.tags ?? [],\n });\n } catch {\n return null;\n }\n }\n\n searchSkills(query: string): Skill[] {\n const lower = query.toLowerCase();\n return this.listSkills().filter(\n (s) =>\n s.name.toLowerCase().includes(lower) ||\n s.description.toLowerCase().includes(lower) ||\n s.tags.some((t) => t.toLowerCase().includes(lower))\n );\n }\n\n getSkillCount(): number {\n return skills.size;\n }\n}\n\n// Singleton\nexport const skillRegistry = new SkillRegistry();\n","// Skill executor — runs a skill by building a system prompt and calling Claude\n\nimport type { Skill } from \"./skill-registry\";\nimport { skillRegistry } from \"./skill-registry\";\n\nexport interface SkillExecutionResult {\n success: boolean;\n output: string;\n skillId: string;\n skillName: string;\n tokensUsed?: number;\n error?: string;\n}\n\nexport class SkillExecutor {\n /**\n * Build a system prompt from a skill's instructions\n */\n buildSystemPrompt(skill: Skill, userInput?: string): string {\n const parts: string[] = [];\n\n parts.push(`[SKILL: ${skill.name}]`);\n parts.push(`Description: ${skill.description}`);\n parts.push(\"\");\n parts.push(\"Instructions:\");\n parts.push(skill.instructions);\n\n if (skill.tools.length > 0) {\n parts.push(\"\");\n parts.push(`Allowed tools: ${skill.tools.join(\", \")}`);\n parts.push(\"Only use the tools listed above.\");\n }\n\n if (userInput) {\n parts.push(\"\");\n parts.push(`User input: ${userInput}`);\n }\n\n return parts.join(\"\\n\");\n }\n\n /**\n * Execute a skill with user input.\n * In a full implementation, this calls chatWithTools() with the skill's\n * allowed tools. For now, returns the constructed prompt for the brain\n * module to execute.\n */\n async execute(\n skillNameOrId: string,\n userInput: string,\n userId: string\n ): Promise<SkillExecutionResult> {\n const skill = skillRegistry.getSkill(skillNameOrId);\n if (!skill) {\n return {\n success: false,\n output: \"\",\n skillId: \"\",\n skillName: skillNameOrId,\n error: `Skill not found: ${skillNameOrId}`,\n };\n }\n\n // Track usage\n skillRegistry.incrementUsage(skill.id);\n\n // Build system prompt\n const systemPrompt = this.buildSystemPrompt(skill, userInput);\n\n // The actual Claude call is delegated to brain.ts\n // This returns the prompt context for integration\n return {\n success: true,\n output: systemPrompt,\n skillId: skill.id,\n skillName: skill.name,\n };\n }\n\n /**\n * Interactively teach a new skill by asking the user questions\n */\n async teachSkill(params: {\n name: string;\n description: string;\n instructions: string;\n tools?: string[];\n userId: string;\n }): Promise<SkillExecutionResult> {\n const skill = skillRegistry.registerSkill({\n name: params.name,\n description: params.description,\n instructions: params.instructions,\n tools: params.tools,\n createdBy: params.userId,\n isPublic: false,\n });\n\n return {\n success: true,\n output: `Skill \"${skill.name}\" created with trigger \"${skill.trigger}\"`,\n skillId: skill.id,\n skillName: skill.name,\n };\n }\n}\n\n// Singleton\nexport const skillExecutor = new SkillExecutor();\n","// Built-in starter skills shipped with OpenSentinel\n\nexport interface BuiltinSkillDef {\n name: string;\n description: string;\n trigger: string;\n instructions: string;\n tools: string[];\n tags: string[];\n category: \"productivity\" | \"development\" | \"research\" | \"communication\" | \"utility\";\n}\n\nexport const BUILTIN_SKILLS: BuiltinSkillDef[] = [\n {\n name: \"Summarize Webpage\",\n description: \"Summarize any webpage URL into key points\",\n trigger: \"/summarize-url\",\n instructions: `Given a URL, browse to it and create a concise summary with:\n1. A one-sentence TL;DR\n2. 3-5 key points as bullet points\n3. Any important dates, numbers, or names mentioned\nKeep the summary under 200 words.`,\n tools: [\"browse_url\", \"web_search\"],\n tags: [\"research\", \"summary\", \"web\"],\n category: \"research\",\n },\n {\n name: \"Daily Briefing\",\n description: \"Generate a personalized daily briefing with news, weather, and tasks\",\n trigger: \"/briefing\",\n instructions: `Generate a concise daily briefing that includes:\n1. Top 3 news headlines (use web search)\n2. Weather summary for the user's location\n3. Any scheduled tasks or reminders for today\n4. A motivational quote\nFormat as a clean, scannable message with emojis for sections.`,\n tools: [\"web_search\", \"browse_url\"],\n tags: [\"daily\", \"news\", \"productivity\"],\n category: \"productivity\",\n },\n {\n name: \"Code Review\",\n description: \"Review a code file for bugs, style issues, and improvements\",\n trigger: \"/review\",\n instructions: `Review the provided code file or snippet. Analyze for:\n1. Bugs and potential runtime errors\n2. Security vulnerabilities (injection, XSS, etc.)\n3. Performance issues\n4. Code style and readability\n5. Missing error handling\nRate severity (critical/warning/info) for each finding.\nProvide specific line numbers and suggested fixes.`,\n tools: [\"read_file\"],\n tags: [\"code\", \"review\", \"development\"],\n category: \"development\",\n },\n {\n name: \"Meeting Notes\",\n description: \"Structure raw meeting notes into organized action items\",\n trigger: \"/meeting-notes\",\n instructions: `Transform raw meeting notes or a transcript into structured output:\n1. **Meeting Summary** - 2-3 sentence overview\n2. **Key Decisions** - Bulleted list of decisions made\n3. **Action Items** - Each with owner, deadline, and description\n4. **Open Questions** - Unresolved items needing follow-up\n5. **Next Steps** - What happens next\nFormat clearly with markdown headers.`,\n tools: [\"read_file\", \"write_file\"],\n tags: [\"meeting\", \"notes\", \"productivity\"],\n category: \"productivity\",\n },\n {\n name: \"Explain Like I'm 5\",\n description: \"Explain any concept in simple, easy-to-understand terms\",\n trigger: \"/eli5\",\n instructions: `Explain the given concept in the simplest possible terms:\n- Use everyday analogies and metaphors\n- Avoid technical jargon entirely\n- Use short sentences\n- Include a fun real-world comparison\n- Keep it under 100 words\n- End with \"In other words: [one-sentence summary]\"`,\n tools: [\"web_search\"],\n tags: [\"explain\", \"learning\", \"simple\"],\n category: \"utility\",\n },\n {\n name: \"Quick Email Draft\",\n description: \"Draft a professional email from a brief description\",\n trigger: \"/draft-email\",\n instructions: `Draft a professional email based on the user's description:\n- Infer appropriate tone (formal, friendly, urgent) from context\n- Include subject line suggestion\n- Keep it concise but complete\n- Include proper greeting and closing\n- If the user mentions a recipient or context, adapt accordingly\nOutput format: Subject, Body, optional PS/follow-up note.`,\n tools: [],\n tags: [\"email\", \"writing\", \"communication\"],\n category: \"communication\",\n },\n {\n name: \"Git Changelog\",\n description: \"Generate a changelog from recent git commits\",\n trigger: \"/changelog\",\n instructions: `Generate a formatted changelog from git history:\n1. Run git log to get recent commits\n2. Group commits by type (feat, fix, refactor, docs, etc.)\n3. Format as a markdown changelog with categories\n4. Include commit hashes as references\n5. Highlight breaking changes prominently\nFormat following Keep a Changelog conventions.`,\n tools: [\"execute_command\"],\n tags: [\"git\", \"changelog\", \"development\"],\n category: \"development\",\n },\n {\n name: \"Research Topic\",\n description: \"Deep-dive research on any topic with sources\",\n trigger: \"/research\",\n instructions: `Conduct thorough research on the given topic:\n1. Search for multiple sources\n2. Synthesize findings into a structured report\n3. Include: Overview, Key Facts, Different Perspectives, Recent Developments\n4. Cite sources with URLs\n5. Note confidence level for each claim\n6. Flag any conflicting information\nKeep the report focused and under 500 words.`,\n tools: [\"web_search\", \"browse_url\"],\n tags: [\"research\", \"analysis\", \"deep-dive\"],\n category: \"research\",\n },\n {\n name: \"Screenshot Analysis\",\n description: \"Take a screenshot and describe what's on screen\",\n trigger: \"/what-on-screen\",\n instructions: `Take a screenshot and provide a detailed analysis:\n1. Describe what application/website is visible\n2. Identify key UI elements and their state\n3. Note any errors, warnings, or notifications\n4. Describe the overall layout\n5. If code is visible, summarize what it does\nBe specific about positions (top-left, center, etc.).`,\n tools: [\"screenshot_analyze\"],\n tags: [\"screenshot\", \"vision\", \"analysis\"],\n category: \"utility\",\n },\n {\n name: \"Regex Helper\",\n description: \"Build and explain regular expressions\",\n trigger: \"/regex\",\n instructions: `Help the user build a regular expression:\n1. Understand what they want to match\n2. Build the regex step by step, explaining each part\n3. Provide the final regex in multiple flavors if needed (JS, Python, PCRE)\n4. Include 3-5 test cases showing matches and non-matches\n5. Explain any edge cases or gotchas\nFormat with code blocks for readability.`,\n tools: [],\n tags: [\"regex\", \"development\", \"utility\"],\n category: \"development\",\n },\n];\n","// Sentinel Hub — community marketplace for skills, plugins, and templates\n\nimport { skillRegistry, type Skill } from \"../skills\";\nimport { BUILTIN_SKILLS, type BuiltinSkillDef } from \"./builtin-skills\";\n\nexport type HubCategory = \"skills\" | \"plugins\" | \"templates\" | \"workflows\";\n\nexport interface HubItem {\n id: string;\n name: string;\n description: string;\n category: HubCategory;\n author: string;\n version: string;\n tags: string[];\n rating: number;\n ratingCount: number;\n downloads: number;\n createdAt: Date;\n data: string; // JSON serialized content\n}\n\n// In-memory hub registry\nconst hubItems: Map<string, HubItem> = new Map();\nconst userRatings: Map<string, Map<string, number>> = new Map(); // itemId -> userId -> rating\nlet initialized = false;\n\nexport class SentinelHub {\n /**\n * Initialize hub with built-in starter items\n */\n async initialize(): Promise<void> {\n if (initialized) return;\n initialized = true;\n\n for (const builtin of BUILTIN_SKILLS) {\n const item: HubItem = {\n id: `builtin-${builtin.trigger.replace(\"/\", \"\")}`,\n name: builtin.name,\n description: builtin.description,\n category: \"skills\",\n author: \"OpenSentinel\",\n version: \"1.0.0\",\n tags: builtin.tags,\n rating: 5.0,\n ratingCount: 0,\n downloads: 0,\n createdAt: new Date(),\n data: JSON.stringify({\n name: builtin.name,\n description: builtin.description,\n trigger: builtin.trigger,\n instructions: builtin.instructions,\n tools: builtin.tools,\n tags: builtin.tags,\n }),\n };\n hubItems.set(item.id, item);\n }\n }\n\n /**\n * Browse hub items with optional filtering\n */\n browseHub(params?: {\n category?: HubCategory;\n search?: string;\n tag?: string;\n limit?: number;\n offset?: number;\n }): { items: HubItem[]; total: number } {\n let items = [...hubItems.values()];\n\n if (params?.category) {\n items = items.filter((i) => i.category === params.category);\n }\n\n if (params?.search) {\n const q = params.search.toLowerCase();\n items = items.filter(\n (i) =>\n i.name.toLowerCase().includes(q) ||\n i.description.toLowerCase().includes(q) ||\n i.tags.some((t) => t.toLowerCase().includes(q))\n );\n }\n\n if (params?.tag) {\n const tag = params.tag.toLowerCase();\n items = items.filter((i) => i.tags.some((t) => t.toLowerCase() === tag));\n }\n\n // Sort by rating then downloads\n items.sort((a, b) => b.rating - a.rating || b.downloads - a.downloads);\n\n const total = items.length;\n const offset = params?.offset ?? 0;\n const limit = params?.limit ?? 20;\n items = items.slice(offset, offset + limit);\n\n return { items, total };\n }\n\n /**\n * Install a hub item (skill, plugin, template, etc.)\n */\n async installFromHub(\n itemId: string,\n userId: string\n ): Promise<{ success: boolean; message: string; skillId?: string }> {\n const item = hubItems.get(itemId);\n if (!item) {\n return { success: false, message: `Hub item not found: ${itemId}` };\n }\n\n item.downloads++;\n\n if (item.category === \"skills\") {\n const skill = skillRegistry.importSkill(item.data, userId);\n if (!skill) {\n return { success: false, message: \"Failed to import skill data\" };\n }\n return {\n success: true,\n message: `Installed skill \"${item.name}\" — use ${skill.trigger} to run it`,\n skillId: skill.id,\n };\n }\n\n // For plugins/templates/workflows — placeholder\n return {\n success: true,\n message: `Installed ${item.category} \"${item.name}\"`,\n };\n }\n\n /**\n * Publish a skill/plugin to the hub\n */\n async publishToHub(params: {\n name: string;\n description: string;\n category: HubCategory;\n data: string;\n author: string;\n tags?: string[];\n version?: string;\n }): Promise<{ success: boolean; itemId?: string; message: string }> {\n const id = `user-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;\n\n const item: HubItem = {\n id,\n name: params.name,\n description: params.description,\n category: params.category,\n author: params.author,\n version: params.version ?? \"1.0.0\",\n tags: params.tags ?? [],\n rating: 0,\n ratingCount: 0,\n downloads: 0,\n createdAt: new Date(),\n data: params.data,\n };\n\n hubItems.set(id, item);\n return { success: true, itemId: id, message: `Published \"${params.name}\" to Sentinel Hub` };\n }\n\n /**\n * Rate a hub item\n */\n rateItem(\n itemId: string,\n userId: string,\n rating: number\n ): { success: boolean; newRating?: number } {\n const item = hubItems.get(itemId);\n if (!item) return { success: false };\n\n rating = Math.max(1, Math.min(5, Math.round(rating)));\n\n if (!userRatings.has(itemId)) {\n userRatings.set(itemId, new Map());\n }\n\n const ratings = userRatings.get(itemId)!;\n const hadPrevious = ratings.has(userId);\n ratings.set(userId, rating);\n\n // Recalculate average\n let sum = 0;\n for (const r of ratings.values()) sum += r;\n item.rating = Math.round((sum / ratings.size) * 10) / 10;\n item.ratingCount = ratings.size;\n\n return { success: true, newRating: item.rating };\n }\n\n /**\n * Get a specific hub item\n */\n getItem(itemId: string): HubItem | undefined {\n return hubItems.get(itemId);\n }\n\n /**\n * Get hub statistics\n */\n getStats(): {\n totalItems: number;\n categories: Record<HubCategory, number>;\n totalDownloads: number;\n } {\n const stats = {\n totalItems: hubItems.size,\n categories: { skills: 0, plugins: 0, templates: 0, workflows: 0 } as Record<HubCategory, number>,\n totalDownloads: 0,\n };\n\n for (const item of hubItems.values()) {\n stats.categories[item.category]++;\n stats.totalDownloads += item.downloads;\n }\n\n return stats;\n }\n}\n\n// Singleton\nexport const sentinelHub = new SentinelHub();\n","import type { Tool } from \"@anthropic-ai/sdk/resources/messages\";\nimport { isMCPTool, executeMCPTool, type MCPRegistry } from \"../core/mcp\";\nimport { executeCommand } from \"./shell\";\nimport {\n listDirectory,\n readFileContent,\n writeFileContent,\n searchFiles,\n} from \"./files\";\nimport { navigateTo, searchGoogle, takeScreenshot as browserScreenshot } from \"./browser\";\nimport { webSearch, research } from \"./web-search\";\nimport { analyzeImage } from \"./image-analysis\";\nimport { performOCR, extractStructuredData } from \"./ocr\";\nimport { screenshotAndAnalyze, takeScreenshot as systemScreenshot } from \"./screenshot\";\nimport { generatePDF } from \"./file-generation/pdf\";\nimport { generateSpreadsheet } from \"./file-generation/spreadsheet\";\nimport { generateChart } from \"./file-generation/charts\";\nimport { generateDiagram, generateStructuredDiagram } from \"./file-generation/diagrams\";\nimport { spawnAgent, getAgent, cancelAgent } from \"../core/agents/agent-manager\";\nimport { renderMath, renderMathDocument } from \"./rendering/math-renderer\";\nimport { highlightCode, renderCode } from \"./rendering/code-highlighter\";\nimport { markdownToHtml, renderMarkdown } from \"./rendering/markdown-renderer\";\nimport {\n summarizeVideo,\n quickSummarizeVideo,\n detailedSummarizeVideo,\n extractKeyMoments,\n getVideoInfo,\n} from \"./video-summarization\";\nimport { applyPatch } from \"./patch\";\nimport { pollManager } from \"../core/polls\";\nimport { skillRegistry } from \"../core/skills/skill-registry\";\nimport { skillExecutor } from \"../core/skills/skill-executor\";\nimport { sentinelHub } from \"../core/hub\";\n\n// Define tools for Claude\nexport const TOOLS: Tool[] = [\n {\n name: \"execute_command\",\n description:\n \"Execute a shell command on the system. Use for system tasks, git operations, running scripts, etc. Some dangerous commands are blocked for safety.\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n command: {\n type: \"string\",\n description: \"The shell command to execute\",\n },\n working_directory: {\n type: \"string\",\n description: \"Optional working directory for the command\",\n },\n },\n required: [\"command\"],\n },\n },\n {\n name: \"list_directory\",\n description: \"List files and folders in a directory\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n path: {\n type: \"string\",\n description: \"The directory path to list\",\n },\n },\n required: [\"path\"],\n },\n },\n {\n name: \"read_file\",\n description: \"Read the contents of a file\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n path: {\n type: \"string\",\n description: \"The file path to read\",\n },\n },\n required: [\"path\"],\n },\n },\n {\n name: \"write_file\",\n description: \"Write content to a file (creates or overwrites)\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n path: {\n type: \"string\",\n description: \"The file path to write to\",\n },\n content: {\n type: \"string\",\n description: \"The content to write\",\n },\n },\n required: [\"path\", \"content\"],\n },\n },\n {\n name: \"search_files\",\n description: \"Search for files matching a glob pattern\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n pattern: {\n type: \"string\",\n description: \"Glob pattern to search for (e.g., '**/*.ts')\",\n },\n base_path: {\n type: \"string\",\n description: \"Base directory to search from\",\n },\n },\n required: [\"pattern\"],\n },\n },\n {\n name: \"web_search\",\n description: \"Search the web for information\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n query: {\n type: \"string\",\n description: \"The search query\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"browse_url\",\n description: \"Navigate to a URL and extract its content\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n url: {\n type: \"string\",\n description: \"The URL to browse\",\n },\n },\n required: [\"url\"],\n },\n },\n {\n name: \"take_screenshot\",\n description: \"Take a screenshot of the current browser page\",\n input_schema: {\n type: \"object\" as const,\n properties: {},\n required: [],\n },\n },\n {\n name: \"analyze_image\",\n description: \"Analyze an image using AI vision. Can describe, extract information, or answer questions about images.\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n image_url: {\n type: \"string\",\n description: \"URL of the image to analyze\",\n },\n image_path: {\n type: \"string\",\n description: \"Local file path of the image to analyze\",\n },\n prompt: {\n type: \"string\",\n description: \"What to analyze or ask about the image\",\n },\n },\n required: [\"prompt\"],\n },\n },\n {\n name: \"ocr_document\",\n description: \"Extract text from an image or document using OCR\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n file_path: {\n type: \"string\",\n description: \"Path to the image or PDF file\",\n },\n language: {\n type: \"string\",\n description: \"Expected language of the text (default: English)\",\n },\n },\n required: [\"file_path\"],\n },\n },\n {\n name: \"extract_document_data\",\n description: \"Extract structured data from documents like receipts, invoices, forms, or tables\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n file_path: {\n type: \"string\",\n description: \"Path to the document image\",\n },\n data_type: {\n type: \"string\",\n enum: [\"table\", \"form\", \"receipt\", \"invoice\"],\n description: \"Type of data to extract\",\n },\n },\n required: [\"file_path\"],\n },\n },\n {\n name: \"screenshot_analyze\",\n description: \"Take a screenshot of the desktop and analyze it with AI\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n prompt: {\n type: \"string\",\n description: \"What to analyze or look for in the screenshot\",\n },\n region: {\n type: \"string\",\n description: \"Screen region: 'full', 'active_window', or coordinates 'x,y,width,height'\",\n },\n },\n required: [\"prompt\"],\n },\n },\n {\n name: \"generate_pdf\",\n description: \"Generate a PDF document from markdown or HTML content\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n content: {\n type: \"string\",\n description: \"The markdown or HTML content for the PDF\",\n },\n filename: {\n type: \"string\",\n description: \"Output filename for the PDF\",\n },\n content_type: {\n type: \"string\",\n enum: [\"markdown\", \"html\"],\n description: \"Type of content (default: markdown)\",\n },\n title: {\n type: \"string\",\n description: \"Document title\",\n },\n },\n required: [\"content\", \"filename\"],\n },\n },\n {\n name: \"generate_spreadsheet\",\n description: \"Generate a spreadsheet (Excel or CSV) from data\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n data: {\n type: \"array\",\n description: \"Data rows (2D array or array of objects)\",\n },\n filename: {\n type: \"string\",\n description: \"Output filename (.xlsx or .csv)\",\n },\n headers: {\n type: \"array\",\n description: \"Column headers\",\n items: { type: \"string\" },\n },\n sheet_name: {\n type: \"string\",\n description: \"Name of the worksheet\",\n },\n },\n required: [\"data\", \"filename\"],\n },\n },\n {\n name: \"generate_chart\",\n description: \"Generate a chart as SVG\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n type: {\n type: \"string\",\n enum: [\"bar\", \"line\", \"pie\", \"doughnut\", \"scatter\", \"area\"],\n description: \"Type of chart\",\n },\n labels: {\n type: \"array\",\n description: \"Labels for data points\",\n items: { type: \"string\" },\n },\n values: {\n type: \"array\",\n description: \"Numeric values\",\n items: { type: \"number\" },\n },\n title: {\n type: \"string\",\n description: \"Chart title\",\n },\n filename: {\n type: \"string\",\n description: \"Output filename for the SVG\",\n },\n },\n required: [\"type\", \"labels\", \"values\"],\n },\n },\n {\n name: \"generate_diagram\",\n description: \"Generate a diagram using Mermaid syntax\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n type: {\n type: \"string\",\n enum: [\"flowchart\", \"sequence\", \"class\", \"state\", \"er\", \"gantt\", \"mindmap\"],\n description: \"Type of diagram\",\n },\n mermaid_code: {\n type: \"string\",\n description: \"Mermaid diagram code (if providing raw code)\",\n },\n data: {\n type: \"object\",\n description: \"Structured data for the diagram (alternative to mermaid_code)\",\n },\n filename: {\n type: \"string\",\n description: \"Output filename\",\n },\n },\n required: [\"type\"],\n },\n },\n {\n name: \"spawn_agent\",\n description: \"Spawn a background agent to work on a task autonomously\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n type: {\n type: \"string\",\n enum: [\"research\", \"coding\", \"writing\", \"analysis\"],\n description: \"Type of agent to spawn\",\n },\n objective: {\n type: \"string\",\n description: \"The objective/task for the agent\",\n },\n context: {\n type: \"object\",\n description: \"Additional context for the agent\",\n },\n token_budget: {\n type: \"number\",\n description: \"Maximum tokens the agent can use\",\n },\n },\n required: [\"type\", \"objective\"],\n },\n },\n {\n name: \"check_agent\",\n description: \"Check the status and progress of a running agent\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n agent_id: {\n type: \"string\",\n description: \"The ID of the agent to check\",\n },\n },\n required: [\"agent_id\"],\n },\n },\n {\n name: \"cancel_agent\",\n description: \"Cancel a running agent\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n agent_id: {\n type: \"string\",\n description: \"The ID of the agent to cancel\",\n },\n },\n required: [\"agent_id\"],\n },\n },\n {\n name: \"render_math\",\n description: \"Render a LaTeX mathematical expression to SVG/HTML. Useful for displaying equations, formulas, and mathematical notation.\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n latex: {\n type: \"string\",\n description: \"LaTeX expression to render (e.g., 'x = \\\\frac{-b \\\\pm \\\\sqrt{b^2-4ac}}{2a}')\",\n },\n display_mode: {\n type: \"boolean\",\n description: \"true for block/display math, false for inline (default: true)\",\n },\n filename: {\n type: \"string\",\n description: \"Optional filename to save the rendered SVG\",\n },\n font_size: {\n type: \"number\",\n description: \"Font size in pixels (default: 20)\",\n },\n color: {\n type: \"string\",\n description: \"Text color (default: black)\",\n },\n },\n required: [\"latex\"],\n },\n },\n {\n name: \"render_math_document\",\n description: \"Render multiple LaTeX expressions into an HTML document with MathJax support\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n expressions: {\n type: \"array\",\n description: \"Array of expressions with latex and optional label\",\n items: {\n type: \"object\",\n properties: {\n latex: { type: \"string\" },\n label: { type: \"string\" },\n },\n required: [\"latex\"],\n },\n },\n filename: {\n type: \"string\",\n description: \"Output filename for the HTML document\",\n },\n },\n required: [\"expressions\"],\n },\n },\n {\n name: \"render_code\",\n description: \"Syntax highlight code with themes. Outputs styled HTML for code display.\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n code: {\n type: \"string\",\n description: \"The source code to highlight\",\n },\n language: {\n type: \"string\",\n enum: [\"typescript\", \"javascript\", \"python\", \"go\", \"rust\"],\n description: \"Programming language (default: javascript)\",\n },\n theme: {\n type: \"string\",\n enum: [\"light\", \"dark\", \"github\", \"monokai\"],\n description: \"Color theme (default: dark)\",\n },\n line_numbers: {\n type: \"boolean\",\n description: \"Show line numbers (default: true)\",\n },\n highlight_lines: {\n type: \"array\",\n description: \"Line numbers to highlight\",\n items: { type: \"number\" },\n },\n title: {\n type: \"string\",\n description: \"Optional title/filename to display above the code\",\n },\n filename: {\n type: \"string\",\n description: \"Output filename to save the HTML\",\n },\n },\n required: [\"code\"],\n },\n },\n {\n name: \"render_markdown\",\n description: \"Convert markdown to styled HTML. Supports code blocks, tables, images, links, and more.\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n markdown: {\n type: \"string\",\n description: \"The markdown content to render\",\n },\n theme: {\n type: \"string\",\n enum: [\"light\", \"dark\", \"github\"],\n description: \"Visual theme (default: github)\",\n },\n syntax_highlight: {\n type: \"boolean\",\n description: \"Enable syntax highlighting in code blocks (default: true)\",\n },\n table_of_contents: {\n type: \"boolean\",\n description: \"Generate a table of contents from headings (default: false)\",\n },\n filename: {\n type: \"string\",\n description: \"Output filename to save the HTML\",\n },\n },\n required: [\"markdown\"],\n },\n },\n {\n name: \"summarize_video\",\n description: \"Summarize a video file by extracting frames, transcribing audio, and generating a comprehensive summary with key moments.\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n video_path: {\n type: \"string\",\n description: \"Path to the video file to summarize\",\n },\n frame_count: {\n type: \"number\",\n description: \"Number of frames to extract and analyze (default: 8, max: 20)\",\n },\n include_transcript: {\n type: \"boolean\",\n description: \"Whether to transcribe audio (default: true if video has audio)\",\n },\n analysis_depth: {\n type: \"string\",\n enum: [\"quick\", \"standard\", \"detailed\"],\n description: \"Depth of analysis (default: standard)\",\n },\n language: {\n type: \"string\",\n description: \"Language for transcription (default: en)\",\n },\n focus_areas: {\n type: \"array\",\n description: \"Specific aspects to focus on in the analysis\",\n items: { type: \"string\" },\n },\n },\n required: [\"video_path\"],\n },\n },\n {\n name: \"video_info\",\n description: \"Get basic information about a video file (duration, resolution, codec, etc.) without full analysis.\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n video_path: {\n type: \"string\",\n description: \"Path to the video file\",\n },\n },\n required: [\"video_path\"],\n },\n },\n {\n name: \"extract_video_moments\",\n description: \"Extract and analyze key moments from a video without generating a full summary.\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n video_path: {\n type: \"string\",\n description: \"Path to the video file\",\n },\n frame_count: {\n type: \"number\",\n description: \"Number of key moments to extract (default: 8)\",\n },\n },\n required: [\"video_path\"],\n },\n },\n {\n name: \"apply_patch\",\n description: \"Apply a unified diff patch to a file. Useful for making targeted code changes with context-aware matching.\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n file_path: {\n type: \"string\",\n description: \"Path to the file to patch\",\n },\n patch: {\n type: \"string\",\n description: \"Unified diff patch content (with @@ hunk headers, +/- lines)\",\n },\n create_backup: {\n type: \"boolean\",\n description: \"Create a .bak backup before patching (default: true)\",\n },\n },\n required: [\"file_path\", \"patch\"],\n },\n },\n {\n name: \"create_poll\",\n description: \"Create a poll for users to vote on. Supports multiple choice and timed auto-close.\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n question: {\n type: \"string\",\n description: \"The poll question\",\n },\n options: {\n type: \"array\",\n description: \"List of answer options (2-10)\",\n items: { type: \"string\" },\n },\n multi_select: {\n type: \"boolean\",\n description: \"Allow multiple selections (default: false)\",\n },\n duration: {\n type: \"number\",\n description: \"Auto-close after this many minutes (optional)\",\n },\n },\n required: [\"question\", \"options\"],\n },\n },\n {\n name: \"teach_skill\",\n description: \"Create a new reusable skill that OpenSentinel can execute on demand. Skills are user-teachable workflows with custom instructions.\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n name: {\n type: \"string\",\n description: \"Skill name\",\n },\n description: {\n type: \"string\",\n description: \"What the skill does\",\n },\n instructions: {\n type: \"string\",\n description: \"Detailed instructions for executing the skill (system prompt)\",\n },\n tools: {\n type: \"array\",\n description: \"List of tool names this skill can use\",\n items: { type: \"string\" },\n },\n },\n required: [\"name\", \"description\", \"instructions\"],\n },\n },\n {\n name: \"run_skill\",\n description: \"Execute a previously created skill by name or trigger\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n skill: {\n type: \"string\",\n description: \"Skill name, ID, or trigger (e.g., 'Code Review' or '/review')\",\n },\n input: {\n type: \"string\",\n description: \"User input to pass to the skill\",\n },\n },\n required: [\"skill\"],\n },\n },\n {\n name: \"hub_browse\",\n description: \"Browse the Sentinel Hub marketplace for skills, plugins, templates, and workflows\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n category: {\n type: \"string\",\n enum: [\"skills\", \"plugins\", \"templates\", \"workflows\"],\n description: \"Filter by category\",\n },\n search: {\n type: \"string\",\n description: \"Search query\",\n },\n },\n required: [],\n },\n },\n {\n name: \"hub_install\",\n description: \"Install an item from the Sentinel Hub marketplace\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n item_id: {\n type: \"string\",\n description: \"The hub item ID to install\",\n },\n },\n required: [\"item_id\"],\n },\n },\n {\n name: \"hub_publish\",\n description: \"Publish a skill, plugin, or workflow to the Sentinel Hub for sharing\",\n input_schema: {\n type: \"object\" as const,\n properties: {\n name: {\n type: \"string\",\n description: \"Item name\",\n },\n description: {\n type: \"string\",\n description: \"Item description\",\n },\n category: {\n type: \"string\",\n enum: [\"skills\", \"plugins\", \"templates\", \"workflows\"],\n description: \"Item category\",\n },\n data: {\n type: \"string\",\n description: \"JSON-serialized item content\",\n },\n tags: {\n type: \"array\",\n description: \"Tags for discovery\",\n items: { type: \"string\" },\n },\n },\n required: [\"name\", \"description\", \"category\", \"data\"],\n },\n },\n];\n\n// MCP registry reference (set by brain.ts after initialization)\nlet mcpRegistry: MCPRegistry | null = null;\n\nexport function setMCPRegistry(registry: MCPRegistry | null): void {\n mcpRegistry = registry;\n}\n\nexport function getMCPRegistry(): MCPRegistry | null {\n return mcpRegistry;\n}\n\n// Execute a tool by name\nexport async function executeTool(\n name: string,\n input: Record<string, unknown>\n): Promise<{ success: boolean; result: unknown; error?: string }> {\n try {\n // Check if this is an MCP tool\n if (isMCPTool(name) && mcpRegistry) {\n const result = await executeMCPTool(mcpRegistry, name, input);\n return {\n success: result.success,\n result: result.output || result.error,\n error: result.error,\n };\n }\n\n switch (name) {\n case \"execute_command\": {\n const result = await executeCommand(\n input.command as string,\n input.working_directory as string | undefined\n );\n return {\n success: result.success,\n result: {\n stdout: result.stdout,\n stderr: result.stderr,\n exitCode: result.exitCode,\n },\n error: result.success ? undefined : result.stderr,\n };\n }\n\n case \"list_directory\": {\n const files = await listDirectory(input.path as string);\n return { success: true, result: files };\n }\n\n case \"read_file\": {\n const content = await readFileContent(input.path as string);\n return { success: true, result: content };\n }\n\n case \"write_file\": {\n await writeFileContent(input.path as string, input.content as string);\n return { success: true, result: \"File written successfully\" };\n }\n\n case \"search_files\": {\n const files = await searchFiles(\n input.pattern as string,\n input.base_path as string | undefined\n );\n return { success: true, result: files };\n }\n\n case \"web_search\": {\n const results = await webSearch(input.query as string);\n return { success: true, result: results };\n }\n\n case \"browse_url\": {\n const page = await navigateTo(input.url as string);\n return { success: true, result: page };\n }\n\n case \"take_screenshot\": {\n const screenshot = await browserScreenshot();\n return {\n success: true,\n result: { screenshot: `data:image/png;base64,${screenshot}` },\n };\n }\n\n case \"analyze_image\": {\n const result = await analyzeImage({\n imageUrl: input.image_url as string | undefined,\n imagePath: input.image_path as string | undefined,\n prompt: input.prompt as string,\n });\n return {\n success: result.success,\n result: result.analysis,\n error: result.error,\n };\n }\n\n case \"ocr_document\": {\n const result = await performOCR(\n input.file_path as string,\n { language: input.language as string | undefined }\n );\n return {\n success: result.success,\n result: result.text,\n error: result.error,\n };\n }\n\n case \"extract_document_data\": {\n const result = await extractStructuredData(\n input.file_path as string,\n input.data_type as \"table\" | \"form\" | \"receipt\" | \"invoice\" | undefined\n );\n return {\n success: result.success,\n result: result.data,\n error: result.error,\n };\n }\n\n case \"screenshot_analyze\": {\n let region: \"full\" | \"active_window\" | { x: number; y: number; width: number; height: number } = \"full\";\n\n if (input.region === \"active_window\") {\n region = \"active_window\";\n } else if (typeof input.region === \"string\" && input.region.includes(\",\")) {\n const [x, y, width, height] = input.region.split(\",\").map(Number);\n region = { x, y, width, height };\n }\n\n const result = await screenshotAndAnalyze(\n input.prompt as string,\n { region }\n );\n return {\n success: result.success,\n result: result.analysis,\n error: result.error,\n };\n }\n\n case \"generate_pdf\": {\n const result = await generatePDF(\n input.content as string,\n input.filename as string,\n {\n contentType: input.content_type as \"markdown\" | \"html\" | undefined,\n title: input.title as string | undefined,\n }\n );\n return {\n success: result.success,\n result: result.filePath,\n error: result.error,\n };\n }\n\n case \"generate_spreadsheet\": {\n const result = await generateSpreadsheet(\n input.data as unknown[][],\n input.filename as string,\n {\n headers: input.headers as string[] | undefined,\n sheetName: input.sheet_name as string | undefined,\n }\n );\n return {\n success: result.success,\n result: result.filePath,\n error: result.error,\n };\n }\n\n case \"generate_chart\": {\n const { quickChart } = await import(\"./file-generation/charts\");\n const result = await quickChart(\n input.type as \"bar\" | \"line\" | \"pie\" | \"doughnut\" | \"scatter\" | \"area\",\n input.labels as string[],\n input.values as number[],\n input.title as string | undefined,\n input.filename as string | undefined\n );\n return {\n success: result.success,\n result: result.filePath,\n error: result.error,\n };\n }\n\n case \"generate_diagram\": {\n if (input.mermaid_code) {\n const result = await generateDiagram(\n input.mermaid_code as string,\n input.filename as string | undefined\n );\n return {\n success: result.success,\n result: result.filePath,\n error: result.error,\n };\n } else if (input.data) {\n const result = await generateStructuredDiagram(\n input.type as \"flowchart\" | \"sequence\" | \"class\" | \"state\" | \"er\" | \"gantt\" | \"mindmap\",\n input.data,\n input.filename as string | undefined\n );\n return {\n success: result.success,\n result: result.filePath,\n error: result.error,\n };\n }\n return { success: false, result: null, error: \"Must provide mermaid_code or data\" };\n }\n\n case \"spawn_agent\": {\n const agentId = await spawnAgent({\n userId: \"system\", // Would come from context in real usage\n type: input.type as \"research\" | \"coding\" | \"writing\" | \"analysis\",\n objective: input.objective as string,\n context: input.context as Record<string, unknown> | undefined,\n tokenBudget: input.token_budget as number | undefined,\n });\n return {\n success: true,\n result: { agentId, message: \"Agent spawned successfully\" },\n };\n }\n\n case \"check_agent\": {\n const agent = await getAgent(input.agent_id as string);\n if (!agent) {\n return { success: false, result: null, error: \"Agent not found\" };\n }\n return {\n success: true,\n result: {\n id: agent.id,\n type: agent.type,\n status: agent.status,\n objective: agent.objective,\n tokensUsed: agent.tokensUsed,\n progress: agent.progress.slice(-5),\n result: agent.result,\n },\n };\n }\n\n case \"cancel_agent\": {\n const cancelled = await cancelAgent(input.agent_id as string);\n return {\n success: cancelled,\n result: cancelled ? \"Agent cancelled\" : \"Could not cancel agent\",\n };\n }\n\n case \"render_math\": {\n const result = await renderMath(\n input.latex as string,\n input.filename as string | undefined,\n {\n displayMode: input.display_mode as boolean | undefined,\n fontSize: input.font_size as number | undefined,\n color: input.color as string | undefined,\n }\n );\n return {\n success: result.success,\n result: {\n svg: result.svg,\n html: result.html,\n filePath: result.filePath,\n },\n error: result.error,\n };\n }\n\n case \"render_math_document\": {\n const result = await renderMathDocument(\n input.expressions as Array<{ latex: string; label?: string }>,\n input.filename as string | undefined\n );\n return {\n success: result.success,\n result: {\n html: result.html,\n filePath: result.filePath,\n },\n error: result.error,\n };\n }\n\n case \"render_code\": {\n const result = await renderCode(\n input.code as string,\n input.filename as string | undefined,\n {\n language: input.language as string | undefined,\n theme: input.theme as \"light\" | \"dark\" | \"github\" | \"monokai\" | undefined,\n lineNumbers: input.line_numbers as boolean | undefined,\n highlightLines: input.highlight_lines as number[] | undefined,\n title: input.title as string | undefined,\n }\n );\n return {\n success: result.success,\n result: {\n html: result.html,\n filePath: result.filePath,\n },\n error: result.error,\n };\n }\n\n case \"render_markdown\": {\n const result = await renderMarkdown(\n input.markdown as string,\n input.filename as string | undefined,\n {\n theme: input.theme as \"light\" | \"dark\" | \"github\" | undefined,\n syntaxHighlight: input.syntax_highlight as boolean | undefined,\n tableOfContents: input.table_of_contents as boolean | undefined,\n }\n );\n return {\n success: result.success,\n result: {\n html: result.html,\n filePath: result.filePath,\n },\n error: result.error,\n };\n }\n\n case \"summarize_video\": {\n const result = await summarizeVideo(\n input.video_path as string,\n {\n frameCount: input.frame_count as number | undefined,\n includeTranscript: input.include_transcript as boolean | undefined,\n analysisDepth: input.analysis_depth as \"quick\" | \"standard\" | \"detailed\" | undefined,\n language: input.language as string | undefined,\n focusAreas: input.focus_areas as string[] | undefined,\n }\n );\n return {\n success: result.success,\n result: result.summary,\n error: result.error,\n };\n }\n\n case \"video_info\": {\n const result = await getVideoInfo(input.video_path as string);\n return {\n success: result.success,\n result: result.info,\n error: result.error,\n };\n }\n\n case \"extract_video_moments\": {\n const result = await extractKeyMoments(\n input.video_path as string,\n input.frame_count as number | undefined\n );\n return {\n success: result.success,\n result: result.moments,\n error: result.error,\n };\n }\n\n case \"apply_patch\": {\n const result = await applyPatch(\n input.file_path as string,\n input.patch as string,\n input.create_backup as boolean | undefined\n );\n return {\n success: result.applied,\n result: {\n linesChanged: result.linesChanged,\n backup: result.backup,\n },\n error: result.error,\n };\n }\n\n case \"create_poll\": {\n const poll = pollManager.createPoll({\n question: input.question as string,\n options: input.options as string[],\n multiSelect: input.multi_select as boolean | undefined,\n duration: input.duration as number | undefined,\n channelType: \"system\",\n channelId: \"system\",\n createdBy: \"assistant\",\n });\n return {\n success: true,\n result: {\n pollId: poll.id,\n question: poll.question,\n options: poll.options.map((o) => o.text),\n message: pollManager.formatPollMessage(poll.id),\n },\n };\n }\n\n case \"teach_skill\": {\n const result = await skillExecutor.teachSkill({\n name: input.name as string,\n description: input.description as string,\n instructions: input.instructions as string,\n tools: input.tools as string[] | undefined,\n userId: \"system\",\n });\n return {\n success: result.success,\n result: {\n skillId: result.skillId,\n skillName: result.skillName,\n message: result.output,\n },\n error: result.error,\n };\n }\n\n case \"run_skill\": {\n const result = await skillExecutor.execute(\n input.skill as string,\n input.input as string ?? \"\",\n \"system\"\n );\n return {\n success: result.success,\n result: {\n skillId: result.skillId,\n skillName: result.skillName,\n systemPrompt: result.output,\n },\n error: result.error,\n };\n }\n\n case \"hub_browse\": {\n await sentinelHub.initialize();\n const results = sentinelHub.browseHub({\n category: input.category as any,\n search: input.search as string | undefined,\n });\n return {\n success: true,\n result: {\n items: results.items.map((i) => ({\n id: i.id,\n name: i.name,\n description: i.description,\n category: i.category,\n author: i.author,\n rating: i.rating,\n downloads: i.downloads,\n tags: i.tags,\n })),\n total: results.total,\n },\n };\n }\n\n case \"hub_install\": {\n await sentinelHub.initialize();\n const result = await sentinelHub.installFromHub(\n input.item_id as string,\n \"system\"\n );\n return {\n success: result.success,\n result: {\n message: result.message,\n skillId: result.skillId,\n },\n };\n }\n\n case \"hub_publish\": {\n await sentinelHub.initialize();\n const result = await sentinelHub.publishToHub({\n name: input.name as string,\n description: input.description as string,\n category: input.category as any,\n data: input.data as string,\n author: \"user\",\n tags: input.tags as string[] | undefined,\n });\n return {\n success: result.success,\n result: {\n itemId: result.itemId,\n message: result.message,\n },\n };\n }\n\n default:\n return { success: false, result: null, error: `Unknown tool: ${name}` };\n }\n } catch (error) {\n return {\n success: false,\n result: null,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AAsHtB,IAAM,wBAAwB,oBAAI,IAAI;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGD,IAAM,2BAA2B,oBAAI,IAAI;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,E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K,eAAe;AAClB,cAAM,YAAY,WAAW;AAC7B,cAAM,SAAS,MAAM,YAAY;AAAA,UAC/B,MAAM;AAAA,UACN;AAAA,QACF;AACA,eAAO;AAAA,UACL,SAAS,OAAO;AAAA,UAChB,QAAQ;AAAA,YACN,SAAS,OAAO;AAAA,YAChB,SAAS,OAAO;AAAA,UAClB;AAAA,QACF;AAAA,MACF;AAAA,MAEA,KAAK,eAAe;AAClB,cAAM,YAAY,WAAW;AAC7B,cAAM,SAAS,MAAM,YAAY,aAAa;AAAA,UAC5C,MAAM,MAAM;AAAA,UACZ,aAAa,MAAM;AAAA,UACnB,UAAU,MAAM;AAAA,UAChB,MAAM,MAAM;AAAA,UACZ,QAAQ;AAAA,UACR,MAAM,MAAM;AAAA,QACd,CAAC;AACD,eAAO;AAAA,UACL,SAAS,OAAO;AAAA,UAChB,QAAQ;AAAA,YACN,QAAQ,OAAO;AAAA,YACf,SAAS,OAAO;AAAA,UAClB;AAAA,QACF;AAAA,MACF;AAAA,MAEA;AACE,eAAO,EAAE,SAAS,OAAO,QAAQ,MAAM,OAAO,iBAAiB,IAAI,GAAG;AAAA,IAC1E;AAAA,EACF,SAAS,OAAO;AACd,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,IAC9D;AAAA,EACF;AACF;","names":["resolve","isPathAllowed","readFile","readFile","join","join","takeScreenshot","readFile","mkdir","dirname","join","tmpdir","randomBytes","getTempPath","randomBytes","join","tmpdir","mkdir","dirname","writeFile","chromium","browser","page","join","tmpdir","randomBytes","writeFile","mkdir","dirname","getTempPath","randomBytes","join","tmpdir","mkdir","dirname","writeFile","index","join","tmpdir","randomBytes","writeFile","mkdir","dirname","getTempPath","randomBytes","join","tmpdir","messages","mkdir","dirname","writeFile","eq","and","desc","eq","and","gte","lte","desc","eq","messages","eq","eq","join","tmpdir","writeFile","mkdir","dirname","join","tmpdir","mkdir","dirname","writeFile","join","tmpdir","writeFile","mkdir","dirname","escapeHtml","join","tmpdir","mkdir","dirname","writeFile","join","tmpdir","writeFile","mkdir","dirname","THEMES","escapeHtml","text","join","tmpdir","mkdir","dirname","writeFile","Anthropic","readFile","unlink","mkdir","stat","readdir","join","spawn","tmpdir","anthropic","Anthropic","resolve","timestamp","join","tmpdir","mkdir","readFile","writeFile","existsSync","randomUUID","text","option","randomUUID","page"]}
|