adaptive-bitmask 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,431 @@
1
+ import { WebSocket } from 'ws';
2
+ import { S as SchemaManager, C as Coordinator, A as Arbiter, a as SchemaConfig, b as CoordinatorConfig, c as ArbiterConfig, d as ArbiterResult, B as BitmaskMessage } from './coordinator-Df48t6yJ.mjs';
3
+ export { e as AggregationResult, f as ArbiterTelemetryEvent, g as BITMASK_WIDTH, h as BitConfidence, i as Bitmask, j as BitmaskMessageData, k as CoordinatorDropReason, l as CoordinatorTelemetryEvent, D as Decision, E as EMERGENCY_RANGE, m as EncodeOptions, n as ExportedSchema, H as HIGH_FREQ_RANGE, M as MED_FREQ_RANGE, o as MESSAGE_SIZE_BYTES, P as PruneResult, p as SchemaSnapshot, q as ScoreStrategiesOptions, r as StaleMessagePolicy, s as StrategyCandidate, t as StrategyDecisionResult, u as StrategyScore, v as activeBits, w as clearBit, x as createFinancialArbiter, y as createRoboticArbiter, z as decode, F as delta, G as emergencyBits, I as empty, J as encode, K as forEachSetBit, L as fromBytes, N as hammingDistance, O as hasEmergency, Q as intersect, R as merge, T as popcount, U as setBit, V as testBit, W as toBytes } from './coordinator-Df48t6yJ.mjs';
4
+
5
+ /**
6
+ * WebSocket transport layer for adaptive-bitmask
7
+ *
8
+ * Real-time bidirectional communication for multi-agent coordination
9
+ */
10
+
11
+ interface WebSocketTransportConfig {
12
+ /** WebSocket server port */
13
+ port: number;
14
+ /** Maximum concurrent connections */
15
+ maxConnections?: number;
16
+ /** Connection timeout in milliseconds */
17
+ connectionTimeoutMs?: number;
18
+ /** Message timeout in milliseconds */
19
+ messageTimeoutMs?: number;
20
+ /** Enable compression */
21
+ enableCompression?: boolean;
22
+ /** Circuit breaker failure threshold */
23
+ circuitBreakerThreshold?: number;
24
+ /** Health check interval */
25
+ healthCheckIntervalMs?: number;
26
+ }
27
+ interface ConnectedAgent {
28
+ id: number;
29
+ socket: WebSocket;
30
+ lastSeen: number;
31
+ messagesReceived: number;
32
+ messagesSent: number;
33
+ schemaVersion: number;
34
+ }
35
+ interface TransportMessage {
36
+ type: 'BITMASK_MESSAGE' | 'HEARTBEAT' | 'ERROR' | 'SCHEMA_UPDATE';
37
+ payload: Uint8Array | object;
38
+ timestamp: number;
39
+ agentId?: number;
40
+ }
41
+ declare class WebSocketTransport {
42
+ private server;
43
+ private agents;
44
+ private nextAgentId;
45
+ private logger;
46
+ private metrics;
47
+ private circuitBreaker;
48
+ private config;
49
+ private isShuttingDown;
50
+ constructor(config: WebSocketTransportConfig);
51
+ private setupEventHandlers;
52
+ private handleConnection;
53
+ private handleMessage;
54
+ private processMessage;
55
+ private parseMessage;
56
+ private sendMessage;
57
+ private handleDisconnection;
58
+ private startHeartbeat;
59
+ private startHealthChecks;
60
+ broadcast(message: TransportMessage): void;
61
+ sendToAgent(agentId: number, message: TransportMessage): void;
62
+ getConnectedAgents(): ConnectedAgent[];
63
+ getAgentCount(): number;
64
+ getMetrics(): MetricsCollector;
65
+ shutdown(): Promise<void>;
66
+ private listeners;
67
+ private emit;
68
+ on(event: 'message' | 'disconnection', listener: Function): void;
69
+ off(event: 'message' | 'disconnection', listener: Function): void;
70
+ }
71
+ declare function createWebSocketTransport(config: WebSocketTransportConfig): WebSocketTransport;
72
+
73
+ /**
74
+ * HTTP/REST transport layer for adaptive-bitmask
75
+ *
76
+ * Simple REST API for multi-agent coordination over HTTP
77
+ */
78
+
79
+ interface HttpTransportConfig {
80
+ /** HTTP server port */
81
+ port: number;
82
+ /** Request timeout in milliseconds */
83
+ requestTimeoutMs?: number;
84
+ /** Maximum request body size */
85
+ maxBodySize?: number;
86
+ /** Enable CORS */
87
+ enableCors?: boolean;
88
+ /** Circuit breaker failure threshold */
89
+ circuitBreakerThreshold?: number;
90
+ /** Rate limiting requests per minute */
91
+ rateLimitPerMinute?: number;
92
+ }
93
+ interface HttpRequest {
94
+ method: string;
95
+ url: string;
96
+ headers: Record<string, string>;
97
+ body?: Buffer;
98
+ timestamp: number;
99
+ }
100
+ interface HttpResponse {
101
+ statusCode: number;
102
+ headers: Record<string, string>;
103
+ body?: string | Buffer;
104
+ timestamp: number;
105
+ }
106
+ declare class HttpTransport {
107
+ private server;
108
+ private logger;
109
+ private metrics;
110
+ private circuitBreaker;
111
+ private config;
112
+ private requestCounts;
113
+ private isShuttingDown;
114
+ constructor(config: HttpTransportConfig);
115
+ private handleRequest;
116
+ private processRequest;
117
+ private parseRequestBody;
118
+ private routeRequest;
119
+ private handleCoordinate;
120
+ private handleHealth;
121
+ private handleMetrics;
122
+ private handleGetSchema;
123
+ private handleUpdateSchema;
124
+ private sendResponse;
125
+ private isRateLimited;
126
+ private startRateLimitCleanup;
127
+ start(): void;
128
+ shutdown(): Promise<void>;
129
+ getMetrics(): MetricsCollector;
130
+ private listeners;
131
+ private emit;
132
+ on(event: 'message', listener: Function): void;
133
+ off(event: 'message', listener: Function): void;
134
+ }
135
+ declare function createHttpTransport(config: HttpTransportConfig): HttpTransport;
136
+
137
+ /**
138
+ * Production-grade logging and telemetry for adaptive-bitmask
139
+ *
140
+ * Provides structured logging, metrics collection, and observability
141
+ */
142
+ declare enum LogLevel {
143
+ DEBUG = 0,
144
+ INFO = 1,
145
+ WARN = 2,
146
+ ERROR = 3,
147
+ FATAL = 4
148
+ }
149
+ interface LogEntry {
150
+ timestamp: number;
151
+ level: LogLevel;
152
+ component: string;
153
+ message: string;
154
+ metadata?: Record<string, unknown>;
155
+ error?: {
156
+ name: string;
157
+ message: string;
158
+ stack?: string;
159
+ code?: string;
160
+ };
161
+ }
162
+ interface Metrics {
163
+ coordinationLatencyUs: number[];
164
+ messageProcessingTimeUs: number[];
165
+ encodingTimeUs: number[];
166
+ decodingTimeUs: number[];
167
+ messagesProcessed: number;
168
+ agentsConnected: number;
169
+ featuresActive: number;
170
+ schemaVersion: number;
171
+ errorsByType: Record<string, number>;
172
+ timeouts: number;
173
+ circuitBreakerTrips: number;
174
+ memoryUsageMB: number;
175
+ bufferUtilization: number;
176
+ lastReset: number;
177
+ uptimeMs: number;
178
+ }
179
+ interface HealthStatus {
180
+ status: 'HEALTHY' | 'DEGRADED' | 'UNHEALTHY';
181
+ uptime: number;
182
+ version: string;
183
+ timestamp: number;
184
+ checks: {
185
+ memory: boolean;
186
+ latency: boolean;
187
+ errorRate: boolean;
188
+ circuitBreakers: boolean;
189
+ };
190
+ metrics: {
191
+ messagesProcessed: number;
192
+ agentsConnected: number;
193
+ coordinationLatencyUs: {
194
+ mean: number;
195
+ p50: number;
196
+ p95: number;
197
+ p99: number;
198
+ max: number;
199
+ min: number;
200
+ };
201
+ memoryUsageMB: number;
202
+ errorsByType: Record<string, number>;
203
+ };
204
+ }
205
+ declare class Logger {
206
+ private static instance;
207
+ private logLevel;
208
+ private logs;
209
+ private maxLogSize;
210
+ private onLog?;
211
+ private constructor();
212
+ static getInstance(): Logger;
213
+ setLogLevel(level: LogLevel): void;
214
+ setLogCallback(callback: (entry: LogEntry) => void): void;
215
+ private shouldLog;
216
+ private createLogEntry;
217
+ private addLog;
218
+ debug(component: string, message: string, metadata?: Record<string, unknown>): void;
219
+ info(component: string, message: string, metadata?: Record<string, unknown>): void;
220
+ warn(component: string, message: string, metadata?: Record<string, unknown>): void;
221
+ error(component: string, message: string, error?: Error, metadata?: Record<string, unknown>): void;
222
+ fatal(component: string, message: string, error?: Error, metadata?: Record<string, unknown>): void;
223
+ getRecentLogs(count?: number): LogEntry[];
224
+ getLogsByLevel(level: LogLevel): LogEntry[];
225
+ clearLogs(): void;
226
+ }
227
+ declare class MetricsCollector {
228
+ private metrics;
229
+ private startTime;
230
+ private logger;
231
+ constructor();
232
+ private initializeMetrics;
233
+ recordCoordinationLatency(latencyUs: number): void;
234
+ recordMessageProcessingTime(timeUs: number): void;
235
+ recordEncodingTime(timeUs: number): void;
236
+ recordDecodingTime(timeUs: number): void;
237
+ incrementMessagesProcessed(): void;
238
+ setAgentsConnected(count: number): void;
239
+ setFeaturesActive(count: number): void;
240
+ setSchemaVersion(version: number): void;
241
+ recordError(errorType: string): void;
242
+ recordTimeout(): void;
243
+ recordCircuitBreakerTrip(): void;
244
+ updateMemoryUsage(): void;
245
+ setBufferUtilization(utilization: number): void;
246
+ getMetrics(): Metrics;
247
+ getLatencyStats(): {
248
+ mean: number;
249
+ p50: number;
250
+ p95: number;
251
+ p99: number;
252
+ max: number;
253
+ min: number;
254
+ };
255
+ reset(): void;
256
+ }
257
+ declare class HealthChecker {
258
+ private metrics;
259
+ private logger;
260
+ private version;
261
+ constructor(metrics: MetricsCollector);
262
+ getHealthStatus(): HealthStatus;
263
+ private getErrorRate;
264
+ startHealthCheck(intervalMs?: number): void;
265
+ }
266
+ declare class Profiler {
267
+ private static sessions;
268
+ private logger;
269
+ static startSession(sessionId: string): void;
270
+ static recordEvent(sessionId: string, event: string, data?: unknown): void;
271
+ static endSession(sessionId: string): Array<{
272
+ event: string;
273
+ time: number;
274
+ data?: unknown;
275
+ }>;
276
+ private static getLogger;
277
+ }
278
+ declare function createProductionLogger(config?: {
279
+ level?: LogLevel;
280
+ maxLogSize?: number;
281
+ enableConsole?: boolean;
282
+ }): Logger;
283
+ declare function createMetricsCollector(autoUpdateMs?: number): MetricsCollector;
284
+
285
+ /**
286
+ * Production-grade error handling for adaptive-bitmask
287
+ *
288
+ * Provides structured error classes, validation, and graceful degradation
289
+ */
290
+ declare class AdaptiveBitmaskError extends Error {
291
+ readonly code: string;
292
+ readonly category: 'VALIDATION' | 'RUNTIME' | 'NETWORK' | 'SYSTEM';
293
+ readonly context?: Record<string, unknown>;
294
+ readonly timestamp: number;
295
+ constructor(message: string, code: string, category: 'VALIDATION' | 'RUNTIME' | 'NETWORK' | 'SYSTEM', context?: Record<string, unknown>);
296
+ toJSON(): {
297
+ name: string;
298
+ message: string;
299
+ code: string;
300
+ category: "VALIDATION" | "RUNTIME" | "NETWORK" | "SYSTEM";
301
+ context: Record<string, unknown> | undefined;
302
+ timestamp: number;
303
+ stack: string | undefined;
304
+ };
305
+ }
306
+ declare class ValidationError extends AdaptiveBitmaskError {
307
+ constructor(message: string, context?: Record<string, unknown>);
308
+ }
309
+ declare class SchemaValidationError extends ValidationError {
310
+ constructor(message: string, schemaVersion?: number, feature?: string);
311
+ }
312
+ declare class MessageValidationError extends ValidationError {
313
+ constructor(message: string, agentId?: number, messageSize?: number);
314
+ }
315
+ declare class RuntimeError extends AdaptiveBitmaskError {
316
+ constructor(message: string, context?: Record<string, unknown>);
317
+ }
318
+ declare class CoordinatorError extends RuntimeError {
319
+ constructor(message: string, agentCount?: number, deadlineMs?: number);
320
+ }
321
+ declare class ArbiterError extends RuntimeError {
322
+ constructor(message: string, score?: number, decision?: string);
323
+ }
324
+ declare class NetworkError extends AdaptiveBitmaskError {
325
+ constructor(message: string, context?: Record<string, unknown>);
326
+ }
327
+ declare class TimeoutError extends NetworkError {
328
+ constructor(message: string, timeoutMs?: number, operation?: string);
329
+ }
330
+ declare class SystemError extends AdaptiveBitmaskError {
331
+ constructor(message: string, context?: Record<string, unknown>);
332
+ }
333
+ declare class MemoryError extends SystemError {
334
+ constructor(message: string, memoryUsage?: number, limit?: number);
335
+ }
336
+ declare class Validator {
337
+ static validateAgentId(agentId: number): void;
338
+ static validateFeatureName(feature: string): void;
339
+ static validateFeatureArray(features: string[]): void;
340
+ static validateSchemaVersion(version: number): void;
341
+ static validateDeadlineMs(deadlineMs: number): void;
342
+ static validateTimeout(timeoutMs: number, operation: string): void;
343
+ }
344
+ declare class CircuitBreaker {
345
+ private readonly failureThreshold;
346
+ private readonly recoveryTimeoutMs;
347
+ private readonly monitoringPeriodMs;
348
+ private failures;
349
+ private lastFailureTime;
350
+ private state;
351
+ constructor(failureThreshold?: number, recoveryTimeoutMs?: number, monitoringPeriodMs?: number);
352
+ execute<T>(operation: () => Promise<T>, operationName: string): Promise<T>;
353
+ private recordFailure;
354
+ private reset;
355
+ getStatus(): {
356
+ state: "CLOSED" | "OPEN" | "HALF_OPEN";
357
+ failures: number;
358
+ lastFailureTime: number;
359
+ isHealthy: boolean;
360
+ };
361
+ }
362
+ declare class TimeoutManager {
363
+ static withTimeout<T>(promise: Promise<T>, timeoutMs: number, operation: string): Promise<T>;
364
+ }
365
+ declare class RecoveryManager {
366
+ static withRetry<T>(operation: () => Promise<T>, maxRetries?: number, baseDelayMs?: number, operationName?: string): Promise<T>;
367
+ }
368
+
369
+ interface SharedCognitionConfig {
370
+ schema?: SchemaConfig;
371
+ coordinator?: CoordinatorConfig;
372
+ arbiter?: ArbiterConfig;
373
+ /** Automatically register unknown features when they are observed. Default: true. */
374
+ autoRegister?: boolean;
375
+ }
376
+ interface SwarmTickResult {
377
+ /** The final decision: EXECUTE, SYNTHESIZE, or REJECT */
378
+ decision: ArbiterResult['decision'];
379
+ /** Final confidence-adjusted composite score [0, 1] */
380
+ finalScore: number;
381
+ /** End-to-end latency in milliseconds */
382
+ latencyMs: number;
383
+ /** Array of features that were active in the consensus mask */
384
+ activeFeatures: string[];
385
+ /** Full result from the Arbiter for advanced inspection */
386
+ arbiterResult: ArbiterResult;
387
+ }
388
+ /**
389
+ * SharedCognition
390
+ *
391
+ * The high-level wrapper that sits on top of the adaptive-bitmask core engine.
392
+ * Tailored for instant multi-agent coordination without boilerplate.
393
+ */
394
+ declare class SharedCognition {
395
+ schema: SchemaManager;
396
+ coordinator: Coordinator;
397
+ arbiter: Arbiter;
398
+ autoRegister: boolean;
399
+ constructor(config?: SharedCognitionConfig);
400
+ /**
401
+ * Process a single coordination tick across the entire swarm.
402
+ *
403
+ * 1. Encodes all agent string observations into 64-bit masks
404
+ * 2. Routes through the Meta-Coordinator
405
+ * 3. Arbitrates a final decision
406
+ *
407
+ * @param agentObservations Array of string feature arrays, one per agent
408
+ * @returns The unified swarm decision and latency
409
+ */
410
+ processSwarmTick(agentObservations: string[][]): SwarmTickResult;
411
+ }
412
+
413
+ interface TransportEnvelope {
414
+ /** Schema fingerprint expected by sender. */
415
+ schemaFingerprint: string;
416
+ /** Optional round identifier from transport layer. */
417
+ roundId?: string;
418
+ /** 24-byte bitmask payload. */
419
+ payload: Uint8Array;
420
+ }
421
+ /**
422
+ * Wrap a bitmask message with schema metadata for transport-level validation.
423
+ * Payload stays exactly the protocol 24-byte message.
424
+ */
425
+ declare function createEnvelope(message: BitmaskMessage, schemaFingerprint: string, roundId?: string): TransportEnvelope;
426
+ /**
427
+ * Validate an envelope and decode the underlying 24-byte message.
428
+ */
429
+ declare function decodeEnvelope(envelope: TransportEnvelope, expectedSchemaFingerprint?: string): BitmaskMessage;
430
+
431
+ export { AdaptiveBitmaskError, Arbiter, ArbiterConfig, ArbiterError, ArbiterResult, BitmaskMessage, CircuitBreaker, type ConnectedAgent, Coordinator, CoordinatorConfig, CoordinatorError, HealthChecker, type HealthStatus, type HttpRequest, type HttpResponse, HttpTransport, type HttpTransportConfig, type LogEntry, LogLevel, Logger, MemoryError, MessageValidationError, type Metrics, MetricsCollector, NetworkError, Profiler, RecoveryManager, RuntimeError, SchemaConfig, SchemaManager, SchemaValidationError, SharedCognition, type SharedCognitionConfig, type SwarmTickResult, SystemError, TimeoutError, TimeoutManager, type TransportEnvelope, type TransportMessage, ValidationError, Validator, WebSocketTransport, type WebSocketTransportConfig, createEnvelope, createHttpTransport, createMetricsCollector, createProductionLogger, createWebSocketTransport, decodeEnvelope };