Elffuss BraidHub

kikocis/osiris public

master · 7.7 KiBRawPermalink
1/**
2 * ╔══════════════════════════════════════════════════════════════════╗
3 * ║ POLYBOLOS SDK — Lattice Adapter ║
4 * ║ Anduril Lattice Entity Translation Layer ║
5 * ║ ║
6 * ║ Translates Lattice Track/Sensor state → Polybolos Entities ║
7 * ╚══════════════════════════════════════════════════════════════════╝
8 */
9
10import {
11 type PolybolosEntity,
12 type LatticeConfig,
13 type LatticeConnectionStatus,
14 Domain,
15 EntityType,
16 ThreatLevel,
17 Classification,
18} from './types';
19
20// ── Lattice Raw Types (Simulated from Lattice SDK docs) ────────────
21
22interface LatticeTrack {
23 entityId: string;
24 displayName: string;
25 trackType: string; // 'AIR' | 'SURFACE' | 'SUBSURFACE' | 'SPACE' | 'LAND'
26 position: {
27 latitude_deg: number;
28 longitude_deg: number;
29 altitude_hae_m?: number;
30 };
31 kinematics?: {
32 speed_mps?: number;
33 heading_deg?: number;
34 };
35 classification?: string;
36 allegiance?: string; // 'FRIENDLY' | 'HOSTILE' | 'NEUTRAL' | 'UNKNOWN'
37 timestamp: string;
38 metadata?: Record<string, string>;
39}
40
41// ── Domain Mapping ─────────────────────────────────────────────────
42
43const LATTICE_DOMAIN_MAP: Record<string, Domain> = {
44 'AIR': Domain.AIR,
45 'SURFACE': Domain.SEA,
46 'SUBSURFACE': Domain.SUBSURFACE,
47 'SPACE': Domain.SPACE,
48 'LAND': Domain.LAND,
49};
50
51const ALLEGIANCE_THREAT_MAP: Record<string, ThreatLevel> = {
52 'HOSTILE': ThreatLevel.CRITICAL,
53 'SUSPECT': ThreatLevel.HIGH,
54 'UNKNOWN': ThreatLevel.ELEVATED,
55 'NEUTRAL': ThreatLevel.LOW,
56 'FRIENDLY': ThreatLevel.NONE,
57};
58
59const ALLEGIANCE_COLOR_MAP: Record<string, string> = {
60 'HOSTILE': '#FF1744',
61 'SUSPECT': '#FF9500',
62 'UNKNOWN': '#FFD700',
63 'NEUTRAL': '#00BCD4',
64 'FRIENDLY': '#00E676',
65};
66
67// ── Adapter Class ──────────────────────────────────────────────────
68
69export class LatticeAdapter {
70 private config: LatticeConfig;
71 private status: LatticeConnectionStatus = 'disconnected';
72 private entityBuffer: Map<string, PolybolosEntity> = new Map();
73 private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
74 private eventSource: EventSource | null = null;
75
76 constructor(config: LatticeConfig) {
77 this.config = config;
78 }
79
80 /** Current connection status */
81 getStatus(): LatticeConnectionStatus {
82 return this.status;
83 }
84
85 /** All currently tracked Lattice entities */
86 getEntities(): PolybolosEntity[] {
87 return Array.from(this.entityBuffer.values());
88 }
89
90 /** Entity count */
91 getEntityCount(): number {
92 return this.entityBuffer.size;
93 }
94
95 /**
96 * Connect to Lattice entity stream.
97 * In production, this would open a gRPC stream or SSE connection
98 * to the Lattice API. For the SDK layer, we simulate the protocol.
99 */
100 async connect(): Promise<void> {
101 this.setStatus('connecting');
102
103 try {
104 // In a real Lattice integration, this would be:
105 // const stream = await latticeClient.subscribeToEntities(this.config.entityFilter);
106 // stream.on('data', (track) => this.handleTrack(track));
107
108 // For now, we validate the configuration and set up the adapter
109 if (!this.config.endpoint || !this.config.token) {
110 this.setStatus('disconnected');
111 return;
112 }
113
114 this.setStatus('authenticated');
115
116 // Attempt SSE connection to Lattice endpoint
117 if (typeof EventSource !== 'undefined') {
118 try {
119 this.eventSource = new EventSource(
120 `${this.config.endpoint}/v1/entities/stream?token=${this.config.token}`
121 );
122
123 this.eventSource.onopen = () => {
124 this.setStatus('streaming');
125 };
126
127 this.eventSource.onmessage = (event) => {
128 try {
129 const track: LatticeTrack = JSON.parse(event.data);
130 const entity = this.translateTrack(track);
131 this.entityBuffer.set(entity.id, entity);
132 } catch {
133 // Skip malformed messages
134 }
135 };
136
137 this.eventSource.onerror = () => {
138 this.setStatus('error');
139 this.scheduleReconnect();
140 };
141 } catch {
142 // EventSource connection failed, adapter remains in authenticated state
143 this.setStatus('authenticated');
144 }
145 }
146 } catch {
147 this.setStatus('error');
148 this.scheduleReconnect();
149 }
150 }
151
152 /** Disconnect from Lattice */
153 disconnect(): void {
154 if (this.eventSource) {
155 this.eventSource.close();
156 this.eventSource = null;
157 }
158 if (this.reconnectTimer) {
159 clearTimeout(this.reconnectTimer);
160 this.reconnectTimer = null;
161 }
162 this.entityBuffer.clear();
163 this.setStatus('disconnected');
164 }
165
166 /**
167 * Manually ingest a Lattice track (for webhook/push integrations).
168 * This is the public API for external systems to push Lattice-format
169 * data directly into the Polybolos COP.
170 */
171 ingestTrack(track: LatticeTrack): PolybolosEntity {
172 const entity = this.translateTrack(track);
173 this.entityBuffer.set(entity.id, entity);
174 return entity;
175 }
176
177 /**
178 * Translate a raw Lattice Track into a normalized Polybolos Entity.
179 * This is the core intelligence translation function.
180 */
181 private translateTrack(track: LatticeTrack): PolybolosEntity {
182 const domain = LATTICE_DOMAIN_MAP[track.trackType] || Domain.LAND;
183 const allegiance = track.allegiance || 'UNKNOWN';
184 const threat = ALLEGIANCE_THREAT_MAP[allegiance] || ThreatLevel.ELEVATED;
185 const color = ALLEGIANCE_COLOR_MAP[allegiance] || '#FFD700';
186
187 // Determine icon based on domain
188 let icon = 'dot-gold';
189 if (domain === Domain.AIR) icon = 'plane-cyan';
190 else if (domain === Domain.SEA) icon = 'dot-orange';
191 else if (domain === Domain.SPACE) icon = 'dot-gold';
192
193 return {
194 id: `lattice-${track.entityId}`,
195 name: track.displayName || `TRACK-${track.entityId.slice(0, 8)}`,
196 domain,
197 entityType: EntityType.TRACK,
198 position: {
199 lat: track.position.latitude_deg,
200 lng: track.position.longitude_deg,
201 alt: track.position.altitude_hae_m,
202 heading: track.kinematics?.heading_deg,
203 speed: track.kinematics?.speed_mps
204 ? track.kinematics.speed_mps * 1.94384 // m/s → knots
205 : undefined,
206 },
207 threat,
208 classification: Classification.UNCLASSIFIED,
209 source: {
210 provider: 'anduril-lattice',
211 feed: 'entity-stream',
212 originalId: track.entityId,
213 confidence: 0.95,
214 },
215 timestamp: track.timestamp || new Date().toISOString(),
216 properties: {
217 allegiance,
218 trackType: track.trackType,
219 ...track.metadata,
220 },
221 display: {
222 color,
223 icon,
224 layerType: domain === Domain.AIR ? 'symbol' : 'circle',
225 glow: threat >= ThreatLevel.HIGH,
226 scale: threat >= ThreatLevel.CRITICAL ? 1.5 : 1.0,
227 },
228 };
229 }
230
231 private setStatus(status: LatticeConnectionStatus): void {
232 this.status = status;
233 this.config.onStatusChange?.(status);
234 }
235
236 private scheduleReconnect(): void {
237 if (this.reconnectTimer) return;
238 this.reconnectTimer = setTimeout(() => {
239 this.reconnectTimer = null;
240 this.connect();
241 }, 5000);
242 }
243}