Elffuss BraidHub

kikocis/osiris public

a7136ef5ec82 · 11.4 KiBRawPermalink
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
9import { GoogleGenerativeAI, type GenerativeModel } from '@google/generative-ai';
10
11/* ─────────────────────────────────────────────────────────────
12 Data Interfaces — Zero `any` types
13 ───────────────────────────────────────────────────────────── */
14
15export 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
28export 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
40export 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
53export 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
64export 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
76const 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
851. **PATTERN RECOGNITION**: Cross-reference events across feeds. A cyber attack + earthquake + political instability in the same region = elevated compound risk
862. **THREAT ASSESSMENT**: Rate threats on a CRITICAL / HIGH / ELEVATED / LOW scale with reasoning
873. **TEMPORAL ANALYSIS**: Identify acceleration patterns — are events clustering? Is frequency increasing?
884. **GEOSPATIAL CORRELATION**: Events in proximity may be related. Identify geographic hotspots
895. **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
106You have access to the live intelligence context of the OSIRIS platform. Analyze it with precision.`;
107
108const 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
1152-3 sentence overview of the current global threat landscape based on available data.
116
117### II. PRIORITY INTELLIGENCE REQUIREMENTS (PIRs)
118Identify the top 3-5 most significant developments from the data feeds, ranked by assessed impact.
119
120### III. SEISMIC & NATURAL HAZARD ASSESSMENT
121Analyze earthquake data for patterns — clustering, tectonic corridor activity, tsunami risk.
122
123### IV. GEOPOLITICAL & CONFLICT INTELLIGENCE
124Synthesize news feeds for conflict escalation patterns, diplomatic shifts, or emerging crises.
125
126### V. CYBER THREAT LANDSCAPE
127Assess active CVEs and cyber alerts for coordinated campaign indicators or critical infrastructure risk.
128
129### VI. COMPOUND RISK SCENARIOS
130Identify 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
138State overall confidence level and key analytical gaps.
139
140Analyze the provided data thoroughly. Be specific — reference actual events, magnitudes, locations, and CVE IDs from the context.`;
141
142/* ─────────────────────────────────────────────────────────────
143 Client Factory
144 ───────────────────────────────────────────────────────────── */
145
146export function createGeminiClient(apiKey: string): GoogleGenerativeAI {
147 return new GoogleGenerativeAI(apiKey);
148}
149
150/* ─────────────────────────────────────────────────────────────
151 API Key Rotation — Round-robin through available keys
152 ───────────────────────────────────────────────────────────── */
153
154let _keyIndex = 0;
155
156export 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
169function 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
220export 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
238Provide 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
249export 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
265Generate the briefing now.`;
266
267 const result = await model.generateContent(prompt);
268 const response = result.response;
269 return response.text();
270}