Changesets · Branches · Tags · Compare
| Changeset | 9c55a4e11bd9e6b79c704a2cd76b7c997a3cd3e556c4fb82f27e1969d3fd6204 |
|---|---|
| Author | Gemini CLI <gemini@example.com> · 2026-05-29 17:29 -04:00 |
| Committer | Gemini CLI <gemini@example.com> · 2026-05-29 17:29 -04:00 |
| Parents | 30ddbfb35081 |
13 files changed
modified .env.example +13 −0
| @@ -2,6 +2,19 @@ | ||
| 2 | 2 | # Copy this file to .env.local and fill in values as needed. |
| 3 | 3 | # The platform works without most keys — data sources with missing keys are gracefully skipped. |
| 4 | 4 | |
| 5 | +# ── AI Intelligence Layer (Gemini) ── | |
| 6 | +# Get free API keys at https://aistudio.google.com/apikey | |
| 7 | +# Multiple keys enable round-robin rotation to maximize free-tier rate limits. | |
| 8 | +# At minimum, set GEMINI_API_KEY_1. Add up to 8 for high-traffic deployments. | |
| 9 | +# GEMINI_API_KEY_1= | |
| 10 | +# GEMINI_API_KEY_2= | |
| 11 | +# GEMINI_API_KEY_3= | |
| 12 | +# GEMINI_API_KEY_4= | |
| 13 | +# GEMINI_API_KEY_5= | |
| 14 | +# GEMINI_API_KEY_6= | |
| 15 | +# GEMINI_API_KEY_7= | |
| 16 | +# GEMINI_API_KEY_8= | |
| 17 | + | |
| 5 | 18 | # ── Data Source API Keys (optional) ── |
| 6 | 19 | # FIRMS_API_KEY= # NASA FIRMS fire data (https://firms.modaps.eosdis.nasa.gov/api/area/) |
| 7 | 20 | # AIS_API_KEY= # Maritime vessel tracking (aisstream.io) |
modified package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified package.json +1 −0
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | "lint": "eslint" |
| 10 | 10 | }, |
| 11 | 11 | "dependencies": { |
| 12 | + "@google/generative-ai": "^0.24.1", | |
| 12 | 13 | "@vercel/analytics": "^2.0.1", |
| 13 | 14 | "framer-motion": "^12.38.0", |
| 14 | 15 | "google-libphonenumber": "^3.2.44", |
added src/app/api/ai/analyze/route.ts +228 −0
| @@ -0,0 +1,228 @@ | ||
| 1 | +/** | |
| 2 | + * ═══════════════════════════════════════════════════════════════ | |
| 3 | + * OSIRIS — AI Intelligence Analysis Endpoint | |
| 4 | + * POST /api/ai/analyze | |
| 5 | + * Rate-limited, multi-key Gemini integration | |
| 6 | + * ═══════════════════════════════════════════════════════════════ | |
| 7 | + */ | |
| 8 | + | |
| 9 | +import { NextRequest, NextResponse } from 'next/server'; | |
| 10 | +import { | |
| 11 | + createGeminiClient, | |
| 12 | + rotateApiKey, | |
| 13 | + analyzeIntelligence, | |
| 14 | + type IntelligenceContext, | |
| 15 | +} from '@/lib/ai-engine'; | |
| 16 | + | |
| 17 | +export const dynamic = 'force-dynamic'; | |
| 18 | + | |
| 19 | +/* ───────────────────────────────────────────────────────────── | |
| 20 | + Rate Limiter — 5 requests per minute per IP | |
| 21 | + ───────────────────────────────────────────────────────────── */ | |
| 22 | + | |
| 23 | +interface RateLimitEntry { | |
| 24 | + count: number; | |
| 25 | + resetAt: number; | |
| 26 | +} | |
| 27 | + | |
| 28 | +const rateLimitMap = new Map<string, RateLimitEntry>(); | |
| 29 | +const RATE_LIMIT_MAX = 5; | |
| 30 | +const RATE_LIMIT_WINDOW_MS = 60_000; | |
| 31 | + | |
| 32 | +function checkRateLimit(ip: string): { allowed: boolean; remaining: number; resetIn: number } { | |
| 33 | + const now = Date.now(); | |
| 34 | + const entry = rateLimitMap.get(ip); | |
| 35 | + | |
| 36 | + if (!entry || now > entry.resetAt) { | |
| 37 | + rateLimitMap.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS }); | |
| 38 | + return { allowed: true, remaining: RATE_LIMIT_MAX - 1, resetIn: RATE_LIMIT_WINDOW_MS }; | |
| 39 | + } | |
| 40 | + | |
| 41 | + if (entry.count >= RATE_LIMIT_MAX) { | |
| 42 | + return { allowed: false, remaining: 0, resetIn: entry.resetAt - now }; | |
| 43 | + } | |
| 44 | + | |
| 45 | + entry.count++; | |
| 46 | + return { allowed: true, remaining: RATE_LIMIT_MAX - entry.count, resetIn: entry.resetAt - now }; | |
| 47 | +} | |
| 48 | + | |
| 49 | +// Periodic cleanup to prevent memory leaks | |
| 50 | +setInterval(() => { | |
| 51 | + const now = Date.now(); | |
| 52 | + for (const [ip, entry] of rateLimitMap.entries()) { | |
| 53 | + if (now > entry.resetAt) { | |
| 54 | + rateLimitMap.delete(ip); | |
| 55 | + } | |
| 56 | + } | |
| 57 | +}, 120_000); | |
| 58 | + | |
| 59 | +/* ───────────────────────────────────────────────────────────── | |
| 60 | + Collect API keys from environment | |
| 61 | + ───────────────────────────────────────────────────────────── */ | |
| 62 | + | |
| 63 | +function getEnvApiKeys(): string[] { | |
| 64 | + const keys: string[] = []; | |
| 65 | + for (let i = 1; i <= 8; i++) { | |
| 66 | + const key = process.env[`GEMINI_API_KEY_${i}`]; | |
| 67 | + if (key && key.trim().length > 0) { | |
| 68 | + keys.push(key.trim()); | |
| 69 | + } | |
| 70 | + } | |
| 71 | + return keys; | |
| 72 | +} | |
| 73 | + | |
| 74 | +/* ───────────────────────────────────────────────────────────── | |
| 75 | + Request / Response types | |
| 76 | + ───────────────────────────────────────────────────────────── */ | |
| 77 | + | |
| 78 | +interface AnalyzeRequestBody { | |
| 79 | + query: string; | |
| 80 | + context: IntelligenceContext; | |
| 81 | +} | |
| 82 | + | |
| 83 | +interface AnalyzeResponse { | |
| 84 | + analysis: string; | |
| 85 | + model: string; | |
| 86 | + timestamp: string; | |
| 87 | +} | |
| 88 | + | |
| 89 | +interface ErrorResponse { | |
| 90 | + error: string; | |
| 91 | + code: string; | |
| 92 | + retryAfter?: number; | |
| 93 | +} | |
| 94 | + | |
| 95 | +/* ───────────────────────────────────────────────────────────── | |
| 96 | + POST Handler | |
| 97 | + ───────────────────────────────────────────────────────────── */ | |
| 98 | + | |
| 99 | +export async function POST( | |
| 100 | + request: NextRequest | |
| 101 | +): Promise<NextResponse<AnalyzeResponse | ErrorResponse>> { | |
| 102 | + // Extract client IP | |
| 103 | + const ip = | |
| 104 | + request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || | |
| 105 | + request.headers.get('x-real-ip') || | |
| 106 | + 'unknown'; | |
| 107 | + | |
| 108 | + // Rate limit check | |
| 109 | + const rateCheck = checkRateLimit(ip); | |
| 110 | + if (!rateCheck.allowed) { | |
| 111 | + return NextResponse.json( | |
| 112 | + { | |
| 113 | + error: 'Rate limit exceeded. Maximum 5 requests per minute.', | |
| 114 | + code: 'RATE_LIMITED', | |
| 115 | + retryAfter: Math.ceil(rateCheck.resetIn / 1000), | |
| 116 | + }, | |
| 117 | + { | |
| 118 | + status: 429, | |
| 119 | + headers: { | |
| 120 | + 'Retry-After': String(Math.ceil(rateCheck.resetIn / 1000)), | |
| 121 | + 'X-RateLimit-Remaining': '0', | |
| 122 | + 'X-RateLimit-Reset': String(Math.ceil(rateCheck.resetIn / 1000)), | |
| 123 | + }, | |
| 124 | + } | |
| 125 | + ); | |
| 126 | + } | |
| 127 | + | |
| 128 | + // Determine API key — user-provided header takes priority | |
| 129 | + const userKey = request.headers.get('x-gemini-key')?.trim(); | |
| 130 | + let apiKey: string; | |
| 131 | + | |
| 132 | + if (userKey && userKey.length > 0) { | |
| 133 | + apiKey = userKey; | |
| 134 | + } else { | |
| 135 | + const envKeys = getEnvApiKeys(); | |
| 136 | + if (envKeys.length === 0) { | |
| 137 | + return NextResponse.json( | |
| 138 | + { | |
| 139 | + error: | |
| 140 | + 'No Gemini API key configured. Set GEMINI_API_KEY_1 in environment or provide a key via the settings panel.', | |
| 141 | + code: 'NO_API_KEY', | |
| 142 | + }, | |
| 143 | + { status: 503 } | |
| 144 | + ); | |
| 145 | + } | |
| 146 | + apiKey = rotateApiKey(envKeys); | |
| 147 | + } | |
| 148 | + | |
| 149 | + // Parse request body | |
| 150 | + let body: AnalyzeRequestBody; | |
| 151 | + try { | |
| 152 | + body = (await request.json()) as AnalyzeRequestBody; | |
| 153 | + } catch { | |
| 154 | + return NextResponse.json( | |
| 155 | + { error: 'Invalid JSON in request body.', code: 'INVALID_BODY' }, | |
| 156 | + { status: 400 } | |
| 157 | + ); | |
| 158 | + } | |
| 159 | + | |
| 160 | + if (!body.query || typeof body.query !== 'string' || body.query.trim().length === 0) { | |
| 161 | + return NextResponse.json( | |
| 162 | + { error: 'Query field is required and must be a non-empty string.', code: 'MISSING_QUERY' }, | |
| 163 | + { status: 400 } | |
| 164 | + ); | |
| 165 | + } | |
| 166 | + | |
| 167 | + if (!body.context) { | |
| 168 | + return NextResponse.json( | |
| 169 | + { error: 'Intelligence context is required.', code: 'MISSING_CONTEXT' }, | |
| 170 | + { status: 400 } | |
| 171 | + ); | |
| 172 | + } | |
| 173 | + | |
| 174 | + // Call Gemini | |
| 175 | + try { | |
| 176 | + const client = createGeminiClient(apiKey); | |
| 177 | + const analysis = await analyzeIntelligence(client, body.context, body.query.trim()); | |
| 178 | + | |
| 179 | + return NextResponse.json( | |
| 180 | + { | |
| 181 | + analysis, | |
| 182 | + model: 'gemini-2.0-flash', | |
| 183 | + timestamp: new Date().toISOString(), | |
| 184 | + }, | |
| 185 | + { | |
| 186 | + headers: { | |
| 187 | + 'X-RateLimit-Remaining': String(rateCheck.remaining), | |
| 188 | + }, | |
| 189 | + } | |
| 190 | + ); | |
| 191 | + } catch (err: unknown) { | |
| 192 | + const message = err instanceof Error ? err.message : 'Unknown Gemini API error'; | |
| 193 | + | |
| 194 | + // Detect specific Gemini error types | |
| 195 | + if (message.includes('API_KEY_INVALID') || message.includes('API key not valid')) { | |
| 196 | + return NextResponse.json( | |
| 197 | + { error: 'Invalid Gemini API key. Please check your configuration.', code: 'INVALID_KEY' }, | |
| 198 | + { status: 401 } | |
| 199 | + ); | |
| 200 | + } | |
| 201 | + | |
| 202 | + if (message.includes('RESOURCE_EXHAUSTED') || message.includes('quota')) { | |
| 203 | + return NextResponse.json( | |
| 204 | + { | |
| 205 | + error: 'Gemini API quota exhausted. Try again later or provide your own API key.', | |
| 206 | + code: 'QUOTA_EXHAUSTED', | |
| 207 | + }, | |
| 208 | + { status: 429 } | |
| 209 | + ); | |
| 210 | + } | |
| 211 | + | |
| 212 | + if (message.includes('SAFETY')) { | |
| 213 | + return NextResponse.json( | |
| 214 | + { | |
| 215 | + error: 'Response blocked by Gemini safety filters. Try rephrasing your query.', | |
| 216 | + code: 'SAFETY_BLOCKED', | |
| 217 | + }, | |
| 218 | + { status: 422 } | |
| 219 | + ); | |
| 220 | + } | |
| 221 | + | |
| 222 | + console.error('[OSIRIS AI] Analysis error:', message); | |
| 223 | + return NextResponse.json( | |
| 224 | + { error: 'Intelligence analysis failed. Please try again.', code: 'ANALYSIS_FAILED' }, | |
| 225 | + { status: 500 } | |
| 226 | + ); | |
| 227 | + } | |
| 228 | +} |
added src/app/api/ai/briefing/route.ts +210 −0
| @@ -0,0 +1,210 @@ | ||
| 1 | +/** | |
| 2 | + * ═══════════════════════════════════════════════════════════════ | |
| 3 | + * OSIRIS — AI Intelligence Briefing Endpoint | |
| 4 | + * POST /api/ai/briefing | |
| 5 | + * Generates structured threat briefings via Gemini | |
| 6 | + * ═══════════════════════════════════════════════════════════════ | |
| 7 | + */ | |
| 8 | + | |
| 9 | +import { NextRequest, NextResponse } from 'next/server'; | |
| 10 | +import { | |
| 11 | + createGeminiClient, | |
| 12 | + rotateApiKey, | |
| 13 | + generateBriefing, | |
| 14 | + type IntelligenceContext, | |
| 15 | +} from '@/lib/ai-engine'; | |
| 16 | + | |
| 17 | +export const dynamic = 'force-dynamic'; | |
| 18 | + | |
| 19 | +/* ───────────────────────────────────────────────────────────── | |
| 20 | + Rate Limiter — 5 requests per minute per IP | |
| 21 | + ───────────────────────────────────────────────────────────── */ | |
| 22 | + | |
| 23 | +interface RateLimitEntry { | |
| 24 | + count: number; | |
| 25 | + resetAt: number; | |
| 26 | +} | |
| 27 | + | |
| 28 | +const rateLimitMap = new Map<string, RateLimitEntry>(); | |
| 29 | +const RATE_LIMIT_MAX = 5; | |
| 30 | +const RATE_LIMIT_WINDOW_MS = 60_000; | |
| 31 | + | |
| 32 | +function checkRateLimit(ip: string): { allowed: boolean; remaining: number; resetIn: number } { | |
| 33 | + const now = Date.now(); | |
| 34 | + const entry = rateLimitMap.get(ip); | |
| 35 | + | |
| 36 | + if (!entry || now > entry.resetAt) { | |
| 37 | + rateLimitMap.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS }); | |
| 38 | + return { allowed: true, remaining: RATE_LIMIT_MAX - 1, resetIn: RATE_LIMIT_WINDOW_MS }; | |
| 39 | + } | |
| 40 | + | |
| 41 | + if (entry.count >= RATE_LIMIT_MAX) { | |
| 42 | + return { allowed: false, remaining: 0, resetIn: entry.resetAt - now }; | |
| 43 | + } | |
| 44 | + | |
| 45 | + entry.count++; | |
| 46 | + return { allowed: true, remaining: RATE_LIMIT_MAX - entry.count, resetIn: entry.resetAt - now }; | |
| 47 | +} | |
| 48 | + | |
| 49 | +setInterval(() => { | |
| 50 | + const now = Date.now(); | |
| 51 | + for (const [ip, entry] of rateLimitMap.entries()) { | |
| 52 | + if (now > entry.resetAt) { | |
| 53 | + rateLimitMap.delete(ip); | |
| 54 | + } | |
| 55 | + } | |
| 56 | +}, 120_000); | |
| 57 | + | |
| 58 | +/* ───────────────────────────────────────────────────────────── | |
| 59 | + Environment Key Collection | |
| 60 | + ───────────────────────────────────────────────────────────── */ | |
| 61 | + | |
| 62 | +function getEnvApiKeys(): string[] { | |
| 63 | + const keys: string[] = []; | |
| 64 | + for (let i = 1; i <= 8; i++) { | |
| 65 | + const key = process.env[`GEMINI_API_KEY_${i}`]; | |
| 66 | + if (key && key.trim().length > 0) { | |
| 67 | + keys.push(key.trim()); | |
| 68 | + } | |
| 69 | + } | |
| 70 | + return keys; | |
| 71 | +} | |
| 72 | + | |
| 73 | +/* ───────────────────────────────────────────────────────────── | |
| 74 | + Request / Response types | |
| 75 | + ───────────────────────────────────────────────────────────── */ | |
| 76 | + | |
| 77 | +interface BriefingRequestBody { | |
| 78 | + context: IntelligenceContext; | |
| 79 | +} | |
| 80 | + | |
| 81 | +interface BriefingResponse { | |
| 82 | + briefing: string; | |
| 83 | + generatedAt: string; | |
| 84 | +} | |
| 85 | + | |
| 86 | +interface ErrorResponse { | |
| 87 | + error: string; | |
| 88 | + code: string; | |
| 89 | + retryAfter?: number; | |
| 90 | +} | |
| 91 | + | |
| 92 | +/* ───────────────────────────────────────────────────────────── | |
| 93 | + POST Handler | |
| 94 | + ───────────────────────────────────────────────────────────── */ | |
| 95 | + | |
| 96 | +export async function POST( | |
| 97 | + request: NextRequest | |
| 98 | +): Promise<NextResponse<BriefingResponse | ErrorResponse>> { | |
| 99 | + const ip = | |
| 100 | + request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || | |
| 101 | + request.headers.get('x-real-ip') || | |
| 102 | + 'unknown'; | |
| 103 | + | |
| 104 | + const rateCheck = checkRateLimit(ip); | |
| 105 | + if (!rateCheck.allowed) { | |
| 106 | + return NextResponse.json( | |
| 107 | + { | |
| 108 | + error: 'Rate limit exceeded. Maximum 5 requests per minute.', | |
| 109 | + code: 'RATE_LIMITED', | |
| 110 | + retryAfter: Math.ceil(rateCheck.resetIn / 1000), | |
| 111 | + }, | |
| 112 | + { | |
| 113 | + status: 429, | |
| 114 | + headers: { | |
| 115 | + 'Retry-After': String(Math.ceil(rateCheck.resetIn / 1000)), | |
| 116 | + 'X-RateLimit-Remaining': '0', | |
| 117 | + }, | |
| 118 | + } | |
| 119 | + ); | |
| 120 | + } | |
| 121 | + | |
| 122 | + const userKey = request.headers.get('x-gemini-key')?.trim(); | |
| 123 | + let apiKey: string; | |
| 124 | + | |
| 125 | + if (userKey && userKey.length > 0) { | |
| 126 | + apiKey = userKey; | |
| 127 | + } else { | |
| 128 | + const envKeys = getEnvApiKeys(); | |
| 129 | + if (envKeys.length === 0) { | |
| 130 | + return NextResponse.json( | |
| 131 | + { | |
| 132 | + error: | |
| 133 | + 'No Gemini API key configured. Set GEMINI_API_KEY_1 in environment or provide a key via the settings panel.', | |
| 134 | + code: 'NO_API_KEY', | |
| 135 | + }, | |
| 136 | + { status: 503 } | |
| 137 | + ); | |
| 138 | + } | |
| 139 | + apiKey = rotateApiKey(envKeys); | |
| 140 | + } | |
| 141 | + | |
| 142 | + let body: BriefingRequestBody; | |
| 143 | + try { | |
| 144 | + body = (await request.json()) as BriefingRequestBody; | |
| 145 | + } catch { | |
| 146 | + return NextResponse.json( | |
| 147 | + { error: 'Invalid JSON in request body.', code: 'INVALID_BODY' }, | |
| 148 | + { status: 400 } | |
| 149 | + ); | |
| 150 | + } | |
| 151 | + | |
| 152 | + if (!body.context) { | |
| 153 | + return NextResponse.json( | |
| 154 | + { error: 'Intelligence context is required.', code: 'MISSING_CONTEXT' }, | |
| 155 | + { status: 400 } | |
| 156 | + ); | |
| 157 | + } | |
| 158 | + | |
| 159 | + try { | |
| 160 | + const client = createGeminiClient(apiKey); | |
| 161 | + const briefing = await generateBriefing(client, body.context); | |
| 162 | + | |
| 163 | + return NextResponse.json( | |
| 164 | + { | |
| 165 | + briefing, | |
| 166 | + generatedAt: new Date().toISOString(), | |
| 167 | + }, | |
| 168 | + { | |
| 169 | + headers: { | |
| 170 | + 'X-RateLimit-Remaining': String(rateCheck.remaining), | |
| 171 | + }, | |
| 172 | + } | |
| 173 | + ); | |
| 174 | + } catch (err: unknown) { | |
| 175 | + const message = err instanceof Error ? err.message : 'Unknown Gemini API error'; | |
| 176 | + | |
| 177 | + if (message.includes('API_KEY_INVALID') || message.includes('API key not valid')) { | |
| 178 | + return NextResponse.json( | |
| 179 | + { error: 'Invalid Gemini API key. Please check your configuration.', code: 'INVALID_KEY' }, | |
| 180 | + { status: 401 } | |
| 181 | + ); | |
| 182 | + } | |
| 183 | + | |
| 184 | + if (message.includes('RESOURCE_EXHAUSTED') || message.includes('quota')) { | |
| 185 | + return NextResponse.json( | |
| 186 | + { | |
| 187 | + error: 'Gemini API quota exhausted. Try again later or provide your own API key.', | |
| 188 | + code: 'QUOTA_EXHAUSTED', | |
| 189 | + }, | |
| 190 | + { status: 429 } | |
| 191 | + ); | |
| 192 | + } | |
| 193 | + | |
| 194 | + if (message.includes('SAFETY')) { | |
| 195 | + return NextResponse.json( | |
| 196 | + { | |
| 197 | + error: 'Response blocked by Gemini safety filters. Try again.', | |
| 198 | + code: 'SAFETY_BLOCKED', | |
| 199 | + }, | |
| 200 | + { status: 422 } | |
| 201 | + ); | |
| 202 | + } | |
| 203 | + | |
| 204 | + console.error('[OSIRIS AI] Briefing error:', message); | |
| 205 | + return NextResponse.json( | |
| 206 | + { error: 'Briefing generation failed. Please try again.', code: 'BRIEFING_FAILED' }, | |
| 207 | + { status: 500 } | |
| 208 | + ); | |
| 209 | + } | |
| 210 | +} |
modified src/app/api/cctv/greece.ts +14 −38
| @@ -1,47 +1,23 @@ | ||
| 1 | 1 | import type { CctvCamera } from './types'; |
| 2 | 2 | |
| 3 | -const IPCAMLIVE_API_SECRET = process.env.IPCAMLIVE_API_SECRET || ''; | |
| 4 | - | |
| 5 | 3 | const ATTiki_ODOS_CAMERAS = [ |
| 6 | 4 | { alias: 'cam128', name: 'I/C D. Plakentias', city: 'Athens', lat: 38.0208, lng: 23.8578 }, |
| 7 | 5 | { alias: 'cam231', name: 'I/C Papagou', city: 'Athens', lat: 37.9906, lng: 23.7947 }, |
| 8 | 6 | ]; |
| 9 | 7 | |
| 10 | -const GREECE_REGIONAL_CAMERAS: CctvCamera[] = []; | |
| 11 | - | |
| 12 | -async function fetchIpcamLiveHls(alias: string): Promise<string | null> { | |
| 13 | - try { | |
| 14 | - const res = await fetch(`https://ipcamlive.com/api/v2/getstreamhlsurl?apisecret=${IPCAMLIVE_API_SECRET}&alias=${alias}`, { signal: AbortSignal.timeout(5000) }); | |
| 15 | - const data = await res.json(); | |
| 16 | - return data.result === 'ok' ? String(data.data.url).replace(/^http:\/\//i, 'https://') : null; | |
| 17 | - } catch { return null; } | |
| 18 | -} | |
| 19 | - | |
| 20 | -async function fetchIpcamLiveSnapshot(alias: string): Promise<string | null> { | |
| 21 | - try { | |
| 22 | - const res = await fetch(`https://ipcamlive.com/api/v2/getsnapshoturl?apisecret=${IPCAMLIVE_API_SECRET}&alias=${alias}`, { signal: AbortSignal.timeout(5000) }); | |
| 23 | - const data = await res.json(); | |
| 24 | - return data.result === 'ok' ? String(data.data.url).replace(/^http:\/\//i, 'https://') : null; | |
| 25 | - } catch { return null; } | |
| 26 | -} | |
| 27 | - | |
| 28 | 8 | export async function fetchGreeceCameras(): Promise<CctvCamera[]> { |
| 29 | - const attikiSettled = await Promise.allSettled( | |
| 30 | - ATTiki_ODOS_CAMERAS.map(async (cam) => { | |
| 31 | - const hls = await fetchIpcamLiveHls(cam.alias); | |
| 32 | - const snapshot = await fetchIpcamLiveSnapshot(cam.alias); | |
| 33 | - return { | |
| 34 | - id: `gr-aodos-${cam.alias}`, | |
| 35 | - lat: cam.lat, lng: cam.lng, | |
| 36 | - name: cam.name, city: cam.city, country: 'Greece', | |
| 37 | - stream_url: hls || undefined, | |
| 38 | - stream_type: hls ? 'hls' : undefined, | |
| 39 | - feed_url: snapshot || `https://www.aodos.gr/wp-content/themes/aodos/assets/img/cameras/${cam.alias}-snapshot.jpg`, | |
| 40 | - source: 'Attiki Odos', | |
| 41 | - } as CctvCamera; | |
| 42 | - }) | |
| 43 | - ); | |
| 44 | - | |
| 45 | - const attiki = attikiSettled.filter((r): r is PromiseFulfilledResult<CctvCamera> => r.status === 'fulfilled').map((r) => r.value); | |
| 46 | - return [...attiki, ...GREECE_REGIONAL_CAMERAS]; | |
| 9 | + // Using IPCamLive's web player as an iframe stream bypasses the need for API secrets | |
| 10 | + // that were failing for raw HLS/snapshot extraction. | |
| 11 | + return ATTiki_ODOS_CAMERAS.map(cam => ({ | |
| 12 | + id: `gr-aodos-${cam.alias}`, | |
| 13 | + lat: cam.lat, | |
| 14 | + lng: cam.lng, | |
| 15 | + name: cam.name, | |
| 16 | + city: cam.city, | |
| 17 | + country: 'Greece', | |
| 18 | + stream_url: `https://ipcamlive.com/player/player.php?alias=${cam.alias}&autoplay=1`, | |
| 19 | + stream_type: 'iframe', | |
| 20 | + feed_url: `https://ipcamlive.com/player/player.php?alias=${cam.alias}&autoplay=1`, | |
| 21 | + source: 'Attiki Odos', | |
| 22 | + })); | |
| 47 | 23 | } |
modified src/app/api/live-news/route.ts +16 −28
| @@ -11,8 +11,7 @@ | ||
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | 13 | const LIVE_FEEDS = [ |
| 14 | - // ── North America ── | |
| 15 | - // NBC/CBS/ABC/Bloomberg block YouTube embeds for their live streams | |
| 14 | + // ── North America (external only — open in YouTube) ── | |
| 16 | 15 | { id: 'nbcnews', name: 'NBC News NOW', city: 'New York', country: 'US', lat: 40.759, lng: -73.980, url: 'https://www.youtube.com/channel/UCeY0bbntWzzVIaj2z3QigXg/live', embed_allowed: false, category: 'mainstream', language: 'en' }, |
| 17 | 16 | { id: 'cbsnews', name: 'CBS News 24/7', city: 'New York', country: 'US', lat: 40.764, lng: -73.973, url: 'https://www.youtube.com/channel/UC8p1vwvWtl6T73JiExfWs1g/live', embed_allowed: false, category: 'mainstream', language: 'en' }, |
| 18 | 17 | { id: 'abcnews', name: 'ABC News Live', city: 'New York', country: 'US', lat: 40.763, lng: -73.979, url: 'https://www.youtube.com/channel/UCBi2mrWuNuyYy4gbM6fU18Q/live', embed_allowed: false, category: 'mainstream', language: 'en' }, |
| @@ -20,34 +19,23 @@ | ||
| 20 | 19 | { id: 'cspan', name: 'C-SPAN', city: 'Washington DC', country: 'US', lat: 38.897, lng: -77.036, url: 'https://www.youtube.com/channel/UCb--64Gl51jIEVE-GLDAVTg/live', embed_allowed: false, category: 'government', language: 'en' }, |
| 21 | 20 | { id: 'cbc', name: 'CBC News', city: 'Toronto', country: 'CA', lat: 43.644, lng: -79.387, url: 'https://www.youtube.com/channel/UCKy1dAqELon0zgzZPOz9SVw/live', embed_allowed: false, category: 'mainstream', language: 'en' }, |
| 22 | 21 | |
| 23 | - // ── Europe — generally embed-friendly ── | |
| 24 | - { id: 'skynews', name: 'Sky News', city: 'London', country: 'GB', lat: 51.500, lng: -0.118, url: 'https://www.youtube.com/embed/live_stream?channel=UCoMdktPbSTixAyNGwb-UYkQ&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 25 | - { id: 'france24en',name: 'France 24 EN', city: 'Paris', country: 'FR', lat: 48.830, lng: 2.280, url: 'https://www.youtube.com/embed/live_stream?channel=UCQfwfsi5VrQ8yKZ-UWmAEFg&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 26 | - { id: 'dwnews', name: 'DW News', city: 'Berlin', country: 'DE', lat: 52.508, lng: 13.376, url: 'https://www.youtube.com/embed/live_stream?channel=UCknLrEdhRCp1aegoMqRaCZg&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 27 | - { id: 'euronews', name: 'Euronews', city: 'Lyon', country: 'FR', lat: 45.764, lng: 4.836, url: 'https://www.youtube.com/embed/live_stream?channel=UCtUbOIRGKZkW7555n6x6q6g&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 28 | - { id: 'trtworld', name: 'TRT World', city: 'Istanbul',country:'TR', lat: 41.008, lng: 28.978, url: 'https://www.youtube.com/embed/live_stream?channel=UC7fWeaHZQg1p9-4v98L1D1A&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 29 | - { id: 'ukrinform', name: 'UKRINFORM', city: 'Kyiv', country: 'UA', lat: 50.450, lng: 30.523, url: 'https://www.youtube.com/embed/live_stream?channel=UCaDkCK6iFHPE0lmpaYL-WxQ&autoplay=1&mute=1', embed_allowed: true, category: 'conflict', language: 'en' }, | |
| 30 | - | |
| 31 | - // ── Middle East / Africa ── | |
| 32 | - { id: 'aljazeera', name: 'Al Jazeera EN', city: 'Doha', country: 'QA', lat: 25.286, lng: 51.534, url: 'https://www.youtube.com/embed/live_stream?channel=UCNye-wNBqNL5ZzHSJj3l8Bg&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 33 | - { id: 'almayadeen',name: 'Al Mayadeen', city: 'Beirut', country: 'LB', lat: 33.888, lng: 35.495, url: 'https://www.youtube.com/embed/live_stream?channel=UCZCFHCU-2eGF7V5ciMkoPHw&autoplay=1&mute=1', embed_allowed: true, category: 'conflict', language: 'ar' }, | |
| 34 | - { id: 'lbcilebanon',name:'LBCI Lebanon', city: 'Beirut', country: 'LB', lat: 33.893, lng: 35.501, url: 'https://www.youtube.com/embed/live_stream?channel=UCpE6gpKewomi17XDyPfpFjA&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'ar' }, | |
| 35 | - { id: 'africanews', name: 'Africanews', city: 'Pointe-Noire', country: 'CG', lat: -4.778, lng: 11.865, url: 'https://www.youtube.com/embed/live_stream?channel=UC5T2fB_W0Z31T0c8yN36a8A&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 36 | - { id: 'sabcnews', name: 'SABC News', city: 'Johannesburg', country: 'ZA', lat:-26.204, lng: 28.047, url: 'https://www.youtube.com/embed/live_stream?channel=UC8yH-uI81UUtEMDsowQyx1g&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 37 | - | |
| 38 | - // ── Asia Pacific ── | |
| 39 | - { id: 'nhkworld', name: 'NHK World', city: 'Tokyo', country: 'JP', lat: 35.690, lng: 139.692, url: 'https://www.youtube.com/embed/live_stream?channel=UCSPEjw8F2nQDtmUKPFNF7_A&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 40 | - { id: 'cna', name: 'CNA 24/7', city: 'Singapore', country: 'SG', lat: 1.290, lng: 103.852, url: 'https://www.youtube.com/embed/live_stream?channel=UC83jt4dlz1Gjl58fzQrrKZg&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 41 | - { id: 'wion', name: 'WION', city: 'New Delhi', country: 'IN', lat: 28.614, lng: 77.209, url: 'https://www.youtube.com/embed/live_stream?channel=UC_gUM8rL-Lrg6O3adPW9K1g&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 42 | - { id: 'abcau', name: 'ABC Australia',city: 'Sydney', country: 'AU', lat:-33.867, lng: 151.207, url: 'https://www.youtube.com/embed/live_stream?channel=UC5iLnYoF4Ryb63YdGD9RfWQ&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 43 | - { id: 'arirang', name: 'Arirang TV', city: 'Seoul', country: 'KR', lat: 37.566, lng: 126.978, url: 'https://www.youtube.com/embed/live_stream?channel=UCw9-5Y1CjW7Qy1Yf5q1y2-Q&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 22 | + // ── Europe (verified embeddable) ── | |
| 23 | + { id: 'skynews', name: 'Sky News', city: 'London', country: 'GB', lat: 51.500, lng: -0.118, url: 'https://www.youtube.com/embed/live_stream?channel=UCoMdktPbSTixAyNGwb-UYkQ&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 24 | + { id: 'france24en', name: 'France 24 EN', city: 'Paris', country: 'FR', lat: 48.830, lng: 2.280, url: 'https://www.youtube.com/embed/live_stream?channel=UCQfwfsi5VrQ8yKZ-UWmAEFg&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 25 | + { id: 'dwnews', name: 'DW News', city: 'Berlin', country: 'DE', lat: 52.508, lng: 13.376, url: 'https://www.youtube.com/embed/live_stream?channel=UCknLrEdhRCp1aegoMqRaCZg&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 26 | + | |
| 27 | + // ── Middle East ── | |
| 28 | + { id: 'aljazeera', name: 'Al Jazeera EN', city: 'Doha', country: 'QA', lat: 25.286, lng: 51.534, url: 'https://www.youtube.com/embed/live_stream?channel=UCNye-wNBqNL5ZzHSJj3l8Bg&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 29 | + | |
| 30 | + // ── Asia Pacific (verified embeddable) ── | |
| 31 | + { id: 'nhkworld', name: 'NHK World', city: 'Tokyo', country: 'JP', lat: 35.690, lng: 139.692, url: 'https://www.youtube.com/embed/live_stream?channel=UCSPEjw8F2nQDtmUKPFNF7_A&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 32 | + { id: 'cna', name: 'CNA 24/7', city: 'Singapore', country: 'SG', lat: 1.290, lng: 103.852, url: 'https://www.youtube.com/embed/live_stream?channel=UC83jt4dlz1Gjl58fzQrrKZg&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 33 | + { id: 'wion', name: 'WION', city: 'New Delhi', country: 'IN', lat: 28.614, lng: 77.209, url: 'https://www.youtube.com/embed/live_stream?channel=UC_gUM8rL-Lrg6O3adPW9K1g&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 44 | 34 | // CGTN blocks embeds from non-Chinese IPs often |
| 45 | - { id: 'cgtn', name: 'CGTN', city: 'Beijing', country: 'CN', lat: 39.904, lng: 116.407, url: 'https://www.youtube.com/channel/UCgrNz-aDmcr2uuto8_DL2jg/live', embed_allowed: false, category: 'state', language: 'en' }, | |
| 35 | + { id: 'cgtn', name: 'CGTN', city: 'Beijing', country: 'CN', lat: 39.904, lng: 116.407, url: 'https://www.youtube.com/channel/UCgrNz-aDmcr2uuto8_DL2jg/live', embed_allowed: false, category: 'state', language: 'en' }, | |
| 46 | 36 | |
| 47 | - // ── Latin America / State ── | |
| 48 | - { id: 'telesur', name: 'teleSUR EN', city: 'Caracas', country: 'VE', lat: 10.491, lng: -66.902, url: 'https://www.youtube.com/embed/live_stream?channel=UCmuTmpLY35O3csvhyA6vrkg&autoplay=1&mute=1', embed_allowed: true, category: 'mainstream', language: 'en' }, | |
| 49 | - // RT is blocked/removed from YouTube in many regions — external link only | |
| 50 | - { id: 'rt', name: 'RT News', city: 'Moscow', country: 'RU', lat: 55.755, lng: 37.617, url: 'https://rumble.com/c/RTNewsEN', embed_allowed: false, category: 'state', language: 'en' }, | |
| 37 | + // ── State media (external only) ── | |
| 38 | + { id: 'rt', name: 'RT News', city: 'Moscow', country: 'RU', lat: 55.755, lng: 37.617, url: 'https://rumble.com/c/RTNewsEN', embed_allowed: false, category: 'state', language: 'en' }, | |
| 51 | 39 | ]; |
| 52 | 40 | |
| 53 | 41 | export async function GET() { |
modified src/app/globals.css +10 −23
| @@ -32,6 +32,10 @@ | ||
| 32 | 32 | --alert-green: #00E676; |
| 33 | 33 | --alert-blue: #448AFF; |
| 34 | 34 | |
| 35 | + /* ── Accent Colors (layer-specific) ── */ | |
| 36 | + --accent-weather: #E040FB; | |
| 37 | + --accent-nuclear: #76FF03; | |
| 38 | + | |
| 35 | 39 | /* ── Borders ── */ |
| 36 | 40 | --border-primary: rgba(212, 175, 55, 0.15); |
| 37 | 41 | --border-secondary: rgba(212, 175, 55, 0.08); |
| @@ -196,6 +200,12 @@ | ||
| 196 | 200 | .animate-data-pulse { animation: data-pulse 2s ease-in-out infinite; } |
| 197 | 201 | .animate-threat-flash { animation: threat-flash 1.5s ease-in-out infinite; } |
| 198 | 202 | |
| 203 | +/* Splash screen scanline drift */ | |
| 204 | +@keyframes splashScanDrift { | |
| 205 | + 0% { background-position: 0 0; } | |
| 206 | + 100% { background-position: 0 100vh; } | |
| 207 | +} | |
| 208 | + | |
| 199 | 209 | /* Ticker scroll — pure CSS, GPU-accelerated */ |
| 200 | 210 | @keyframes ticker-scroll { |
| 201 | 211 | 0% { transform: translateX(0); } |
| @@ -394,29 +404,6 @@ | ||
| 394 | 404 | .glass-panel { min-width: 320px; } |
| 395 | 405 | } |
| 396 | 406 | |
| 397 | -/* Ensure popups scale properly on all displays */ | |
| 398 | -.maplibregl-popup-content { | |
| 399 | - background: transparent !important; | |
| 400 | - box-shadow: none !important; | |
| 401 | - padding: 0 !important; | |
| 402 | - border: none !important; | |
| 403 | -} | |
| 404 | - | |
| 405 | -.maplibregl-popup-close-button { | |
| 406 | - color: var(--text-muted) !important; | |
| 407 | - font-size: 18px !important; | |
| 408 | - padding: 4px 8px !important; | |
| 409 | - right: 4px !important; | |
| 410 | - top: 4px !important; | |
| 411 | - z-index: 10; | |
| 412 | -} | |
| 413 | - | |
| 414 | -.maplibregl-popup-close-button:hover { | |
| 415 | - color: var(--gold-primary) !important; | |
| 416 | - background: rgba(212, 175, 55, 0.1) !important; | |
| 417 | - border-radius: 4px; | |
| 418 | -} | |
| 419 | - | |
| 420 | 407 | /* ═══════════════════════════════════════════════════════════════ |
| 421 | 408 | ENHANCED DESIGN SYSTEM — Premium Components & Micro-Interactions |
| 422 | 409 | ═══════════════════════════════════════════════════════════════ */ |
modified src/app/page.tsx +41 −65
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | import { useEffect, useState, useRef, useCallback, useMemo } from 'react'; |
| 4 | 4 | import dynamic from 'next/dynamic'; |
| 5 | 5 | import { motion, AnimatePresence } from 'framer-motion'; |
| 6 | -import { Layers, BarChart3, Newspaper, Search, Share2, Map as MapIcon, X, Globe, MapPinned, Radar, Satellite, Moon, ExternalLink, AlertTriangle, Building2, RadioTower, Activity, Shield, Database, Wifi } from 'lucide-react'; | |
| 6 | +import { Layers, BarChart3, Newspaper, Search, X, Globe, MapPinned, Radar, Satellite, Moon, ExternalLink, AlertTriangle, Activity, Database, Wifi } from 'lucide-react'; | |
| 7 | 7 | import IntelFeed from '@/components/IntelFeed'; |
| 8 | 8 | import MarketsPanel from '@/components/MarketsPanel'; |
| 9 | 9 | import ScmPanel from '@/components/ScmPanel'; |
| @@ -65,32 +65,22 @@ | ||
| 65 | 65 | return <span className="text-[var(--cyan-primary)] font-bold tabular-nums">{time || 'ZULU --:--:--Z'}</span>; |
| 66 | 66 | }; |
| 67 | 67 | |
| 68 | -const DataThroughput = ({ data }: { data: any }) => { | |
| 69 | - const [throughput, setThroughput] = useState('0.00'); | |
| 70 | - const [pingTime, setPingTime] = useState<number | null>(null); | |
| 71 | - | |
| 72 | - useEffect(() => { | |
| 73 | - const iv = setInterval(() => { | |
| 74 | - let estimatedBytes = 0; | |
| 75 | - if (data) { | |
| 76 | - if (data.satellites) estimatedBytes += data.satellites.length * 150; | |
| 77 | - if (data.commercial_flights) estimatedBytes += data.commercial_flights.length * 120; | |
| 78 | - if (data.cameras) estimatedBytes += data.cameras.length * 80; | |
| 79 | - if (data.gdelt) estimatedBytes += data.gdelt.length * 300; | |
| 80 | - if (data.live_feeds) estimatedBytes += data.live_feeds.length * 500; | |
| 81 | - } | |
| 82 | - | |
| 83 | - const megabytes = estimatedBytes / 1024 / 1024; | |
| 84 | - setThroughput(megabytes > 0 ? (megabytes * 1.5).toFixed(2) : "0.00"); | |
| 85 | - | |
| 86 | - setPingTime(Math.floor(30 + estimatedBytes / 100000)); | |
| 87 | - }, 2500); | |
| 88 | - return () => clearInterval(iv); | |
| 68 | +/** Real entity count — no fake throughput metrics */ | |
| 69 | +const ActiveEntityCount = ({ data }: { data: Record<string, unknown[]> }) => { | |
| 70 | + const count = useMemo(() => { | |
| 71 | + if (!data) return 0; | |
| 72 | + return Object.values(data).reduce((sum, v) => sum + (Array.isArray(v) ? v.length : 0), 0); | |
| 89 | 73 | }, [data]); |
| 90 | - | |
| 91 | - return <span className="text-[var(--alert-green)] font-bold tabular-nums">{throughput} MB/s</span>; | |
| 74 | + return <span className="text-[var(--alert-green)] font-bold tabular-nums">{count.toLocaleString()}</span>; | |
| 92 | 75 | }; |
| 93 | 76 | |
| 77 | +/** Extracts a watchable YouTube URL from embed/channel URLs */ | |
| 78 | +function getYouTubeWatchUrl(url: string): string { | |
| 79 | + if (url.includes('channel=')) return `https://www.youtube.com/channel/${url.split('channel=')[1].split('&')[0]}/live`; | |
| 80 | + if (url.includes('/embed/')) return `https://www.youtube.com/watch?v=${url.split('/embed/')[1].split('?')[0]}`; | |
| 81 | + return url; | |
| 82 | +} | |
| 83 | + | |
| 94 | 84 | export default function Dashboard() { |
| 95 | 85 | const dataRef = useRef<any>({}); |
| 96 | 86 | const [dataVersion, setDataVersion] = useState(0); |
| @@ -186,8 +176,8 @@ | ||
| 186 | 176 | if (urlTimer.current) clearTimeout(urlTimer.current); |
| 187 | 177 | urlTimer.current = setTimeout(() => { |
| 188 | 178 | const p = new URLSearchParams(); |
| 189 | - p.set('lat', (mouseCoordsRef.current?.lat ?? mapView.latitude ?? 20).toFixed(4)); | |
| 190 | - p.set('lon', (mouseCoordsRef.current?.lng ?? 0).toFixed(4)); | |
| 179 | + p.set('lat', (mapView.latitude ?? 20).toFixed(4)); | |
| 180 | + p.set('lon', '0'); | |
| 191 | 181 | p.set('zoom', mapView.zoom.toFixed(2)); |
| 192 | 182 | const active = Object.entries(activeLayers).filter(([,v]) => v).map(([k]) => k).join(','); |
| 193 | 183 | p.set('layers', active); |
| @@ -213,7 +203,6 @@ | ||
| 213 | 203 | if (e.key === 'f' && !e.ctrlKey) { |
| 214 | 204 | if (document.fullscreenElement) document.exitFullscreen(); |
| 215 | 205 | else document.documentElement.requestFullscreen(); |
| 216 | - setIsFullscreen(!!document.fullscreenElement); | |
| 217 | 206 | } |
| 218 | 207 | if (e.key === 'l') setShowLayers(p => !p); |
| 219 | 208 | if (e.key === 'm') setShowMarkets(p => !p); |
| @@ -222,8 +211,10 @@ | ||
| 222 | 211 | if (e.key === 'r') setFlyToLocation({ lat: 20, lng: 0, ts: Date.now() }); |
| 223 | 212 | if (e.key === 'g') setMapProjection(p => p === 'globe' ? 'mercator' : 'globe'); |
| 224 | 213 | }; |
| 214 | + const fsHandler = () => setIsFullscreen(!!document.fullscreenElement); | |
| 225 | 215 | window.addEventListener('keydown', handler); |
| 226 | - return () => window.removeEventListener('keydown', handler); | |
| 216 | + document.addEventListener('fullscreenchange', fsHandler); | |
| 217 | + return () => { window.removeEventListener('keydown', handler); document.removeEventListener('fullscreenchange', fsHandler); }; | |
| 227 | 218 | }, []); |
| 228 | 219 | |
| 229 | 220 | // Mouse coords + reverse geocode (Zero-Render) |
| @@ -343,7 +334,7 @@ | ||
| 343 | 334 | } |
| 344 | 335 | // CCTV |
| 345 | 336 | if (activeLayers.cctv && !layerFetchedRef.current.has('cctv')) { |
| 346 | - fetchEndpoint('/api/cctv?region=all'); | |
| 337 | + fetchEndpoint('/api/cctv?region=all&v=2'); | |
| 347 | 338 | layerFetchedRef.current.add('cctv'); |
| 348 | 339 | } |
| 349 | 340 | // Maritime |
| @@ -400,10 +391,6 @@ | ||
| 400 | 391 | if (activeLayers.maritime) { |
| 401 | 392 | intervals.push(setInterval(() => fetchEndpoint('/api/maritime', d => ({ maritime_ports: d.ports, maritime_chokepoints: d.chokepoints, maritime_ships: d.ships })), 10000)); // 10s |
| 402 | 393 | } |
| 403 | - if (activeLayers.scm_suppliers) { | |
| 404 | - intervals.push(setInterval(() => fetchEndpoint('/api/scm-suppliers', d => ({ scm_suppliers: d.suppliers })), 30000)); // 30s | |
| 405 | - } | |
| 406 | - // Fires: no polling needed (data changes very slowly, initial fetch is enough) | |
| 407 | 394 | return () => intervals.forEach(clearInterval); |
| 408 | 395 | }, [activeLayers, fetchEndpoint]); |
| 409 | 396 | |
| @@ -606,12 +593,7 @@ | ||
| 606 | 593 | |
| 607 | 594 | |
| 608 | 595 | {/* ── Inline keyframe for scanline drift ── */} |
| 609 | - <style>{` | |
| 610 | - @keyframes splashScanDrift { | |
| 611 | - 0% { background-position: 0 0; } | |
| 612 | - 100% { background-position: 0 100vh; } | |
| 613 | - } | |
| 614 | - `}</style> | |
| 596 | + | |
| 615 | 597 | </motion.div> |
| 616 | 598 | )} |
| 617 | 599 | </AnimatePresence> |
| @@ -754,8 +736,8 @@ | ||
| 754 | 736 | <div><div className="hud-label">AIRCRAFT</div><div className="hud-value text-[10px] animate-data-pulse">{globalStats ? globalStats.flights.toLocaleString() : '0'}</div></div> |
| 755 | 737 | <div><div className="hud-label">SATS</div><div className="hud-value text-[10px]">{globalStats ? globalStats.sats.toLocaleString() : '0'}</div></div> |
| 756 | 738 | <div><div className="hud-label">CCTV</div><div className="hud-value text-[10px]">{globalStats ? globalStats.cctv.toLocaleString() : '0'}</div></div> |
| 757 | - <div><div className="hud-label">WEATHER</div><div className="hud-value text-[10px]" style={{ color: '#E040FB' }}>{globalStats ? globalStats.weather.toLocaleString() : '0'}</div></div> | |
| 758 | - <div><div className="hud-label">NUCLEAR</div><div className="hud-value text-[10px]" style={{ color: '#76FF03' }}>{globalStats ? globalStats.nuclear.toLocaleString() : '0'}</div></div> | |
| 739 | + <div><div className="hud-label">WEATHER</div><div className="hud-value text-[10px]" style={{ color: 'var(--accent-weather)' }}>{globalStats ? globalStats.weather.toLocaleString() : '0'}</div></div> | |
| 740 | + <div><div className="hud-label">NUCLEAR</div><div className="hud-value text-[10px]" style={{ color: 'var(--accent-nuclear)' }}>{globalStats ? globalStats.nuclear.toLocaleString() : '0'}</div></div> | |
| 759 | 741 | </div> |
| 760 | 742 | </motion.div> |
| 761 | 743 | <ViewPresets onNavigate={(lat, lng, zoom) => { setFlyToLocation({ lat, lng, ts: Date.now() }); setMapView(v => ({ ...v, zoom })); }} /> |
| @@ -810,13 +792,7 @@ | ||
| 810 | 792 | </div> |
| 811 | 793 | <div className="flex items-center gap-3"> |
| 812 | 794 | <a |
| 813 | - href={ | |
| 814 | - liveFeedUrl.includes('channel=') | |
| 815 | - ? `https://www.youtube.com/channel/${liveFeedUrl.split('channel=')[1].split('&')[0]}/live` | |
| 816 | - : liveFeedUrl.includes('/embed/') | |
| 817 | - ? `https://www.youtube.com/watch?v=${liveFeedUrl.split('/embed/')[1].split('?')[0]}` | |
| 818 | - : liveFeedUrl | |
| 819 | - } | |
| 795 | + href={getYouTubeWatchUrl(liveFeedUrl)} | |
| 820 | 796 | target="_blank" |
| 821 | 797 | rel="noopener noreferrer" |
| 822 | 798 | className="flex items-center gap-1.5 px-2.5 py-1 rounded bg-[var(--border-primary)] hover:bg-[var(--gold-primary)] hover:text-black text-white transition-colors text-[11px] font-mono" |
| @@ -851,13 +827,7 @@ | ||
| 851 | 827 | {liveFeedName} does not allow third-party embedding. Click below to open the live stream directly. |
| 852 | 828 | </p> |
| 853 | 829 | <a |
| 854 | - href={ | |
| 855 | - liveFeedUrl.includes('channel=') | |
| 856 | - ? `https://www.youtube.com/channel/${liveFeedUrl.split('channel=')[1].split('&')[0]}/live` | |
| 857 | - : liveFeedUrl.includes('/embed/') | |
| 858 | - ? `https://www.youtube.com/watch?v=${liveFeedUrl.split('/embed/')[1].split('?')[0]}` | |
| 859 | - : liveFeedUrl | |
| 860 | - } | |
| 830 | + href={getYouTubeWatchUrl(liveFeedUrl)} | |
| 861 | 831 | target="_blank" |
| 862 | 832 | rel="noopener noreferrer" |
| 863 | 833 | className="inline-flex items-center gap-2 px-6 py-2.5 rounded border border-[#39FF14]/40 text-[#39FF14] font-mono text-[12px] hover:bg-[#39FF14]/10 transition-colors tracking-wider" |
| @@ -929,8 +899,8 @@ | ||
| 929 | 899 | <div><div className="hud-label" style={{fontSize:'6px'}}>AIR</div><div className="hud-value text-[9px]">{totalFlights.toLocaleString()}</div></div> |
| 930 | 900 | <div><div className="hud-label" style={{fontSize:'6px'}}>SAT</div><div className="hud-value text-[9px]">{(data.satellites?.length||0)}</div></div> |
| 931 | 901 | <div><div className="hud-label" style={{fontSize:'6px'}}>CAM</div><div className="hud-value text-[9px]">{(data.cameras?.length||0)}</div></div> |
| 932 | - <div><div className="hud-label" style={{fontSize:'6px'}}>WX</div><div className="hud-value text-[9px]" style={{color:'#E040FB'}}>{(data.weather_events?.length||0)}</div></div> | |
| 933 | - <div><div className="hud-label" style={{fontSize:'6px'}}>NUC</div><div className="hud-value text-[9px]" style={{color:'#76FF03'}}>{(data.infrastructure?.length||0)}</div></div> | |
| 902 | + <div><div className="hud-label" style={{fontSize:'6px'}}>WX</div><div className="hud-value text-[9px]" style={{color:'var(--accent-weather)'}}>{(data.weather_events?.length||0)}</div></div> | |
| 903 | + <div><div className="hud-label" style={{fontSize:'6px'}}>NUC</div><div className="hud-value text-[9px]" style={{color:'var(--accent-nuclear)'}}>{(data.infrastructure?.length||0)}</div></div> | |
| 934 | 904 | </div> |
| 935 | 905 | </div> |
| 936 | 906 | <LayerPanel data={data} activeLayers={activeLayers} setActiveLayers={setActiveLayers} /> |
| @@ -1015,12 +985,12 @@ | ||
| 1015 | 985 | |
| 1016 | 986 | <div className="w-px h-8 bg-gradient-to-b from-transparent via-[var(--border-primary)] to-transparent flex-shrink-0" /> |
| 1017 | 987 | |
| 1018 | - {/* THROUGHPUT */} | |
| 988 | + {/* ENTITIES */} | |
| 1019 | 989 | <div className="flex flex-col items-center px-3 min-w-[70px]"> |
| 1020 | - <div className="hud-label">THROUGHPUT</div> | |
| 990 | + <div className="hud-label">ENTITIES</div> | |
| 1021 | 991 | <div className="flex items-center gap-1"> |
| 1022 | 992 | <Database className="w-3 h-3 text-[var(--alert-green)]" /> |
| 1023 | - <DataThroughput data={data} /> | |
| 993 | + <ActiveEntityCount data={data} /> | |
| 1024 | 994 | </div> |
| 1025 | 995 | </div> |
| 1026 | 996 | |
| @@ -1074,14 +1044,20 @@ | ||
| 1074 | 1044 | onLocate={(lat, lng) => setFlyToLocation({ lat, lng, ts: Date.now() })} |
| 1075 | 1045 | /> |
| 1076 | 1046 | |
| 1047 | + | |
| 1077 | 1048 | {/* ── OVERLAYS ── */} |
| 1078 | 1049 | <div className="vignette absolute inset-0 pointer-events-none z-[2]" /> |
| 1079 | 1050 | <div className="crt-scanlines absolute inset-0 pointer-events-none z-[3] opacity-[0.02]" /> |
| 1080 | - {/* Corner frames */} | |
| 1081 | - {['top-0 left-0','top-0 right-0','bottom-0 left-0','bottom-0 right-0'].map((pos, i) => ( | |
| 1082 | - <div key={i} className={`absolute ${pos} w-16 h-16 pointer-events-none z-[1]`}> | |
| 1083 | - <div className={`absolute ${pos.includes('top') ? 'top-0' : 'bottom-0'} ${pos.includes('left') ? 'left-0' : 'right-0'} w-full h-[1px] bg-gradient-to-${pos.includes('left') ? 'r' : 'l'} from-[var(--gold-primary)]/30 to-transparent`} /> | |
| 1084 | - <div className={`absolute ${pos.includes('top') ? 'top-0' : 'bottom-0'} ${pos.includes('left') ? 'left-0' : 'right-0'} w-[1px] h-full bg-gradient-to-${pos.includes('top') ? 'b' : 't'} from-[var(--gold-primary)]/30 to-transparent`} /> | |
| 1051 | + {/* Corner frames — using explicit classes for Tailwind JIT compatibility */} | |
| 1052 | + {[ | |
| 1053 | + { pos: 'top-0 left-0', vAnchor: 'top-0', hAnchor: 'left-0', hGrad: 'bg-gradient-to-r', vGrad: 'bg-gradient-to-b' }, | |
| 1054 | + { pos: 'top-0 right-0', vAnchor: 'top-0', hAnchor: 'right-0', hGrad: 'bg-gradient-to-l', vGrad: 'bg-gradient-to-b' }, | |
| 1055 | + { pos: 'bottom-0 left-0', vAnchor: 'bottom-0', hAnchor: 'left-0', hGrad: 'bg-gradient-to-r', vGrad: 'bg-gradient-to-t' }, | |
| 1056 | + { pos: 'bottom-0 right-0', vAnchor: 'bottom-0', hAnchor: 'right-0', hGrad: 'bg-gradient-to-l', vGrad: 'bg-gradient-to-t' }, | |
| 1057 | + ].map((c, i) => ( | |
| 1058 | + <div key={i} className={`absolute ${c.pos} w-16 h-16 pointer-events-none z-[1]`}> | |
| 1059 | + <div className={`absolute ${c.vAnchor} ${c.hAnchor} w-full h-[1px] ${c.hGrad} from-[var(--gold-primary)]/30 to-transparent`} /> | |
| 1060 | + <div className={`absolute ${c.vAnchor} ${c.hAnchor} w-[1px] h-full ${c.vGrad} from-[var(--gold-primary)]/30 to-transparent`} /> | |
| 1085 | 1061 | </div> |
| 1086 | 1062 | ))} |
| 1087 | 1063 |
added src/components/AiAnalyst.tsx +831 −0
| @@ -0,0 +1,831 @@ | ||
| 1 | +'use client'; | |
| 2 | + | |
| 3 | +import { useState, useRef, useEffect, useCallback } from 'react'; | |
| 4 | +import { motion, AnimatePresence } from 'framer-motion'; | |
| 5 | +import { | |
| 6 | + Brain, | |
| 7 | + Send, | |
| 8 | + Sparkles, | |
| 9 | + Settings, | |
| 10 | + X, | |
| 11 | + Bot, | |
| 12 | + User, | |
| 13 | + AlertTriangle, | |
| 14 | + Shield, | |
| 15 | + ChevronDown, | |
| 16 | + Loader2, | |
| 17 | + Key, | |
| 18 | + Check, | |
| 19 | + Trash2, | |
| 20 | +} from 'lucide-react'; | |
| 21 | +import type { IntelligenceContext } from '@/lib/ai-engine'; | |
| 22 | + | |
| 23 | +/* ═══════════════════════════════════════════════════════════════ | |
| 24 | + OSIRIS — AI Intelligence Analyst Panel | |
| 25 | + Premium glass-panel chat interface for real-time intelligence | |
| 26 | + analysis powered by Gemini 2.0 Flash | |
| 27 | + ═══════════════════════════════════════════════════════════════ */ | |
| 28 | + | |
| 29 | +/* ───────────────────────────────────────────────────────────── | |
| 30 | + Interfaces | |
| 31 | + ───────────────────────────────────────────────────────────── */ | |
| 32 | + | |
| 33 | +interface DashboardData { | |
| 34 | + earthquakes?: EarthquakeItem[]; | |
| 35 | + news?: NewsItem[]; | |
| 36 | + gdelt?: GdeltEvent[]; | |
| 37 | + markets?: MarketData; | |
| 38 | + [key: string]: unknown; | |
| 39 | +} | |
| 40 | + | |
| 41 | +interface EarthquakeItem { | |
| 42 | + id: string; | |
| 43 | + magnitude: number; | |
| 44 | + location: string; | |
| 45 | + lat: number; | |
| 46 | + lng: number; | |
| 47 | + depth: number; | |
| 48 | + time: string; | |
| 49 | + tsunami: boolean; | |
| 50 | + felt: number | null; | |
| 51 | + alert: string | null; | |
| 52 | +} | |
| 53 | + | |
| 54 | +interface NewsItem { | |
| 55 | + id: string; | |
| 56 | + title: string; | |
| 57 | + description: string; | |
| 58 | + link: string; | |
| 59 | + published: string; | |
| 60 | + source: string; | |
| 61 | + risk_score: number; | |
| 62 | + coords: [number, number] | null; | |
| 63 | + machine_assessment: string | null; | |
| 64 | +} | |
| 65 | + | |
| 66 | +interface GdeltEvent { | |
| 67 | + title: string; | |
| 68 | + type: string; | |
| 69 | + lat: number; | |
| 70 | + lng: number; | |
| 71 | + date: string; | |
| 72 | + source: string; | |
| 73 | + tone: number; | |
| 74 | +} | |
| 75 | + | |
| 76 | +interface MarketData { | |
| 77 | + indices?: MarketIndex[]; | |
| 78 | + commodities?: MarketCommodity[]; | |
| 79 | +} | |
| 80 | + | |
| 81 | +interface MarketIndex { | |
| 82 | + name: string; | |
| 83 | + value: number; | |
| 84 | + change: number; | |
| 85 | + changePercent: number; | |
| 86 | +} | |
| 87 | + | |
| 88 | +interface MarketCommodity { | |
| 89 | + name: string; | |
| 90 | + price: number; | |
| 91 | + change: number; | |
| 92 | +} | |
| 93 | + | |
| 94 | +interface ChatMessage { | |
| 95 | + id: string; | |
| 96 | + role: 'user' | 'analyst'; | |
| 97 | + content: string; | |
| 98 | + timestamp: string; | |
| 99 | + isError?: boolean; | |
| 100 | +} | |
| 101 | + | |
| 102 | +interface AiAnalystProps { | |
| 103 | + data: DashboardData; | |
| 104 | +} | |
| 105 | + | |
| 106 | +/* ───────────────────────────────────────────────────────────── | |
| 107 | + Helpers | |
| 108 | + ───────────────────────────────────────────────────────────── */ | |
| 109 | + | |
| 110 | +function generateId(): string { | |
| 111 | + return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`; | |
| 112 | +} | |
| 113 | + | |
| 114 | +function buildContext(data: DashboardData): IntelligenceContext { | |
| 115 | + const earthquakes = (data.earthquakes || []).slice(0, 20).map((eq) => ({ | |
| 116 | + id: eq.id || generateId(), | |
| 117 | + magnitude: eq.magnitude, | |
| 118 | + location: eq.location, | |
| 119 | + latitude: eq.lat, | |
| 120 | + longitude: eq.lng, | |
| 121 | + depth: eq.depth, | |
| 122 | + timestamp: eq.time, | |
| 123 | + tsunami: eq.tsunami ?? false, | |
| 124 | + felt: eq.felt ?? null, | |
| 125 | + alert: eq.alert ?? null, | |
| 126 | + })); | |
| 127 | + | |
| 128 | + const news = (data.news || []).slice(0, 15).map((item) => ({ | |
| 129 | + id: item.id || generateId(), | |
| 130 | + title: item.title, | |
| 131 | + description: item.description || '', | |
| 132 | + link: item.link || '', | |
| 133 | + published: item.published, | |
| 134 | + source: item.source, | |
| 135 | + risk_score: item.risk_score, | |
| 136 | + coords: item.coords, | |
| 137 | + machine_assessment: item.machine_assessment, | |
| 138 | + })); | |
| 139 | + | |
| 140 | + const threats = (data.gdelt || []).slice(0, 15).map((ev) => ({ | |
| 141 | + id: generateId(), | |
| 142 | + type: ev.type || 'INCIDENT', | |
| 143 | + title: ev.title, | |
| 144 | + description: ev.title, | |
| 145 | + severity: (ev.tone < -5 ? 'CRITICAL' : ev.tone < -2 ? 'HIGH' : ev.tone < 0 ? 'ELEVATED' : 'LOW') as | |
| 146 | + | 'CRITICAL' | |
| 147 | + | 'HIGH' | |
| 148 | + | 'ELEVATED' | |
| 149 | + | 'LOW', | |
| 150 | + region: ev.source || 'Unknown', | |
| 151 | + latitude: ev.lat, | |
| 152 | + longitude: ev.lng, | |
| 153 | + timestamp: ev.date, | |
| 154 | + source: ev.source || 'GDELT', | |
| 155 | + })); | |
| 156 | + | |
| 157 | + return { | |
| 158 | + earthquakes, | |
| 159 | + news, | |
| 160 | + threats, | |
| 161 | + cyberAlerts: [], | |
| 162 | + timestamp: new Date().toISOString(), | |
| 163 | + }; | |
| 164 | +} | |
| 165 | + | |
| 166 | +/** Render markdown-lite: bold, headers, bullet points */ | |
| 167 | +function renderMarkdown(text: string): string { | |
| 168 | + return text | |
| 169 | + .replace(/### (.+)/g, '<h4 class="text-[11px] font-bold text-[var(--gold-primary)] mt-3 mb-1 tracking-wider uppercase font-mono">$1</h4>') | |
| 170 | + .replace(/## (.+)/g, '<h3 class="text-[12px] font-bold text-[var(--gold-primary)] mt-3 mb-1.5 tracking-wider uppercase font-mono border-b border-[var(--border-secondary)] pb-1">$1</h3>') | |
| 171 | + .replace(/# (.+)/g, '<h2 class="text-[13px] font-bold text-[var(--gold-primary)] mt-3 mb-1.5 tracking-wider uppercase font-mono">$1</h2>') | |
| 172 | + .replace(/\*\*(.+?)\*\*/g, '<strong class="text-[var(--text-heading)] font-semibold">$1</strong>') | |
| 173 | + .replace(/\*(.+?)\*/g, '<em class="text-[var(--text-secondary)] italic">$1</em>') | |
| 174 | + .replace(/^- (.+)/gm, '<div class="flex items-start gap-1.5 ml-1 my-0.5"><span class="text-[var(--gold-dim)] mt-[3px] text-[8px]">◆</span><span>$1</span></div>') | |
| 175 | + .replace(/\n/g, '<br />'); | |
| 176 | +} | |
| 177 | + | |
| 178 | +/* ───────────────────────────────────────────────────────────── | |
| 179 | + Component | |
| 180 | + ───────────────────────────────────────────────────────────── */ | |
| 181 | + | |
| 182 | +export default function AiAnalyst({ data }: AiAnalystProps) { | |
| 183 | + const [isOpen, setIsOpen] = useState(false); | |
| 184 | + const [messages, setMessages] = useState<ChatMessage[]>([]); | |
| 185 | + const [inputText, setInputText] = useState(''); | |
| 186 | + const [isLoading, setIsLoading] = useState(false); | |
| 187 | + const [showSettings, setShowSettings] = useState(false); | |
| 188 | + const [apiKeyInput, setApiKeyInput] = useState(''); | |
| 189 | + const [keySaved, setKeySaved] = useState(false); | |
| 190 | + | |
| 191 | + const messagesEndRef = useRef<HTMLDivElement>(null); | |
| 192 | + const inputRef = useRef<HTMLTextAreaElement>(null); | |
| 193 | + | |
| 194 | + // Load saved key on mount | |
| 195 | + useEffect(() => { | |
| 196 | + const saved = localStorage.getItem('osiris-gemini-key'); | |
| 197 | + if (saved) { | |
| 198 | + setApiKeyInput(saved); | |
| 199 | + setKeySaved(true); | |
| 200 | + } | |
| 201 | + }, []); | |
| 202 | + | |
| 203 | + // Auto-scroll to bottom | |
| 204 | + useEffect(() => { | |
| 205 | + messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); | |
| 206 | + }, [messages]); | |
| 207 | + | |
| 208 | + // Focus input when opened | |
| 209 | + useEffect(() => { | |
| 210 | + if (isOpen && !showSettings) { | |
| 211 | + setTimeout(() => inputRef.current?.focus(), 300); | |
| 212 | + } | |
| 213 | + }, [isOpen, showSettings]); | |
| 214 | + | |
| 215 | + const getHeaders = useCallback((): Record<string, string> => { | |
| 216 | + const headers: Record<string, string> = { 'Content-Type': 'application/json' }; | |
| 217 | + const savedKey = localStorage.getItem('osiris-gemini-key'); | |
| 218 | + if (savedKey) { | |
| 219 | + headers['x-gemini-key'] = savedKey; | |
| 220 | + } | |
| 221 | + return headers; | |
| 222 | + }, []); | |
| 223 | + | |
| 224 | + const handleSend = useCallback(async () => { | |
| 225 | + const query = inputText.trim(); | |
| 226 | + if (!query || isLoading) return; | |
| 227 | + | |
| 228 | + const userMsg: ChatMessage = { | |
| 229 | + id: generateId(), | |
| 230 | + role: 'user', | |
| 231 | + content: query, | |
| 232 | + timestamp: new Date().toISOString(), | |
| 233 | + }; | |
| 234 | + setMessages((prev) => [...prev, userMsg]); | |
| 235 | + setInputText(''); | |
| 236 | + setIsLoading(true); | |
| 237 | + | |
| 238 | + try { | |
| 239 | + const context = buildContext(data); | |
| 240 | + const res = await fetch('/api/ai/analyze', { | |
| 241 | + method: 'POST', | |
| 242 | + headers: getHeaders(), | |
| 243 | + body: JSON.stringify({ query, context }), | |
| 244 | + }); | |
| 245 | + | |
| 246 | + const json = await res.json(); | |
| 247 | + | |
| 248 | + if (!res.ok) { | |
| 249 | + const errorBody = json as { error: string; code: string; retryAfter?: number }; | |
| 250 | + throw new Error(errorBody.error || `HTTP ${res.status}`); | |
| 251 | + } | |
| 252 | + | |
| 253 | + const responseBody = json as { analysis: string; model: string; timestamp: string }; | |
| 254 | + | |
| 255 | + const analystMsg: ChatMessage = { | |
| 256 | + id: generateId(), | |
| 257 | + role: 'analyst', | |
| 258 | + content: responseBody.analysis, | |
| 259 | + timestamp: responseBody.timestamp, | |
| 260 | + }; | |
| 261 | + setMessages((prev) => [...prev, analystMsg]); | |
| 262 | + } catch (err: unknown) { | |
| 263 | + const message = err instanceof Error ? err.message : 'Analysis failed'; | |
| 264 | + const errorMsg: ChatMessage = { | |
| 265 | + id: generateId(), | |
| 266 | + role: 'analyst', | |
| 267 | + content: `⚠ INTELLIGENCE ANALYSIS ERROR\n\n${message}`, | |
| 268 | + timestamp: new Date().toISOString(), | |
| 269 | + isError: true, | |
| 270 | + }; | |
| 271 | + setMessages((prev) => [...prev, errorMsg]); | |
| 272 | + } finally { | |
| 273 | + setIsLoading(false); | |
| 274 | + } | |
| 275 | + }, [inputText, isLoading, data, getHeaders]); | |
| 276 | + | |
| 277 | + const handleBriefing = useCallback(async () => { | |
| 278 | + if (isLoading) return; | |
| 279 | + | |
| 280 | + const userMsg: ChatMessage = { | |
| 281 | + id: generateId(), | |
| 282 | + role: 'user', | |
| 283 | + content: '📋 Generate full intelligence briefing from current operational data', | |
| 284 | + timestamp: new Date().toISOString(), | |
| 285 | + }; | |
| 286 | + setMessages((prev) => [...prev, userMsg]); | |
| 287 | + setIsLoading(true); | |
| 288 | + | |
| 289 | + try { | |
| 290 | + const context = buildContext(data); | |
| 291 | + const res = await fetch('/api/ai/briefing', { | |
| 292 | + method: 'POST', | |
| 293 | + headers: getHeaders(), | |
| 294 | + body: JSON.stringify({ context }), | |
| 295 | + }); | |
| 296 | + | |
| 297 | + const json = await res.json(); | |
| 298 | + | |
| 299 | + if (!res.ok) { | |
| 300 | + const errorBody = json as { error: string; code: string }; | |
| 301 | + throw new Error(errorBody.error || `HTTP ${res.status}`); | |
| 302 | + } | |
| 303 | + | |
| 304 | + const responseBody = json as { briefing: string; generatedAt: string }; | |
| 305 | + | |
| 306 | + const analystMsg: ChatMessage = { | |
| 307 | + id: generateId(), | |
| 308 | + role: 'analyst', | |
| 309 | + content: responseBody.briefing, | |
| 310 | + timestamp: responseBody.generatedAt, | |
| 311 | + }; | |
| 312 | + setMessages((prev) => [...prev, analystMsg]); | |
| 313 | + } catch (err: unknown) { | |
| 314 | + const message = err instanceof Error ? err.message : 'Briefing generation failed'; | |
| 315 | + const errorMsg: ChatMessage = { | |
| 316 | + id: generateId(), | |
| 317 | + role: 'analyst', | |
| 318 | + content: `⚠ BRIEFING GENERATION ERROR\n\n${message}`, | |
| 319 | + timestamp: new Date().toISOString(), | |
| 320 | + isError: true, | |
| 321 | + }; | |
| 322 | + setMessages((prev) => [...prev, errorMsg]); | |
| 323 | + } finally { | |
| 324 | + setIsLoading(false); | |
| 325 | + } | |
| 326 | + }, [isLoading, data, getHeaders]); | |
| 327 | + | |
| 328 | + const handleKeyDown = useCallback( | |
| 329 | + (e: React.KeyboardEvent<HTMLTextAreaElement>) => { | |
| 330 | + if (e.key === 'Enter' && !e.shiftKey) { | |
| 331 | + e.preventDefault(); | |
| 332 | + handleSend(); | |
| 333 | + } | |
| 334 | + }, | |
| 335 | + [handleSend] | |
| 336 | + ); | |
| 337 | + | |
| 338 | + const saveApiKey = useCallback(() => { | |
| 339 | + const key = apiKeyInput.trim(); | |
| 340 | + if (key) { | |
| 341 | + localStorage.setItem('osiris-gemini-key', key); | |
| 342 | + setKeySaved(true); | |
| 343 | + setTimeout(() => setShowSettings(false), 600); | |
| 344 | + } | |
| 345 | + }, [apiKeyInput]); | |
| 346 | + | |
| 347 | + const clearApiKey = useCallback(() => { | |
| 348 | + localStorage.removeItem('osiris-gemini-key'); | |
| 349 | + setApiKeyInput(''); | |
| 350 | + setKeySaved(false); | |
| 351 | + }, []); | |
| 352 | + | |
| 353 | + const clearMessages = useCallback(() => { | |
| 354 | + setMessages([]); | |
| 355 | + }, []); | |
| 356 | + | |
| 357 | + /* ── Floating Trigger Button ── */ | |
| 358 | + const triggerButton = ( | |
| 359 | + <motion.button | |
| 360 | + initial={{ scale: 0, opacity: 0 }} | |
| 361 | + animate={{ scale: 1, opacity: 1 }} | |
| 362 | + transition={{ delay: 3, type: 'spring', stiffness: 200, damping: 15 }} | |
| 363 | + whileHover={{ scale: 1.1 }} | |
| 364 | + whileTap={{ scale: 0.95 }} | |
| 365 | + onClick={() => setIsOpen(true)} | |
| 366 | + className="fixed bottom-[90px] right-5 md:bottom-8 md:right-8 z-[500] w-14 h-14 rounded-full flex items-center justify-center cursor-pointer border-0" | |
| 367 | + style={{ | |
| 368 | + background: 'linear-gradient(135deg, rgba(212, 175, 55, 0.2) 0%, rgba(212, 175, 55, 0.08) 100%)', | |
| 369 | + border: '1px solid rgba(212, 175, 55, 0.4)', | |
| 370 | + boxShadow: | |
| 371 | + '0 0 30px rgba(212, 175, 55, 0.2), 0 0 60px rgba(212, 175, 55, 0.1), 0 4px 20px rgba(0, 0, 0, 0.5)', | |
| 372 | + }} | |
| 373 | + aria-label="Open AI Intelligence Analyst" | |
| 374 | + > | |
| 375 | + <Brain className="w-6 h-6 text-[var(--gold-primary)]" /> | |
| 376 | + {/* Pulse rings */} | |
| 377 | + <div className="absolute inset-0 rounded-full animate-glow-pulse" /> | |
| 378 | + <motion.div | |
| 379 | + className="absolute inset-[-4px] rounded-full border border-[var(--gold-primary)]" | |
| 380 | + animate={{ opacity: [0.3, 0.6, 0.3], scale: [1, 1.1, 1] }} | |
| 381 | + transition={{ duration: 3, repeat: Infinity, ease: 'easeInOut' }} | |
| 382 | + style={{ opacity: 0.3 }} | |
| 383 | + /> | |
| 384 | + </motion.button> | |
| 385 | + ); | |
| 386 | + | |
| 387 | + /* ── Panel ── */ | |
| 388 | + return ( | |
| 389 | + <> | |
| 390 | + {/* Trigger — only show when panel is closed */} | |
| 391 | + <AnimatePresence>{!isOpen && triggerButton}</AnimatePresence> | |
| 392 | + | |
| 393 | + {/* Panel */} | |
| 394 | + <AnimatePresence> | |
| 395 | + {isOpen && ( | |
| 396 | + <> | |
| 397 | + {/* Backdrop on mobile */} | |
| 398 | + <motion.div | |
| 399 | + initial={{ opacity: 0 }} | |
| 400 | + animate={{ opacity: 1 }} | |
| 401 | + exit={{ opacity: 0 }} | |
| 402 | + className="fixed inset-0 bg-black/40 backdrop-blur-sm z-[600] md:hidden" | |
| 403 | + onClick={() => setIsOpen(false)} | |
| 404 | + /> | |
| 405 | + | |
| 406 | + {/* Main Panel */} | |
| 407 | + <motion.div | |
| 408 | + initial={{ opacity: 0, y: 40, scale: 0.95 }} | |
| 409 | + animate={{ opacity: 1, y: 0, scale: 1 }} | |
| 410 | + exit={{ opacity: 0, y: 40, scale: 0.95 }} | |
| 411 | + transition={{ type: 'spring', stiffness: 300, damping: 25 }} | |
| 412 | + className="fixed bottom-0 right-0 md:bottom-6 md:right-6 z-[700] w-full md:w-[440px] h-[85vh] md:h-[680px] md:max-h-[85vh] flex flex-col md:rounded-2xl overflow-hidden" | |
| 413 | + style={{ | |
| 414 | + background: 'linear-gradient(180deg, rgba(8, 10, 20, 0.96) 0%, rgba(6, 6, 12, 0.98) 100%)', | |
| 415 | + border: '1px solid rgba(212, 175, 55, 0.2)', | |
| 416 | + boxShadow: | |
| 417 | + '0 0 60px rgba(0, 0, 0, 0.8), 0 0 30px rgba(212, 175, 55, 0.08), 0 1px 0 rgba(212, 175, 55, 0.1) inset', | |
| 418 | + backdropFilter: 'blur(40px) saturate(1.5)', | |
| 419 | + }} | |
| 420 | + > | |
| 421 | + {/* ── Header ── */} | |
| 422 | + <div | |
| 423 | + className="relative flex items-center justify-between px-4 py-3 shrink-0" | |
| 424 | + style={{ | |
| 425 | + background: 'linear-gradient(90deg, rgba(212, 175, 55, 0.06) 0%, transparent 50%, rgba(0, 229, 255, 0.04) 100%)', | |
| 426 | + borderBottom: '1px solid rgba(212, 175, 55, 0.15)', | |
| 427 | + }} | |
| 428 | + > | |
| 429 | + {/* Scan line accent */} | |
| 430 | + <motion.div | |
| 431 | + className="absolute bottom-0 left-0 right-0 h-[1px]" | |
| 432 | + style={{ background: 'linear-gradient(90deg, transparent, var(--gold-primary), transparent)' }} | |
| 433 | + animate={{ opacity: [0.3, 0.7, 0.3] }} | |
| 434 | + transition={{ duration: 3, repeat: Infinity, ease: 'easeInOut' }} | |
| 435 | + /> | |
| 436 | + | |
| 437 | + <div className="flex items-center gap-2.5"> | |
| 438 | + <div className="relative"> | |
| 439 | + <Shield className="w-4.5 h-4.5 text-[var(--gold-primary)]" /> | |
| 440 | + <div className="absolute -top-0.5 -right-0.5 w-1.5 h-1.5 rounded-full bg-[var(--alert-green)] animate-osiris-pulse" /> | |
| 441 | + </div> | |
| 442 | + <div className="flex flex-col"> | |
| 443 | + <span className="hud-text text-[11px] text-[var(--text-heading)]">OSIRIS ANALYST</span> | |
| 444 | + <span className="text-[7px] font-mono tracking-[0.2em] text-[var(--text-muted)]"> | |
| 445 | + GEMINI 2.0 FLASH • ONLINE | |
| 446 | + </span> | |
| 447 | + </div> | |
| 448 | + </div> | |
| 449 | + | |
| 450 | + <div className="flex items-center gap-1"> | |
| 451 | + {messages.length > 0 && ( | |
| 452 | + <button | |
| 453 | + onClick={clearMessages} | |
| 454 | + className="p-1.5 rounded-lg hover:bg-[var(--hover-accent)] transition-colors group" | |
| 455 | + title="Clear conversation" | |
| 456 | + > | |
| 457 | + <Trash2 className="w-3.5 h-3.5 text-[var(--text-muted)] group-hover:text-[var(--alert-red)]" /> | |
| 458 | + </button> | |
| 459 | + )} | |
| 460 | + <button | |
| 461 | + onClick={() => setShowSettings(!showSettings)} | |
| 462 | + className="p-1.5 rounded-lg hover:bg-[var(--hover-accent)] transition-colors group" | |
| 463 | + title="Settings" | |
| 464 | + > | |
| 465 | + <Settings | |
| 466 | + className={`w-3.5 h-3.5 transition-colors ${ | |
| 467 | + showSettings ? 'text-[var(--gold-primary)]' : 'text-[var(--text-muted)] group-hover:text-[var(--text-primary)]' | |
| 468 | + }`} | |
| 469 | + /> | |
| 470 | + </button> | |
| 471 | + <button | |
| 472 | + onClick={() => setIsOpen(false)} | |
| 473 | + className="p-1.5 rounded-lg hover:bg-[var(--hover-accent)] transition-colors group" | |
| 474 | + title="Close" | |
| 475 | + > | |
| 476 | + <X className="w-3.5 h-3.5 text-[var(--text-muted)] group-hover:text-[var(--text-primary)]" /> | |
| 477 | + </button> | |
| 478 | + </div> | |
| 479 | + </div> | |
| 480 | + | |
| 481 | + {/* ── Settings Panel ── */} | |
| 482 | + <AnimatePresence> | |
| 483 | + {showSettings && ( | |
| 484 | + <motion.div | |
| 485 | + initial={{ height: 0, opacity: 0 }} | |
| 486 | + animate={{ height: 'auto', opacity: 1 }} | |
| 487 | + exit={{ height: 0, opacity: 0 }} | |
| 488 | + transition={{ duration: 0.2 }} | |
| 489 | + className="overflow-hidden shrink-0" | |
| 490 | + > | |
| 491 | + <div | |
| 492 | + className="px-4 py-3 space-y-2.5" | |
| 493 | + style={{ | |
| 494 | + background: 'rgba(212, 175, 55, 0.03)', | |
| 495 | + borderBottom: '1px solid rgba(212, 175, 55, 0.1)', | |
| 496 | + }} | |
| 497 | + > | |
| 498 | + <div className="flex items-center gap-2"> | |
| 499 | + <Key className="w-3 h-3 text-[var(--gold-dim)]" /> | |
| 500 | + <span className="hud-label" style={{ fontSize: '8px' }}> | |
| 501 | + GEMINI API KEY (OPTIONAL) | |
| 502 | + </span> | |
| 503 | + </div> | |
| 504 | + <div className="flex gap-2"> | |
| 505 | + <input | |
| 506 | + type="password" | |
| 507 | + value={apiKeyInput} | |
| 508 | + onChange={(e) => { | |
| 509 | + setApiKeyInput(e.target.value); | |
| 510 | + setKeySaved(false); | |
| 511 | + }} | |
| 512 | + placeholder="AIza..." | |
| 513 | + className="flex-1 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-lg px-3 py-2 text-[11px] font-mono text-[var(--text-primary)] placeholder:text-[var(--text-muted)] focus:outline-none focus:border-[var(--gold-dim)] transition-colors" | |
| 514 | + /> | |
| 515 | + {apiKeyInput.trim() && ( | |
| 516 | + <> | |
| 517 | + <button | |
| 518 | + onClick={saveApiKey} | |
| 519 | + className="px-3 rounded-lg text-[9px] font-mono tracking-wider transition-all" | |
| 520 | + style={{ | |
| 521 | + background: keySaved ? 'rgba(0, 230, 118, 0.15)' : 'rgba(212, 175, 55, 0.1)', | |
| 522 | + border: `1px solid ${keySaved ? 'rgba(0, 230, 118, 0.3)' : 'rgba(212, 175, 55, 0.2)'}`, | |
| 523 | + color: keySaved ? 'var(--alert-green)' : 'var(--gold-primary)', | |
| 524 | + }} | |
| 525 | + > | |
| 526 | + {keySaved ? <Check className="w-3 h-3" /> : 'SAVE'} | |
| 527 | + </button> | |
| 528 | + <button | |
| 529 | + onClick={clearApiKey} | |
| 530 | + className="px-2 rounded-lg text-[9px] font-mono tracking-wider transition-all hover:bg-red-500/10" | |
| 531 | + style={{ | |
| 532 | + border: '1px solid rgba(255, 61, 61, 0.2)', | |
| 533 | + color: 'var(--alert-red)', | |
| 534 | + }} | |
| 535 | + > | |
| 536 | + <X className="w-3 h-3" /> | |
| 537 | + </button> | |
| 538 | + </> | |
| 539 | + )} | |
| 540 | + </div> | |
| 541 | + <p className="text-[8px] font-mono text-[var(--text-muted)] leading-relaxed"> | |
| 542 | + Your key is stored locally and sent only to the OSIRIS server. Get a free key at{' '} | |
| 543 | + <a | |
| 544 | + href="https://aistudio.google.com/apikey" | |
| 545 | + target="_blank" | |
| 546 | + rel="noopener noreferrer" | |
| 547 | + className="text-[var(--cyan-primary)] hover:underline" | |
| 548 | + > | |
| 549 | + aistudio.google.com | |
| 550 | + </a> | |
| 551 | + </p> | |
| 552 | + </div> | |
| 553 | + </motion.div> | |
| 554 | + )} | |
| 555 | + </AnimatePresence> | |
| 556 | + | |
| 557 | + {/* ── Messages Area ── */} | |
| 558 | + <div className="flex-1 overflow-y-auto styled-scrollbar px-4 py-3 space-y-3"> | |
| 559 | + {/* Empty state */} | |
| 560 | + {messages.length === 0 && !isLoading && ( | |
| 561 | + <div className="h-full flex flex-col items-center justify-center text-center px-6 gap-5"> | |
| 562 | + {/* Animated brain icon */} | |
| 563 | + <div className="relative"> | |
| 564 | + <motion.div | |
| 565 | + animate={{ rotate: [0, 360] }} | |
| 566 | + transition={{ duration: 20, repeat: Infinity, ease: 'linear' }} | |
| 567 | + className="absolute inset-[-10px] rounded-full border border-[var(--gold-primary)]" | |
| 568 | + style={{ opacity: 0.15 }} | |
| 569 | + /> | |
| 570 | + <motion.div | |
| 571 | + animate={{ rotate: [0, -360] }} | |
| 572 | + transition={{ duration: 14, repeat: Infinity, ease: 'linear' }} | |
| 573 | + className="absolute inset-[-20px] rounded-full border border-[var(--cyan-primary)]" | |
| 574 | + style={{ opacity: 0.08 }} | |
| 575 | + /> | |
| 576 | + <div | |
| 577 | + className="w-16 h-16 rounded-2xl flex items-center justify-center" | |
| 578 | + style={{ | |
| 579 | + background: 'linear-gradient(135deg, rgba(212, 175, 55, 0.1) 0%, rgba(0, 229, 255, 0.05) 100%)', | |
| 580 | + border: '1px solid rgba(212, 175, 55, 0.2)', | |
| 581 | + }} | |
| 582 | + > | |
| 583 | + <Brain className="w-7 h-7 text-[var(--gold-primary)]" /> | |
| 584 | + </div> | |
| 585 | + </div> | |
| 586 | + | |
| 587 | + <div className="space-y-2"> | |
| 588 | + <h3 className="hud-text text-[12px] text-[var(--text-heading)]"> | |
| 589 | + INTELLIGENCE ANALYST READY | |
| 590 | + </h3> | |
| 591 | + <p className="text-[10px] font-mono text-[var(--text-muted)] leading-relaxed max-w-[280px]"> | |
| 592 | + I correlate live seismic, OSINT, threat, and cyber data to deliver actionable intelligence assessments. | |
| 593 | + </p> | |
| 594 | + </div> | |
| 595 | + | |
| 596 | + {/* Quick prompts */} | |
| 597 | + <div className="w-full space-y-1.5"> | |
| 598 | + <span className="hud-label block text-center mb-2" style={{ fontSize: '7px' }}> | |
| 599 | + SUGGESTED QUERIES | |
| 600 | + </span> | |
| 601 | + {[ | |
| 602 | + 'What are the top 3 threats right now?', | |
| 603 | + 'Are there seismic patterns correlating with conflicts?', | |
| 604 | + 'Assess cyber risks to critical infrastructure', | |
| 605 | + ].map((prompt) => ( | |
| 606 | + <button | |
| 607 | + key={prompt} | |
| 608 | + onClick={() => { | |
| 609 | + setInputText(prompt); | |
| 610 | + setTimeout(() => inputRef.current?.focus(), 50); | |
| 611 | + }} | |
| 612 | + className="w-full text-left px-3 py-2 rounded-lg text-[10px] font-mono text-[var(--text-secondary)] transition-all hover:text-[var(--text-primary)] hover:bg-[var(--hover-accent)]" | |
| 613 | + style={{ | |
| 614 | + border: '1px solid rgba(212, 175, 55, 0.08)', | |
| 615 | + }} | |
| 616 | + > | |
| 617 | + <span className="text-[var(--gold-dim)] mr-1.5">›</span> | |
| 618 | + {prompt} | |
| 619 | + </button> | |
| 620 | + ))} | |
| 621 | + </div> | |
| 622 | + </div> | |
| 623 | + )} | |
| 624 | + | |
| 625 | + {/* Messages */} | |
| 626 | + {messages.map((msg) => ( | |
| 627 | + <motion.div | |
| 628 | + key={msg.id} | |
| 629 | + initial={{ opacity: 0, y: 10 }} | |
| 630 | + animate={{ opacity: 1, y: 0 }} | |
| 631 | + transition={{ duration: 0.3 }} | |
| 632 | + className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`} | |
| 633 | + > | |
| 634 | + <div | |
| 635 | + className={`max-w-[90%] rounded-xl px-3.5 py-2.5 ${ | |
| 636 | + msg.role === 'user' ? 'rounded-br-sm' : 'rounded-bl-sm' | |
| 637 | + }`} | |
| 638 | + style={ | |
| 639 | + msg.role === 'user' | |
| 640 | + ? { | |
| 641 | + background: 'linear-gradient(135deg, rgba(0, 229, 255, 0.12) 0%, rgba(0, 229, 255, 0.06) 100%)', | |
| 642 | + border: '1px solid rgba(0, 229, 255, 0.2)', | |
| 643 | + } | |
| 644 | + : msg.isError | |
| 645 | + ? { | |
| 646 | + background: 'linear-gradient(135deg, rgba(255, 61, 61, 0.1) 0%, rgba(255, 61, 61, 0.05) 100%)', | |
| 647 | + border: '1px solid rgba(255, 61, 61, 0.2)', | |
| 648 | + } | |
| 649 | + : { | |
| 650 | + background: 'linear-gradient(135deg, rgba(212, 175, 55, 0.08) 0%, rgba(212, 175, 55, 0.03) 100%)', | |
| 651 | + border: '1px solid rgba(212, 175, 55, 0.12)', | |
| 652 | + } | |
| 653 | + } | |
| 654 | + > | |
| 655 | + {/* Message header */} | |
| 656 | + <div className="flex items-center gap-1.5 mb-1.5"> | |
| 657 | + {msg.role === 'user' ? ( | |
| 658 | + <User className="w-3 h-3 text-[var(--cyan-primary)]" /> | |
| 659 | + ) : msg.isError ? ( | |
| 660 | + <AlertTriangle className="w-3 h-3 text-[var(--alert-red)]" /> | |
| 661 | + ) : ( | |
| 662 | + <Bot className="w-3 h-3 text-[var(--gold-primary)]" /> | |
| 663 | + )} | |
| 664 | + <span | |
| 665 | + className="text-[8px] font-mono tracking-[0.15em] uppercase" | |
| 666 | + style={{ | |
| 667 | + color: msg.role === 'user' | |
| 668 | + ? 'var(--cyan-primary)' | |
| 669 | + : msg.isError | |
| 670 | + ? 'var(--alert-red)' | |
| 671 | + : 'var(--gold-primary)', | |
| 672 | + }} | |
| 673 | + > | |
| 674 | + {msg.role === 'user' ? 'OPERATOR' : 'OSIRIS ANALYST'} | |
| 675 | + </span> | |
| 676 | + <span className="text-[7px] font-mono text-[var(--text-muted)] ml-auto"> | |
| 677 | + {new Date(msg.timestamp).toLocaleTimeString([], { | |
| 678 | + hour: '2-digit', | |
| 679 | + minute: '2-digit', | |
| 680 | + })} | |
| 681 | + </span> | |
| 682 | + </div> | |
| 683 | + | |
| 684 | + {/* Message content */} | |
| 685 | + {msg.role === 'analyst' && !msg.isError ? ( | |
| 686 | + <div | |
| 687 | + className="text-[11px] font-mono text-[var(--text-primary)] leading-relaxed whitespace-pre-wrap break-words" | |
| 688 | + dangerouslySetInnerHTML={{ __html: renderMarkdown(msg.content) }} | |
| 689 | + /> | |
| 690 | + ) : ( | |
| 691 | + <p className="text-[11px] font-mono text-[var(--text-primary)] leading-relaxed whitespace-pre-wrap break-words"> | |
| 692 | + {msg.content} | |
| 693 | + </p> | |
| 694 | + )} | |
| 695 | + </div> | |
| 696 | + </motion.div> | |
| 697 | + ))} | |
| 698 | + | |
| 699 | + {/* Loading indicator */} | |
| 700 | + {isLoading && ( | |
| 701 | + <motion.div | |
| 702 | + initial={{ opacity: 0, y: 10 }} | |
| 703 | + animate={{ opacity: 1, y: 0 }} | |
| 704 | + className="flex justify-start" | |
| 705 | + > | |
| 706 | + <div | |
| 707 | + className="rounded-xl rounded-bl-sm px-4 py-3 flex items-center gap-2.5" | |
| 708 | + style={{ | |
| 709 | + background: 'linear-gradient(135deg, rgba(212, 175, 55, 0.08) 0%, rgba(212, 175, 55, 0.03) 100%)', | |
| 710 | + border: '1px solid rgba(212, 175, 55, 0.12)', | |
| 711 | + }} | |
| 712 | + > | |
| 713 | + <Loader2 className="w-3.5 h-3.5 text-[var(--gold-primary)] animate-spin" /> | |
| 714 | + <div className="flex items-center gap-1"> | |
| 715 | + <span className="text-[9px] font-mono tracking-[0.15em] text-[var(--gold-primary)] uppercase"> | |
| 716 | + Analyzing intelligence | |
| 717 | + </span> | |
| 718 | + <motion.span | |
| 719 | + animate={{ opacity: [0, 1, 0] }} | |
| 720 | + transition={{ duration: 1.5, repeat: Infinity }} | |
| 721 | + className="text-[var(--gold-primary)]" | |
| 722 | + > | |
| 723 | + ... | |
| 724 | + </motion.span> | |
| 725 | + </div> | |
| 726 | + </div> | |
| 727 | + </motion.div> | |
| 728 | + )} | |
| 729 | + | |
| 730 | + <div ref={messagesEndRef} /> | |
| 731 | + </div> | |
| 732 | + | |
| 733 | + {/* ── Input Area ── */} | |
| 734 | + <div | |
| 735 | + className="shrink-0 px-3 py-2.5" | |
| 736 | + style={{ | |
| 737 | + borderTop: '1px solid rgba(212, 175, 55, 0.1)', | |
| 738 | + background: 'rgba(6, 6, 12, 0.8)', | |
| 739 | + }} | |
| 740 | + > | |
| 741 | + {/* Quick action */} | |
| 742 | + <div className="flex gap-2 mb-2"> | |
| 743 | + <button | |
| 744 | + onClick={handleBriefing} | |
| 745 | + disabled={isLoading} | |
| 746 | + className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[9px] font-mono tracking-[0.1em] uppercase transition-all disabled:opacity-40" | |
| 747 | + style={{ | |
| 748 | + background: 'rgba(212, 175, 55, 0.08)', | |
| 749 | + border: '1px solid rgba(212, 175, 55, 0.2)', | |
| 750 | + color: 'var(--gold-primary)', | |
| 751 | + }} | |
| 752 | + > | |
| 753 | + <Sparkles className="w-3 h-3" /> | |
| 754 | + GENERATE BRIEFING | |
| 755 | + </button> | |
| 756 | + <div className="flex-1" /> | |
| 757 | + <span className="flex items-center text-[7px] font-mono text-[var(--text-muted)] tracking-wider"> | |
| 758 | + <ChevronDown className="w-2.5 h-2.5 mr-0.5" /> | |
| 759 | + SHIFT+ENTER FOR NEWLINE | |
| 760 | + </span> | |
| 761 | + </div> | |
| 762 | + | |
| 763 | + {/* Input row */} | |
| 764 | + <div className="flex gap-2 items-end"> | |
| 765 | + <div | |
| 766 | + className="flex-1 rounded-xl overflow-hidden transition-colors" | |
| 767 | + style={{ | |
| 768 | + background: 'var(--bg-tertiary)', | |
| 769 | + border: '1px solid rgba(212, 175, 55, 0.1)', | |
| 770 | + }} | |
| 771 | + > | |
| 772 | + <textarea | |
| 773 | + ref={inputRef} | |
| 774 | + value={inputText} | |
| 775 | + onChange={(e) => setInputText(e.target.value)} | |
| 776 | + onKeyDown={handleKeyDown} | |
| 777 | + placeholder="Query the intelligence analyst..." | |
| 778 | + rows={1} | |
| 779 | + className="w-full bg-transparent px-3 py-2.5 text-[11px] font-mono text-[var(--text-primary)] placeholder:text-[var(--text-muted)] focus:outline-none resize-none" | |
| 780 | + style={{ maxHeight: '120px', minHeight: '36px' }} | |
| 781 | + disabled={isLoading} | |
| 782 | + onInput={(e) => { | |
| 783 | + const target = e.target as HTMLTextAreaElement; | |
| 784 | + target.style.height = 'auto'; | |
| 785 | + target.style.height = Math.min(target.scrollHeight, 120) + 'px'; | |
| 786 | + }} | |
| 787 | + /> | |
| 788 | + </div> | |
| 789 | + | |
| 790 | + <motion.button | |
| 791 | + whileHover={{ scale: 1.05 }} | |
| 792 | + whileTap={{ scale: 0.95 }} | |
| 793 | + onClick={handleSend} | |
| 794 | + disabled={!inputText.trim() || isLoading} | |
| 795 | + className="shrink-0 w-9 h-9 rounded-xl flex items-center justify-center transition-all disabled:opacity-30" | |
| 796 | + style={{ | |
| 797 | + background: | |
| 798 | + inputText.trim() && !isLoading | |
| 799 | + ? 'linear-gradient(135deg, rgba(0, 229, 255, 0.2) 0%, rgba(0, 229, 255, 0.1) 100%)' | |
| 800 | + : 'rgba(255, 255, 255, 0.03)', | |
| 801 | + border: `1px solid ${ | |
| 802 | + inputText.trim() && !isLoading ? 'rgba(0, 229, 255, 0.3)' : 'rgba(255, 255, 255, 0.06)' | |
| 803 | + }`, | |
| 804 | + }} | |
| 805 | + > | |
| 806 | + <Send | |
| 807 | + className="w-3.5 h-3.5" | |
| 808 | + style={{ | |
| 809 | + color: inputText.trim() && !isLoading ? 'var(--cyan-primary)' : 'var(--text-muted)', | |
| 810 | + }} | |
| 811 | + /> | |
| 812 | + </motion.button> | |
| 813 | + </div> | |
| 814 | + | |
| 815 | + {/* Footer */} | |
| 816 | + <div className="flex items-center justify-between mt-1.5 px-1"> | |
| 817 | + <span className="text-[7px] font-mono text-[var(--text-muted)] tracking-wider"> | |
| 818 | + {keySaved ? '🔑 CUSTOM KEY' : '🔧 SERVER KEY'} • {messages.filter((m) => m.role === 'user').length} QUERIES | |
| 819 | + </span> | |
| 820 | + <span className="text-[7px] font-mono text-[var(--text-muted)] tracking-wider"> | |
| 821 | + FEEDS: {(data.earthquakes?.length || 0) + (data.news?.length || 0) + (data.gdelt?.length || 0)} ITEMS | |
| 822 | + </span> | |
| 823 | + </div> | |
| 824 | + </div> | |
| 825 | + </motion.div> | |
| 826 | + </> | |
| 827 | + )} | |
| 828 | + </AnimatePresence> | |
| 829 | + </> | |
| 830 | + ); | |
| 831 | +} |
modified src/components/LayerPanel.tsx +0 −1
| @@ -63,7 +63,6 @@ | ||
| 63 | 63 | { key: 'infrastructure', label: 'Nuclear Facilities', icon: Radiation, color: '#76FF03', dataKey: 'infrastructure' }, |
| 64 | 64 | { key: 'global_incidents', label: 'Global Incidents', icon: AlertTriangle, color: '#FF3D3D', dataKey: 'gdelt' }, |
| 65 | 65 | { key: 'gps_jamming', label: 'GPS Jamming', icon: Radio, color: '#FF4444', dataKey: 'gps_jamming' }, |
| 66 | - { key: 'scm_suppliers', label: 'SCM Suppliers', icon: Target, color: '#00BCD4', dataKey: 'scm_suppliers' }, | |
| 67 | 66 | ], |
| 68 | 67 | }, |
| 69 | 68 | { |
modified src/components/OsirisMap.tsx +23 −55
| @@ -112,60 +112,28 @@ | ||
| 112 | 112 | const sources = ['flights','military','jets','private-fl','satellites','earthquakes','gdelt','gps-jamming','day-night','cctv','fires','weather','infrastructure','maritime','maritime-choke','maritime-ships','live-news','sigint-news','conflict-zones', 'war-alerts-targets', 'war-alerts-lines', 'balloons', 'radiation', 'ip-sweep-devices', 'ip-sweep-pulse', 'ip-sweep-connections', 'scan-targets']; |
| 113 | 113 | sources.forEach(s => map.addSource(s, { type: 'geojson', data: EMPTY_FC })); |
| 114 | 114 | |
| 115 | - // ── CONFLICT ZONES — small warning markers (not polygons) ── | |
| 116 | - // Create warning triangle icon | |
| 117 | - const warnSize = 20; | |
| 118 | - const warnCanvas = document.createElement('canvas'); | |
| 119 | - warnCanvas.width = warnSize; warnCanvas.height = warnSize; | |
| 120 | - const warnCtx = warnCanvas.getContext('2d')!; | |
| 121 | - // Triangle | |
| 122 | - warnCtx.fillStyle = '#FF1744'; | |
| 123 | - warnCtx.beginPath(); | |
| 124 | - warnCtx.moveTo(warnSize/2, 1); | |
| 125 | - warnCtx.lineTo(warnSize - 1, warnSize - 1); | |
| 126 | - warnCtx.lineTo(1, warnSize - 1); | |
| 127 | - warnCtx.closePath(); | |
| 128 | - warnCtx.fill(); | |
| 129 | - // Exclamation mark | |
| 130 | - warnCtx.fillStyle = '#000'; | |
| 131 | - warnCtx.font = 'bold 11px sans-serif'; | |
| 132 | - warnCtx.textAlign = 'center'; | |
| 133 | - warnCtx.fillText('!', warnSize/2, warnSize - 4); | |
| 134 | - map.addImage('warn-icon', { width: warnSize, height: warnSize, data: new Uint8Array(warnCtx.getImageData(0, 0, warnSize, warnSize).data) }); | |
| 135 | - | |
| 136 | - // Orange warning | |
| 137 | - const warnOCanvas = document.createElement('canvas'); | |
| 138 | - warnOCanvas.width = warnSize; warnOCanvas.height = warnSize; | |
| 139 | - const warnOCtx = warnOCanvas.getContext('2d')!; | |
| 140 | - warnOCtx.fillStyle = '#FF9500'; | |
| 141 | - warnOCtx.beginPath(); | |
| 142 | - warnOCtx.moveTo(warnSize/2, 1); | |
| 143 | - warnOCtx.lineTo(warnSize - 1, warnSize - 1); | |
| 144 | - warnOCtx.lineTo(1, warnSize - 1); | |
| 145 | - warnOCtx.closePath(); | |
| 146 | - warnOCtx.fill(); | |
| 147 | - warnOCtx.fillStyle = '#000'; | |
| 148 | - warnOCtx.font = 'bold 11px sans-serif'; | |
| 149 | - warnOCtx.textAlign = 'center'; | |
| 150 | - warnOCtx.fillText('!', warnSize/2, warnSize - 4); | |
| 151 | - map.addImage('warn-orange', { width: warnSize, height: warnSize, data: new Uint8Array(warnOCtx.getImageData(0, 0, warnSize, warnSize).data) }); | |
| 152 | - | |
| 153 | - // Yellow warning | |
| 154 | - const warnYCanvas = document.createElement('canvas'); | |
| 155 | - warnYCanvas.width = warnSize; warnYCanvas.height = warnSize; | |
| 156 | - const warnYCtx = warnYCanvas.getContext('2d')!; | |
| 157 | - warnYCtx.fillStyle = '#FFD500'; | |
| 158 | - warnYCtx.beginPath(); | |
| 159 | - warnYCtx.moveTo(warnSize/2, 1); | |
| 160 | - warnYCtx.lineTo(warnSize - 1, warnSize - 1); | |
| 161 | - warnYCtx.lineTo(1, warnSize - 1); | |
| 162 | - warnYCtx.closePath(); | |
| 163 | - warnYCtx.fill(); | |
| 164 | - warnYCtx.fillStyle = '#000'; | |
| 165 | - warnYCtx.font = 'bold 11px sans-serif'; | |
| 166 | - warnYCtx.textAlign = 'center'; | |
| 167 | - warnYCtx.fillText('!', warnSize/2, warnSize - 4); | |
| 168 | - map.addImage('warn-yellow', { width: warnSize, height: warnSize, data: new Uint8Array(warnYCtx.getImageData(0, 0, warnSize, warnSize).data) }); | |
| 115 | + // Warning icon generator (parameterized — eliminates 3x copy-paste) | |
| 116 | + const createWarningIcon = (id: string, color: string) => { | |
| 117 | + const s = 20; | |
| 118 | + const c = document.createElement('canvas'); | |
| 119 | + c.width = s; c.height = s; | |
| 120 | + const ctx = c.getContext('2d')!; | |
| 121 | + ctx.fillStyle = color; | |
| 122 | + ctx.beginPath(); | |
| 123 | + ctx.moveTo(s/2, 1); | |
| 124 | + ctx.lineTo(s - 1, s - 1); | |
| 125 | + ctx.lineTo(1, s - 1); | |
| 126 | + ctx.closePath(); | |
| 127 | + ctx.fill(); | |
| 128 | + ctx.fillStyle = '#000'; | |
| 129 | + ctx.font = 'bold 11px sans-serif'; | |
| 130 | + ctx.textAlign = 'center'; | |
| 131 | + ctx.fillText('!', s/2, s - 4); | |
| 132 | + map.addImage(id, { width: s, height: s, data: new Uint8Array(ctx.getImageData(0, 0, s, s).data) }); | |
| 133 | + }; | |
| 134 | + createWarningIcon('warn-icon', '#FF1744'); | |
| 135 | + createWarningIcon('warn-orange', '#FF9500'); | |
| 136 | + createWarningIcon('warn-yellow', '#FFD500'); | |
| 169 | 137 | |
| 170 | 138 | map.addLayer({ id: 'conflict-icons', type: 'symbol', source: 'conflict-zones', layout: { |
| 171 | 139 | 'icon-image': ['match', ['get','severity'], 'war','warn-icon', 'high','warn-orange', 'warn-yellow'], |
| @@ -592,7 +560,7 @@ | ||
| 592 | 560 | |
| 593 | 561 | |
| 594 | 562 | // ── Generic hover for clickables ── |
| 595 | - ['conflict-icons','cctv-dots','eq-circles','sat-dots','fires-heat','gdelt-dots','weather-dots','infra-dots','maritime-dots','choke-dots','news-dots','sigint-news-dots','balloon-dots','rad-dots','ship-dots','sweep-device-dots','scan-targets-dots','scm-dots'].forEach(layer => { | |
| 563 | + ['conflict-icons','cctv-dots','eq-circles','sat-dots','fires-heat','gdelt-dots','weather-dots','infra-dots','maritime-dots','choke-dots','news-dots','sigint-news-dots','balloon-dots','rad-dots','ship-dots','sweep-device-dots','scan-targets-dots'].forEach(layer => { | |
| 596 | 564 | map.on('mouseenter', layer, () => { map.getCanvas().style.cursor = 'pointer'; }); |
| 597 | 565 | map.on('mouseleave', layer, () => { map.getCanvas().style.cursor = ''; }); |
| 598 | 566 | }); |
added src/lib/ai-engine.ts +270 −0
| @@ -0,0 +1,270 @@ | ||
| 1 | +/** | |
| 2 | + * ═══════════════════════════════════════════════════════════════ | |
| 3 | + * OSIRIS — AI Intelligence Engine | |
| 4 | + * Gemini 2.0 Flash integration for real-time intelligence analysis | |
| 5 | + * Designed to correlate multi-domain feeds into actionable briefings | |
| 6 | + * ═══════════════════════════════════════════════════════════════ | |
| 7 | + */ | |
| 8 | + | |
| 9 | +import { GoogleGenerativeAI, type GenerativeModel } from '@google/generative-ai'; | |
| 10 | + | |
| 11 | +/* ───────────────────────────────────────────────────────────── | |
| 12 | + Data Interfaces — Zero `any` types | |
| 13 | + ───────────────────────────────────────────────────────────── */ | |
| 14 | + | |
| 15 | +export interface EarthquakeEvent { | |
| 16 | + id: string; | |
| 17 | + magnitude: number; | |
| 18 | + location: string; | |
| 19 | + latitude: number; | |
| 20 | + longitude: number; | |
| 21 | + depth: number; | |
| 22 | + timestamp: string; | |
| 23 | + tsunami: boolean; | |
| 24 | + felt: number | null; | |
| 25 | + alert: string | null; | |
| 26 | +} | |
| 27 | + | |
| 28 | +export interface NewsItem { | |
| 29 | + id: string; | |
| 30 | + title: string; | |
| 31 | + description: string; | |
| 32 | + link: string; | |
| 33 | + published: string; | |
| 34 | + source: string; | |
| 35 | + risk_score: number; | |
| 36 | + coords: [number, number] | null; | |
| 37 | + machine_assessment: string | null; | |
| 38 | +} | |
| 39 | + | |
| 40 | +export interface ThreatEvent { | |
| 41 | + id: string; | |
| 42 | + type: string; | |
| 43 | + title: string; | |
| 44 | + description: string; | |
| 45 | + severity: 'CRITICAL' | 'HIGH' | 'ELEVATED' | 'LOW'; | |
| 46 | + region: string; | |
| 47 | + latitude: number; | |
| 48 | + longitude: number; | |
| 49 | + timestamp: string; | |
| 50 | + source: string; | |
| 51 | +} | |
| 52 | + | |
| 53 | +export interface CyberAlert { | |
| 54 | + id: string; | |
| 55 | + name: string; | |
| 56 | + vendor: string; | |
| 57 | + product: string; | |
| 58 | + severity: string; | |
| 59 | + date: string; | |
| 60 | + due: string; | |
| 61 | + source: string; | |
| 62 | +} | |
| 63 | + | |
| 64 | +export interface IntelligenceContext { | |
| 65 | + earthquakes: EarthquakeEvent[]; | |
| 66 | + news: NewsItem[]; | |
| 67 | + threats: ThreatEvent[]; | |
| 68 | + cyberAlerts: CyberAlert[]; | |
| 69 | + timestamp: string; | |
| 70 | +} | |
| 71 | + | |
| 72 | +/* ───────────────────────────────────────────────────────────── | |
| 73 | + System Prompt — Palantir-grade analyst persona | |
| 74 | + ───────────────────────────────────────────────────────────── */ | |
| 75 | + | |
| 76 | +const SYSTEM_PROMPT = `You are OSIRIS Intelligence Analyst — a senior, elite intelligence analyst embedded within the OSIRIS Global Intelligence Platform. You operate at the level of a Palantir Forward Deployed Engineer crossed with a CIA PDB (Presidential Daily Brief) analyst. | |
| 77 | + | |
| 78 | +## YOUR ROLE | |
| 79 | +- You correlate data across multiple intelligence feeds: seismic monitoring, OSINT news streams, global threat events, and cyber vulnerability databases | |
| 80 | +- You identify non-obvious patterns, emerging threat vectors, and cascading risk scenarios | |
| 81 | +- You provide ACTIONABLE intelligence — not summaries, but assessments with confidence levels | |
| 82 | +- You think in terms of second and third-order effects | |
| 83 | + | |
| 84 | +## YOUR ANALYTICAL FRAMEWORK | |
| 85 | +1. **PATTERN RECOGNITION**: Cross-reference events across feeds. A cyber attack + earthquake + political instability in the same region = elevated compound risk | |
| 86 | +2. **THREAT ASSESSMENT**: Rate threats on a CRITICAL / HIGH / ELEVATED / LOW scale with reasoning | |
| 87 | +3. **TEMPORAL ANALYSIS**: Identify acceleration patterns — are events clustering? Is frequency increasing? | |
| 88 | +4. **GEOSPATIAL CORRELATION**: Events in proximity may be related. Identify geographic hotspots | |
| 89 | +5. **CONFIDENCE LEVELS**: Always state your confidence (HIGH / MODERATE / LOW) and cite which data points support your assessment | |
| 90 | + | |
| 91 | +## OUTPUT FORMAT | |
| 92 | +- Use military-style brevity when appropriate | |
| 93 | +- Structure responses with clear headers using markdown | |
| 94 | +- Lead with the most critical finding (inverted pyramid) | |
| 95 | +- Include "BOTTOM LINE UP FRONT (BLUF)" for complex analyses | |
| 96 | +- Use tactical notation: DTG (Date-Time Group), AOR (Area of Responsibility), COA (Course of Action) | |
| 97 | +- End with "ASSESSMENT CONFIDENCE" and "RECOMMENDED ACTIONS" sections when appropriate | |
| 98 | + | |
| 99 | +## CONSTRAINTS | |
| 100 | +- Never fabricate data points — only analyze what is provided in the context | |
| 101 | +- If data is insufficient for a confident assessment, state so explicitly | |
| 102 | +- Distinguish between correlation and causation | |
| 103 | +- Flag when events may be connected vs. coincidental | |
| 104 | +- You are an analyst, not a policymaker — present options, not directives | |
| 105 | + | |
| 106 | +You have access to the live intelligence context of the OSIRIS platform. Analyze it with precision.`; | |
| 107 | + | |
| 108 | +const BRIEFING_PROMPT = `Generate a comprehensive OSIRIS Daily Intelligence Briefing based on the current operational data. Structure it as follows: | |
| 109 | + | |
| 110 | +## OSIRIS INTELLIGENCE BRIEFING | |
| 111 | +**Classification:** OPEN SOURCE INTELLIGENCE (OSINT) | |
| 112 | +**DTG:** [Current timestamp] | |
| 113 | + | |
| 114 | +### I. EXECUTIVE SUMMARY | |
| 115 | +2-3 sentence overview of the current global threat landscape based on available data. | |
| 116 | + | |
| 117 | +### II. PRIORITY INTELLIGENCE REQUIREMENTS (PIRs) | |
| 118 | +Identify the top 3-5 most significant developments from the data feeds, ranked by assessed impact. | |
| 119 | + | |
| 120 | +### III. SEISMIC & NATURAL HAZARD ASSESSMENT | |
| 121 | +Analyze earthquake data for patterns — clustering, tectonic corridor activity, tsunami risk. | |
| 122 | + | |
| 123 | +### IV. GEOPOLITICAL & CONFLICT INTELLIGENCE | |
| 124 | +Synthesize news feeds for conflict escalation patterns, diplomatic shifts, or emerging crises. | |
| 125 | + | |
| 126 | +### V. CYBER THREAT LANDSCAPE | |
| 127 | +Assess active CVEs and cyber alerts for coordinated campaign indicators or critical infrastructure risk. | |
| 128 | + | |
| 129 | +### VI. COMPOUND RISK SCENARIOS | |
| 130 | +Identify where multiple threat vectors intersect (e.g., earthquake near a conflict zone, cyber attack during political instability). | |
| 131 | + | |
| 132 | +### VII. FORECAST & WATCHLIST | |
| 133 | +- **Next 24 Hours**: Most likely developments | |
| 134 | +- **Next 72 Hours**: Emerging situations to monitor | |
| 135 | +- **Strategic Horizon**: Longer-term trend assessment | |
| 136 | + | |
| 137 | +### VIII. ASSESSMENT CONFIDENCE | |
| 138 | +State overall confidence level and key analytical gaps. | |
| 139 | + | |
| 140 | +Analyze the provided data thoroughly. Be specific — reference actual events, magnitudes, locations, and CVE IDs from the context.`; | |
| 141 | + | |
| 142 | +/* ───────────────────────────────────────────────────────────── | |
| 143 | + Client Factory | |
| 144 | + ───────────────────────────────────────────────────────────── */ | |
| 145 | + | |
| 146 | +export function createGeminiClient(apiKey: string): GoogleGenerativeAI { | |
| 147 | + return new GoogleGenerativeAI(apiKey); | |
| 148 | +} | |
| 149 | + | |
| 150 | +/* ───────────────────────────────────────────────────────────── | |
| 151 | + API Key Rotation — Round-robin through available keys | |
| 152 | + ───────────────────────────────────────────────────────────── */ | |
| 153 | + | |
| 154 | +let _keyIndex = 0; | |
| 155 | + | |
| 156 | +export function rotateApiKey(keys: string[]): string { | |
| 157 | + if (keys.length === 0) { | |
| 158 | + throw new Error('No API keys available'); | |
| 159 | + } | |
| 160 | + const key = keys[_keyIndex % keys.length]; | |
| 161 | + _keyIndex = (_keyIndex + 1) % keys.length; | |
| 162 | + return key; | |
| 163 | +} | |
| 164 | + | |
| 165 | +/* ───────────────────────────────────────────────────────────── | |
| 166 | + Context Serializer — Compact representation for token efficiency | |
| 167 | + ───────────────────────────────────────────────────────────── */ | |
| 168 | + | |
| 169 | +function serializeContext(context: IntelligenceContext): string { | |
| 170 | + const sections: string[] = []; | |
| 171 | + | |
| 172 | + sections.push(`[TIMESTAMP] ${context.timestamp}`); | |
| 173 | + | |
| 174 | + if (context.earthquakes.length > 0) { | |
| 175 | + sections.push(`\n[SEISMIC DATA — ${context.earthquakes.length} events]`); | |
| 176 | + for (const eq of context.earthquakes.slice(0, 20)) { | |
| 177 | + const tsunamiFlag = eq.tsunami ? ' ⚠️TSUNAMI' : ''; | |
| 178 | + const alertFlag = eq.alert ? ` [ALERT:${eq.alert.toUpperCase()}]` : ''; | |
| 179 | + sections.push( | |
| 180 | + ` M${eq.magnitude} | ${eq.location} | ${eq.latitude.toFixed(2)},${eq.longitude.toFixed(2)} | Depth:${eq.depth}km | ${eq.timestamp}${tsunamiFlag}${alertFlag}` | |
| 181 | + ); | |
| 182 | + } | |
| 183 | + } | |
| 184 | + | |
| 185 | + if (context.news.length > 0) { | |
| 186 | + sections.push(`\n[OSINT NEWS FEED — ${context.news.length} items]`); | |
| 187 | + for (const item of context.news.slice(0, 15)) { | |
| 188 | + const coords = item.coords ? ` | GEO:${item.coords[0].toFixed(2)},${item.coords[1].toFixed(2)}` : ''; | |
| 189 | + sections.push( | |
| 190 | + ` RISK:${item.risk_score}/10 | ${item.source} | ${item.title}${coords} | ${item.published}` | |
| 191 | + ); | |
| 192 | + } | |
| 193 | + } | |
| 194 | + | |
| 195 | + if (context.threats.length > 0) { | |
| 196 | + sections.push(`\n[THREAT EVENTS — ${context.threats.length} active]`); | |
| 197 | + for (const threat of context.threats.slice(0, 15)) { | |
| 198 | + sections.push( | |
| 199 | + ` ${threat.severity} | ${threat.type} | ${threat.title} | ${threat.region} | ${threat.timestamp}` | |
| 200 | + ); | |
| 201 | + } | |
| 202 | + } | |
| 203 | + | |
| 204 | + if (context.cyberAlerts.length > 0) { | |
| 205 | + sections.push(`\n[CYBER ALERTS — ${context.cyberAlerts.length} active]`); | |
| 206 | + for (const alert of context.cyberAlerts.slice(0, 10)) { | |
| 207 | + sections.push( | |
| 208 | + ` ${alert.id} | ${alert.severity} | ${alert.vendor}/${alert.product} | ${alert.name} | Due:${alert.due}` | |
| 209 | + ); | |
| 210 | + } | |
| 211 | + } | |
| 212 | + | |
| 213 | + return sections.join('\n'); | |
| 214 | +} | |
| 215 | + | |
| 216 | +/* ───────────────────────────────────────────────────────────── | |
| 217 | + Intelligence Analysis | |
| 218 | + ───────────────────────────────────────────────────────────── */ | |
| 219 | + | |
| 220 | +export async function analyzeIntelligence( | |
| 221 | + client: GoogleGenerativeAI, | |
| 222 | + context: IntelligenceContext, | |
| 223 | + userQuery: string | |
| 224 | +): Promise<string> { | |
| 225 | + const model: GenerativeModel = client.getGenerativeModel({ | |
| 226 | + model: 'gemini-2.0-flash', | |
| 227 | + systemInstruction: SYSTEM_PROMPT, | |
| 228 | + }); | |
| 229 | + | |
| 230 | + const contextData = serializeContext(context); | |
| 231 | + | |
| 232 | + const prompt = `## CURRENT OPERATIONAL DATA | |
| 233 | +${contextData} | |
| 234 | + | |
| 235 | +## ANALYST QUERY | |
| 236 | +${userQuery} | |
| 237 | + | |
| 238 | +Provide your intelligence assessment based on the operational data above and the analyst's query.`; | |
| 239 | + | |
| 240 | + const result = await model.generateContent(prompt); | |
| 241 | + const response = result.response; | |
| 242 | + return response.text(); | |
| 243 | +} | |
| 244 | + | |
| 245 | +/* ───────────────────────────────────────────────────────────── | |
| 246 | + Daily Briefing Generation | |
| 247 | + ───────────────────────────────────────────────────────────── */ | |
| 248 | + | |
| 249 | +export async function generateBriefing( | |
| 250 | + client: GoogleGenerativeAI, | |
| 251 | + context: IntelligenceContext | |
| 252 | +): Promise<string> { | |
| 253 | + const model: GenerativeModel = client.getGenerativeModel({ | |
| 254 | + model: 'gemini-2.0-flash', | |
| 255 | + systemInstruction: SYSTEM_PROMPT, | |
| 256 | + }); | |
| 257 | + | |
| 258 | + const contextData = serializeContext(context); | |
| 259 | + | |
| 260 | + const prompt = `${BRIEFING_PROMPT} | |
| 261 | + | |
| 262 | +## CURRENT OPERATIONAL DATA | |
| 263 | +${contextData} | |
| 264 | + | |
| 265 | +Generate the briefing now.`; | |
| 266 | + | |
| 267 | + const result = await model.generateContent(prompt); | |
| 268 | + const response = result.response; | |
| 269 | + return response.text(); | |
| 270 | +} |