@a0n/aeon 5.0.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.
Files changed (73) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +199 -0
  3. package/dist/CryptoProvider-SLWjqByk.d.cts +407 -0
  4. package/dist/CryptoProvider-SLWjqByk.d.ts +407 -0
  5. package/dist/compression/index.cjs +1445 -0
  6. package/dist/compression/index.cjs.map +1 -0
  7. package/dist/compression/index.d.cts +451 -0
  8. package/dist/compression/index.d.ts +451 -0
  9. package/dist/compression/index.js +1426 -0
  10. package/dist/compression/index.js.map +1 -0
  11. package/dist/core/index.cjs +4 -0
  12. package/dist/core/index.cjs.map +1 -0
  13. package/dist/core/index.d.cts +212 -0
  14. package/dist/core/index.d.ts +212 -0
  15. package/dist/core/index.js +3 -0
  16. package/dist/core/index.js.map +1 -0
  17. package/dist/crypto/index.cjs +130 -0
  18. package/dist/crypto/index.cjs.map +1 -0
  19. package/dist/crypto/index.d.cts +56 -0
  20. package/dist/crypto/index.d.ts +56 -0
  21. package/dist/crypto/index.js +124 -0
  22. package/dist/crypto/index.js.map +1 -0
  23. package/dist/distributed/index.cjs +2586 -0
  24. package/dist/distributed/index.cjs.map +1 -0
  25. package/dist/distributed/index.d.cts +1005 -0
  26. package/dist/distributed/index.d.ts +1005 -0
  27. package/dist/distributed/index.js +2580 -0
  28. package/dist/distributed/index.js.map +1 -0
  29. package/dist/index.cjs +10953 -0
  30. package/dist/index.cjs.map +1 -0
  31. package/dist/index.d.cts +1953 -0
  32. package/dist/index.d.ts +1953 -0
  33. package/dist/index.js +10828 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/offline/index.cjs +419 -0
  36. package/dist/offline/index.cjs.map +1 -0
  37. package/dist/offline/index.d.cts +148 -0
  38. package/dist/offline/index.d.ts +148 -0
  39. package/dist/offline/index.js +415 -0
  40. package/dist/offline/index.js.map +1 -0
  41. package/dist/optimization/index.cjs +800 -0
  42. package/dist/optimization/index.cjs.map +1 -0
  43. package/dist/optimization/index.d.cts +347 -0
  44. package/dist/optimization/index.d.ts +347 -0
  45. package/dist/optimization/index.js +790 -0
  46. package/dist/optimization/index.js.map +1 -0
  47. package/dist/persistence/index.cjs +207 -0
  48. package/dist/persistence/index.cjs.map +1 -0
  49. package/dist/persistence/index.d.cts +95 -0
  50. package/dist/persistence/index.d.ts +95 -0
  51. package/dist/persistence/index.js +204 -0
  52. package/dist/persistence/index.js.map +1 -0
  53. package/dist/presence/index.cjs +489 -0
  54. package/dist/presence/index.cjs.map +1 -0
  55. package/dist/presence/index.d.cts +283 -0
  56. package/dist/presence/index.d.ts +283 -0
  57. package/dist/presence/index.js +485 -0
  58. package/dist/presence/index.js.map +1 -0
  59. package/dist/types-CMxO7QF0.d.cts +33 -0
  60. package/dist/types-CMxO7QF0.d.ts +33 -0
  61. package/dist/utils/index.cjs +64 -0
  62. package/dist/utils/index.cjs.map +1 -0
  63. package/dist/utils/index.d.cts +38 -0
  64. package/dist/utils/index.d.ts +38 -0
  65. package/dist/utils/index.js +57 -0
  66. package/dist/utils/index.js.map +1 -0
  67. package/dist/versioning/index.cjs +1164 -0
  68. package/dist/versioning/index.cjs.map +1 -0
  69. package/dist/versioning/index.d.cts +537 -0
  70. package/dist/versioning/index.d.ts +537 -0
  71. package/dist/versioning/index.js +1159 -0
  72. package/dist/versioning/index.js.map +1 -0
  73. package/package.json +194 -0
@@ -0,0 +1,1953 @@
1
+ export { BandwidthProfile, CRDTOperation, ConflictDetectionResult, EventCallback, EventUnsubscribe, IEventEmitter, NetworkState, Operation, OperationPriority, OperationStatus, OperationType, PresenceEmotion, PresenceInfo, PresenceInputState, PresenceScroll, PresenceSelection, PresenceTyping, PresenceViewport, ResolutionStrategy, SyncBatch, SyncCoordinatorConfig, SyncResult, VectorClock } from './core/index.js';
2
+ export { Logger, createNamespacedLogger, disableLogging, getLogger, logger, resetLogger, setLogger } from './utils/index.js';
3
+ export { DashStorageAdapter, DashStorageAdapterHooks, DashStorageAdapterOptions, DashStorageBackend, DashStorageChange, DashSyncClient, DashSyncRule, DashSyncRules, DashSyncUrgency, InMemoryStorageAdapter } from './persistence/index.js';
4
+ export { P as PersistedEnvelope, a as PersistenceDeserializer, b as PersistenceSerializer, S as StorageAdapter } from './types-CMxO7QF0.js';
5
+ export { CompatibilityRule, DataTransformer, FieldTransformer, Migration, MigrationEngine, MigrationIntegrityEntry, MigrationRecord, MigrationResult, MigrationState, MigrationTracker, MigrationTrackerOptions, MigrationTrackerPersistenceConfig, MigrationTrackerPersistenceData, RollbackPath, SchemaVersion, SchemaVersionManager, TransformationResult, TransformationRule, VersionMetadata } from './versioning/index.js';
6
+ export { Handshake, MergeStrategy, ProtocolError, ReconciliationResult, RecordPathObservationInput, RecordShardObservationInput, RecoveryConflict, RecoveryLedger, RecoveryLedgerConfig, RecoveryLedgerSnapshot, RecoveryPathObservation, RecoveryPathStatus, RecoveryShardObservation, RecoveryShardRole, RecoveryStatus, Replica, ReplicationEvent, ReplicationManager, ReplicationManagerOptions, ReplicationPersistenceConfig, ReplicationPersistenceData, ReplicationPolicy, StateDiff, StateReconciler, StateVersion, SyncCoordinator, SyncEvent, SyncMessage, SyncNode, SyncProtocol, SyncProtocolOptions, SyncProtocolPersistenceConfig, SyncProtocolPersistenceData, SyncRequest, SyncResponse, SyncSession } from './distributed/index.js';
7
+ export { OfflineOperation, OfflineOperationQueue, OfflineOperationQueueOptions, OfflineQueueEvents, OfflineQueuePersistenceConfig, OfflineQueueStats, getOfflineOperationQueue, resetOfflineOperationQueue } from './offline/index.js';
8
+ export { BUILTIN_CODECS, BrotliCodec, ChunkResult, CompressedBatch, CompressedChunk, CompressionCodec, CompressionEngine, CompressionStats, DeltaBatch, DeltaCodec, DeltaOperation, DeltaStats, DeltaSyncOptimizer, DictionaryCodec, GzipCodec, HuffmanCodec, LZ77Codec, PURE_JS_CODECS, RLECodec, RawCodec, TopologicalCompressionResult, TopologicalCompressor, TopologicalCompressorConfig, getCodecById, getCompressionEngine, getDeltaSyncOptimizer, resetCompressionEngine, resetDeltaSyncOptimizer } from './compression/index.js';
9
+ export { ActivityPattern, AdaptiveCompressionOptimizer, AdaptiveStats, BatchTimingOptimizer, BatchTimingStats, CompressionRecommendation, DeviceProfile, NetworkProfile, NetworkWindow, OperationPattern, OperationPrediction, PrefetchedBatch, PrefetchingEngine, PrefetchingStats, SchedulingDecision, getAdaptiveCompressionOptimizer, getBatchTimingOptimizer, getPrefetchingEngine, resetAdaptiveCompressionOptimizer, resetBatchTimingOptimizer, resetPrefetchingEngine } from './optimization/index.js';
10
+ export { AgentEmotionState, AgentInputState, AgentPresence, AgentPresenceManager, AgentScrollState, AgentSelectionRange, AgentTypingState, AgentViewportState, PresenceEvents, PresenceUpdate, clearAgentPresenceManager, getAgentPresenceManager } from './presence/index.js';
11
+ export { A as AEON_CAPABILITIES, a as AeonCapability, b as AeonCapabilityResult, c as AeonCryptoConfig, d as AeonEncryptionMode, e as AuthenticatedMessageFields, C as Capability, D as DEFAULT_CRYPTO_CONFIG, f as DID, g as DecryptionResult, h as DomainCategory, E as ECKeyPair, i as EncryptedPayload, j as EncryptionAlgorithm, I as ICryptoProvider, k as Identity, K as KeyPair, N as NullCryptoProvider, S as SecureNodeInfo, l as SecureSyncSession, m as SignedSyncData, n as SigningAlgorithm, U as UCANPayload, o as UCANToken, V as VerificationResult } from './CryptoProvider-SLWjqByk.js';
12
+ export { ITransactionSigner, NullTransactionSigner, TransactionSignerErrorCode, TransactionSignerExecuteRequest, TransactionSignerExecuteResponse, TransactionSignerHealth, TransactionSignerMetadata, TransactionSignerPayloadMap, createTransactionSignerAdapter } from './crypto/index.js';
13
+ import 'eventemitter3';
14
+
15
+ /**
16
+ * Aeon Flow Protocol — Type Definitions
17
+ *
18
+ * The Aeon Flow Protocol extracts the fork/race/fold primitive that
19
+ * appears independently across the entire stack (inference, ESI, sync,
20
+ * shell, frontend) into a unified, protocol-level abstraction with a
21
+ * pure binary wire format.
22
+ *
23
+ * @see docs/ebooks/145-log-rolling-pipelined-prefill/ch14-aeon-flow-protocol.md
24
+ */
25
+ /** Fork: opens child streams from a parent */
26
+ declare const FORK = 1;
27
+ /** Race: marks streams as racing — first to complete wins */
28
+ declare const RACE = 2;
29
+ /** Fold: merge results from multiple streams into one */
30
+ declare const FOLD = 4;
31
+ /** Vent: NaN propagation, error, or cancellation */
32
+ declare const VENT = 8;
33
+ /** Fin: stream is complete, no more frames will be sent */
34
+ declare const FIN = 16;
35
+ /** Poison: stream is terminated due to error or cancellation */
36
+ declare const POISON = 32;
37
+ /**
38
+ * A single frame on the wire.
39
+ *
40
+ * FlowFrame {
41
+ * stream_id: u16 // multiplexed stream identifier
42
+ * sequence: u32 // position within stream
43
+ * flags: u8 // FORK | RACE | FOLD | VENT | FIN
44
+ * length: u24 // payload length (up to 16MB)
45
+ * payload: [u8] // raw bytes
46
+ * }
47
+ *
48
+ * Total header: 10 bytes.
49
+ */
50
+ interface FlowFrame {
51
+ /** Multiplexed stream identifier (u16, 0–65535) */
52
+ streamId: number;
53
+ /** Sequence number within the stream (u32) */
54
+ sequence: number;
55
+ /** Bitfield of frame flags (FORK, RACE, FOLD, VENT, FIN) */
56
+ flags: number;
57
+ /** Raw payload bytes */
58
+ payload: Uint8Array;
59
+ }
60
+ /** Stream lifecycle states */
61
+ type FlowStreamState = 'open' | 'racing' | 'folding' | 'closed' | 'vented';
62
+ /**
63
+ * A logical stream within the protocol.
64
+ *
65
+ * Streams form a tree: fork() creates children, race()/fold()
66
+ * operate on sibling streams, vent() propagates down the tree.
67
+ */
68
+ interface FlowStream {
69
+ /** Stream identifier (even = client-initiated, odd = server-initiated) */
70
+ id: number;
71
+ /** Current lifecycle state */
72
+ state: FlowStreamState;
73
+ /** Parent stream that forked this one (undefined for root streams) */
74
+ parent?: number;
75
+ /** Child streams forked from this one */
76
+ children: number[];
77
+ /** Next sequence number to assign */
78
+ nextSequence: number;
79
+ /** Number of frames buffered (for backpressure) */
80
+ bufferedFrames: number;
81
+ /** Accumulated result frames (for race/fold) */
82
+ results: Uint8Array[];
83
+ }
84
+ /**
85
+ * Transport-agnostic interface for sending/receiving binary data.
86
+ *
87
+ * Implementations exist for WebSocket, TCP, WebRTC DataChannel, IPC,
88
+ * and in-memory (for testing).
89
+ */
90
+ interface FlowTransport {
91
+ /** Send binary data over the transport */
92
+ send(data: Uint8Array): void;
93
+ /** Register a handler for incoming data */
94
+ onReceive(handler: (data: Uint8Array) => void): void;
95
+ /** Close the transport */
96
+ close(): void;
97
+ }
98
+ /**
99
+ * Configuration for the Aeon Flow Protocol.
100
+ */
101
+ interface FlowProtocolConfig {
102
+ /**
103
+ * Per-stream high-water mark for backpressure.
104
+ * When a stream has this many unacknowledged frames buffered,
105
+ * sends are paused until the remote drains.
106
+ * @default 64
107
+ */
108
+ highWaterMark: number;
109
+ /**
110
+ * Whether this side initiates even-numbered streams (client)
111
+ * or odd-numbered streams (server). Like HTTP/2.
112
+ * @default 'client'
113
+ */
114
+ role: 'client' | 'server';
115
+ /**
116
+ * Maximum number of concurrent open streams.
117
+ * @default 256
118
+ */
119
+ maxConcurrentStreams: number;
120
+ }
121
+ /**
122
+ * Default protocol configuration.
123
+ */
124
+ declare const DEFAULT_FLOW_CONFIG: FlowProtocolConfig;
125
+ /**
126
+ * Events emitted by the protocol.
127
+ */
128
+ interface FlowProtocolEvents {
129
+ /** A new frame arrived on a stream */
130
+ frame: {
131
+ streamId: number;
132
+ frame: FlowFrame;
133
+ };
134
+ /** A stream reached the FIN state */
135
+ streamEnd: {
136
+ streamId: number;
137
+ };
138
+ /** A stream was vented */
139
+ streamVented: {
140
+ streamId: number;
141
+ };
142
+ /** Backpressure: stream is paused */
143
+ streamPaused: {
144
+ streamId: number;
145
+ };
146
+ /** Backpressure: stream is resumed */
147
+ streamResumed: {
148
+ streamId: number;
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Aeon Flow Protocol — Stream Multiplexing with Fork/Race/Fold
154
+ *
155
+ * The Flow Layer sits between the Frame Layer (FlowCodec) and the
156
+ * Application Layer (inference, ESI, sync, shell, speculate). It manages
157
+ * multiplexed streams with three protocol-level primitives:
158
+ *
159
+ * - **Fork**: Create N child streams from a parent stream. Each child
160
+ * runs independently. Used for parallel pipelines, fragment fetching,
161
+ * reality branching.
162
+ *
163
+ * - **Race**: Mark streams as racing. The first to send a FIN frame wins.
164
+ * Losers are automatically vented. Used for speculative decoding,
165
+ * cache races, A/B testing.
166
+ *
167
+ * - **Fold**: Wait for all streams to complete (or vent), then
168
+ * merge their results via a caller-provided function. Used for shard
169
+ * assembly, fragment stitching, branch reconciliation.
170
+ *
171
+ * Stream IDs: even = client-initiated, odd = server-initiated (like HTTP/2).
172
+ * Backpressure via per-stream high-water mark (configurable, default 64).
173
+ * Vent propagates from parent to all descendants.
174
+ *
175
+ * @see docs/ebooks/145-log-rolling-pipelined-prefill/ch14-aeon-flow-protocol.md
176
+ */
177
+
178
+ type FrameHandler = (frame: FlowFrame) => void;
179
+ type VoidHandler = () => void;
180
+ /**
181
+ * AeonFlowProtocol
182
+ *
183
+ * Manages multiplexed binary streams over a transport with
184
+ * fork/race/fold semantics.
185
+ */
186
+ declare class AeonFlowProtocol {
187
+ private streams;
188
+ private nextEvenId;
189
+ private nextOddId;
190
+ private codec;
191
+ private transport;
192
+ private config;
193
+ private frameHandlers;
194
+ private endHandlers;
195
+ private ventHandlers;
196
+ private raceGroups;
197
+ private foldGroups;
198
+ constructor(transport: FlowTransport, config?: Partial<FlowProtocolConfig>);
199
+ /**
200
+ * Open a new root stream (no parent).
201
+ *
202
+ * Client-initiated streams get even IDs; server-initiated get odd IDs.
203
+ */
204
+ openStream(): number;
205
+ /**
206
+ * Get the current state of a stream.
207
+ */
208
+ getStream(streamId: number): FlowStream | undefined;
209
+ /**
210
+ * Get all active streams.
211
+ */
212
+ getActiveStreams(): FlowStream[];
213
+ /**
214
+ * Fork a parent stream into N child streams.
215
+ *
216
+ * Each child stream is independent and can send/receive frames.
217
+ * The parent tracks all children. Venting the parent vents all children.
218
+ *
219
+ * @param parentStreamId The stream to fork from
220
+ * @param count Number of child streams to create
221
+ * @returns Array of child stream IDs
222
+ */
223
+ fork(parentStreamId: number, count: number): number[];
224
+ /**
225
+ * Race multiple streams. The first to send a FIN frame wins.
226
+ * All other streams in the race are automatically vented.
227
+ *
228
+ * @param streamIds Streams to race (must all be open)
229
+ * @returns Promise resolving with the winner's stream ID and final payload
230
+ */
231
+ race(streamIds: number[]): Promise<{
232
+ winner: number;
233
+ result: Uint8Array;
234
+ }>;
235
+ /**
236
+ * Fold multiple streams: wait for all to complete (or vent),
237
+ * then merge their results.
238
+ *
239
+ * @param streamIds Streams to fold
240
+ * @param merger Function that merges results from all streams
241
+ * @returns Promise resolving with the merged result
242
+ */
243
+ fold(streamIds: number[], merger: (results: Map<number, Uint8Array>) => Uint8Array): Promise<Uint8Array>;
244
+ /**
245
+ * Send a payload on a stream.
246
+ */
247
+ send(streamId: number, payload: Uint8Array, flags?: number): void;
248
+ /**
249
+ * Finish a stream. Sends a FIN frame and transitions to 'closed'.
250
+ *
251
+ * @param streamId Stream to finish
252
+ * @param finalPayload Optional final payload to include with the FIN
253
+ */
254
+ finish(streamId: number, finalPayload?: Uint8Array): void;
255
+ /**
256
+ * Vent a stream. Sends a VENT frame and propagates to all descendants.
257
+ *
258
+ * Venting is the protocol-level equivalent of NaN propagation,
259
+ * AbortSignal cancellation, or error cascading.
260
+ */
261
+ vent(streamId: number): void;
262
+ /**
263
+ * Register a handler for frames arriving on a specific stream.
264
+ */
265
+ onFrame(streamId: number, handler: FrameHandler): () => void;
266
+ /**
267
+ * Register a handler for when a stream ends (FIN received).
268
+ */
269
+ onStreamEnd(streamId: number, handler: VoidHandler): () => void;
270
+ /**
271
+ * Register a handler for when a stream is vented.
272
+ */
273
+ onStreamVented(streamId: number, handler: VoidHandler): () => void;
274
+ /**
275
+ * Close the protocol and underlying transport.
276
+ * Vents all open streams first.
277
+ */
278
+ destroy(): void;
279
+ private handleIncoming;
280
+ private handleFrame;
281
+ private settleRace;
282
+ private settleFold;
283
+ private allocateStreamId;
284
+ private createStream;
285
+ private requireStream;
286
+ private sendFrame;
287
+ private concatenateResults;
288
+ /**
289
+ * Attempt to upgrade to WASM codec without delaying protocol startup.
290
+ * JS codec remains the correctness path if WASM is unavailable.
291
+ */
292
+ private upgradeCodecInBackground;
293
+ }
294
+
295
+ /**
296
+ * Aeon Flow Codec — Binary Frame Layer
297
+ *
298
+ * Encodes and decodes FlowFrames into a compact 10-byte header + payload
299
+ * binary wire format. Optionally accelerated by WASM; falls back to pure JS.
300
+ *
301
+ * Wire format (10 bytes header):
302
+ * [0..1] stream_id u16 big-endian
303
+ * [2..5] sequence u32 big-endian
304
+ * [6] flags u8
305
+ * [7..9] length u24 big-endian (payload bytes, max 16 MB)
306
+ *
307
+ * The codec is zerocopy where possible: decode returns a Uint8Array view
308
+ * into the original buffer rather than copying payload bytes.
309
+ *
310
+ * @see docs/ebooks/145-log-rolling-pipelined-prefill/ch14-aeon-flow-protocol.md
311
+ */
312
+
313
+ /** Header size in bytes */
314
+ declare const HEADER_SIZE = 10;
315
+ /** Maximum payload length (2^24 - 1 = 16,777,215 bytes ≈ 16 MB) */
316
+ declare const MAX_PAYLOAD_LENGTH = 16777215;
317
+ type WasmMode = 'auto' | 'off' | 'force';
318
+ type WasmModuleInput = WebAssembly.Module | BufferSource;
319
+ interface FlowCodecCreateOptions {
320
+ /**
321
+ * WASM mode:
322
+ * - auto: try WASM, fallback to JS on any failure (default)
323
+ * - off: force JS path
324
+ * - force: require WASM, throw if unavailable
325
+ */
326
+ wasmMode?: WasmMode;
327
+ /**
328
+ * Optional caller-supplied WASM module or bytes.
329
+ * Useful in Node/Bun where the caller controls file loading.
330
+ */
331
+ wasmModule?: WasmModuleInput;
332
+ }
333
+ /**
334
+ * FlowCodec — binary encoder/decoder for FlowFrames.
335
+ *
336
+ * Create via `FlowCodec.create()` which attempts WASM acceleration,
337
+ * falling back to the pure JS path (which is always available).
338
+ */
339
+ declare class FlowCodec {
340
+ private wasmInstance;
341
+ private wasmState;
342
+ private constructor();
343
+ /**
344
+ * Create a FlowCodec. Tries WASM acceleration, falls back to JS.
345
+ * The JS path is always correct — WASM is a performance optimization only.
346
+ */
347
+ static create(options?: FlowCodecCreateOptions): Promise<FlowCodec>;
348
+ /**
349
+ * Create a FlowCodec synchronously (JS-only, no WASM attempt).
350
+ */
351
+ static createSync(): FlowCodec;
352
+ /**
353
+ * Whether WASM acceleration is active.
354
+ */
355
+ get isWasmAccelerated(): boolean;
356
+ /**
357
+ * Encode a single FlowFrame into a binary buffer.
358
+ *
359
+ * Returns a new Uint8Array containing the 10-byte header followed by
360
+ * the payload bytes.
361
+ */
362
+ encode(frame: FlowFrame): Uint8Array;
363
+ /**
364
+ * Decode a single FlowFrame from a buffer at the given offset.
365
+ *
366
+ * The returned frame's `payload` is a zerocopy view into the original
367
+ * buffer — no data is copied. Callers who need the payload to outlive
368
+ * the original buffer should `.slice()` it.
369
+ *
370
+ * @returns The decoded frame and the number of bytes consumed.
371
+ */
372
+ decode(buffer: Uint8Array, offset?: number): {
373
+ frame: FlowFrame;
374
+ bytesRead: number;
375
+ };
376
+ /**
377
+ * Encode multiple frames into a single contiguous buffer.
378
+ *
379
+ * Frames are laid out sequentially: [header+payload][header+payload]...
380
+ */
381
+ encodeBatch(frames: FlowFrame[]): Uint8Array;
382
+ /**
383
+ * Decode all frames from a contiguous buffer.
384
+ *
385
+ * Payloads are zerocopy views into the original buffer.
386
+ */
387
+ decodeBatch(buffer: Uint8Array): FlowFrame[];
388
+ private decodeHeader;
389
+ private decodeHeaderInJavaScript;
390
+ private decodeHeaderWithWasm;
391
+ private refreshWasmViews;
392
+ private static createWasmState;
393
+ private static instantiateWasm;
394
+ private static toUint8Array;
395
+ private static loadDefaultWasmModule;
396
+ }
397
+
398
+ /**
399
+ * Frame Reassembler — Out-of-Order Frame Reconstruction
400
+ *
401
+ * Over TCP/WebSocket, frames arrive in order. Over UDP, they don't.
402
+ * The flow header's stream_id (u16) + sequence (u32) already carry
403
+ * the information needed to reassemble — this module uses it.
404
+ *
405
+ * Per-stream reorder buffer with configurable window. Frames arriving
406
+ * out of order are buffered until the gap fills. Frames arriving
407
+ * beyond the window are dropped (assumed lost, will be retransmitted).
408
+ *
409
+ * This is the same insight as QUIC: per-stream ordering eliminates
410
+ * head-of-line blocking across streams. Stream A's lost packet doesn't
411
+ * block Stream B. Only Stream A waits for its own retransmission.
412
+ */
413
+
414
+ interface ReassemblerConfig {
415
+ /**
416
+ * Maximum number of frames to buffer per stream while waiting
417
+ * for gaps to fill. Frames beyond this are dropped.
418
+ * @default 256
419
+ */
420
+ maxBufferPerStream: number;
421
+ /**
422
+ * Maximum number of tracked streams. Oldest streams are evicted
423
+ * when this limit is reached.
424
+ * @default 1024
425
+ */
426
+ maxStreams: number;
427
+ /**
428
+ * Maximum gap in sequence numbers before declaring frames lost.
429
+ * If we receive seq 10 but are expecting seq 3, and gap > maxGap,
430
+ * we skip ahead and emit what we have.
431
+ * @default 64
432
+ */
433
+ maxGap: number;
434
+ }
435
+ interface ReassemblerStats {
436
+ /** Total frames received */
437
+ framesReceived: number;
438
+ /** Frames delivered in order */
439
+ framesDelivered: number;
440
+ /** Frames currently buffered (waiting for gaps) */
441
+ framesBuffered: number;
442
+ /** Frames dropped (duplicates or beyond window) */
443
+ framesDropped: number;
444
+ /** Frames reordered (delivered from buffer after gap fill) */
445
+ framesReordered: number;
446
+ /** Active streams being tracked */
447
+ activeStreams: number;
448
+ }
449
+ declare class FrameReassembler {
450
+ private config;
451
+ private streams;
452
+ private stats;
453
+ constructor(config?: Partial<ReassemblerConfig>);
454
+ /**
455
+ * Process an incoming frame. Returns an array of frames that are
456
+ * now deliverable in order. May return 0 frames (buffered), 1 frame
457
+ * (in order), or multiple frames (gap was filled, releasing buffered).
458
+ *
459
+ * This is the core reassembly operation:
460
+ * - In-order frame → deliver immediately + flush any buffered followers
461
+ * - Out-of-order frame → buffer until gap fills
462
+ * - Duplicate → drop
463
+ * - Beyond window → drop
464
+ */
465
+ push(frame: FlowFrame): FlowFrame[];
466
+ /**
467
+ * Get the sequence numbers that are missing (gaps) for a stream.
468
+ * Used by the reliability layer to request retransmission.
469
+ */
470
+ getMissingSequences(streamId: number): number[];
471
+ /**
472
+ * Clean up a stream's reassembly state.
473
+ * Call when a stream is closed or vented.
474
+ */
475
+ closeStream(streamId: number): void;
476
+ /**
477
+ * Get current reassembly statistics.
478
+ */
479
+ getStats(): Readonly<ReassemblerStats>;
480
+ /**
481
+ * Reset all state.
482
+ */
483
+ reset(): void;
484
+ /**
485
+ * Deliver a frame and flush any consecutively-buffered followers.
486
+ */
487
+ private deliverAndFlush;
488
+ /**
489
+ * Evict the least-recently-active stream to make room.
490
+ */
491
+ private evictOldestStream;
492
+ }
493
+
494
+ /** Safe MTU for UDP datagrams (1500 Ethernet - 20 IP - 8 UDP) */
495
+ declare const UDP_MTU = 1472;
496
+ /** Fragment header size: [frame_id:u16][frag_index:u8][frag_total:u8] */
497
+ declare const FRAGMENT_HEADER_SIZE = 4;
498
+ /** Max payload per UDP datagram after fragment header */
499
+ declare const MAX_FRAGMENT_PAYLOAD: number;
500
+ /** ACK frame flag — not a real flow flag, internal to UDP transport */
501
+ declare const ACK_FLAG = 128;
502
+ interface UDPFlowTransportConfig {
503
+ /** Local bind address */
504
+ host: string;
505
+ /** Local bind port */
506
+ port: number;
507
+ /** Remote host (for client mode) */
508
+ remoteHost?: string;
509
+ /** Remote port (for client mode) */
510
+ remotePort?: number;
511
+ /** MTU override (default: 1472) */
512
+ mtu?: number;
513
+ /** Enable reliability (ACKs + retransmit). Default: true */
514
+ reliable?: boolean;
515
+ /** Reassembler config overrides */
516
+ reassembler?: {
517
+ maxBufferPerStream?: number;
518
+ maxStreams?: number;
519
+ maxGap?: number;
520
+ };
521
+ }
522
+ /**
523
+ * UDP-based FlowTransport implementation.
524
+ *
525
+ * Implements the FlowTransport interface over UDP datagrams with:
526
+ * - MTU-safe fragmentation/reassembly
527
+ * - Out-of-order frame reassembly (via FrameReassembler)
528
+ * - Optional reliability (ACK bitmaps + selective retransmit)
529
+ * - Simple AIMD congestion control
530
+ *
531
+ * The same AeonFlowProtocol instance works unchanged — it just sees
532
+ * frames arriving (possibly out of order, which the reassembler fixes).
533
+ */
534
+ declare class UDPFlowTransport implements FlowTransport {
535
+ private config;
536
+ private receiveHandler;
537
+ private closed;
538
+ private socket;
539
+ private reassembler;
540
+ private fragmentGroups;
541
+ private nextFrameId;
542
+ private inflight;
543
+ private receivedPerStream;
544
+ private ackTimer;
545
+ private retransmitTimer;
546
+ private cwnd;
547
+ private inflightCount;
548
+ private codec;
549
+ constructor(config: UDPFlowTransportConfig);
550
+ /**
551
+ * Bind and start the UDP transport.
552
+ *
553
+ * In server mode (no remoteHost), listens for incoming datagrams.
554
+ * In client mode, binds and sets the remote endpoint.
555
+ */
556
+ bind(): Promise<void>;
557
+ send(data: Uint8Array): void;
558
+ onReceive(handler: (data: Uint8Array) => void): void;
559
+ close(): void;
560
+ /**
561
+ * Attempt to upgrade to WASM codec without delaying transport readiness.
562
+ */
563
+ private upgradeCodecInBackground;
564
+ /** Get reassembly statistics */
565
+ getReassemblerStats(): Readonly<ReassemblerStats>;
566
+ /** Current congestion window size */
567
+ get congestionWindow(): number;
568
+ /** Number of frames in flight (unacked) */
569
+ get framesInFlight(): number;
570
+ /**
571
+ * Handle an incoming UDP datagram.
572
+ *
573
+ * Datagram format:
574
+ * [frame_id:u16][frag_index:u8][frag_total:u8][payload...]
575
+ */
576
+ private handleDatagram;
577
+ /**
578
+ * Handle a fragment of a multi-datagram flow frame.
579
+ */
580
+ private handleFragment;
581
+ /**
582
+ * Handle a complete (reassembled) flow frame.
583
+ * This is where we do out-of-order reassembly using the stream_id + sequence.
584
+ */
585
+ private handleReassembledFrame;
586
+ /**
587
+ * Wrap a flow frame chunk in a fragment header.
588
+ */
589
+ private wrapFragment;
590
+ /**
591
+ * Send a UDP datagram to the remote endpoint.
592
+ */
593
+ private sendDatagram;
594
+ /**
595
+ * Track a sent frame for potential retransmission.
596
+ */
597
+ private trackInflight;
598
+ /**
599
+ * Handle an incoming ACK frame.
600
+ *
601
+ * ACK payload format:
602
+ * [stream_id:u16][base_seq:u32][bitmap_hi:u32][bitmap_lo:u32]
603
+ * (can repeat for multiple streams)
604
+ */
605
+ private handleAck;
606
+ /**
607
+ * Send ACK bitmaps for all received sequences.
608
+ */
609
+ private sendAcks;
610
+ /**
611
+ * Retransmit frames that haven't been ACKed.
612
+ */
613
+ private retransmitLost;
614
+ }
615
+ /**
616
+ * WebTransport-based FlowTransport for browsers.
617
+ *
618
+ * WebTransport (HTTP/3) provides unreliable datagrams — essentially UDP
619
+ * from the browser. This adapter wraps WebTransport's datagram API with
620
+ * the same fragmentation and reassembly used by UDPFlowTransport.
621
+ *
622
+ * Usage:
623
+ * const transport = await WebTransportFlowTransport.connect(
624
+ * 'https://site.example.com/.aeon/udp'
625
+ * );
626
+ * const protocol = new AeonFlowProtocol(transport, { role: 'client' });
627
+ */
628
+ declare class WebTransportFlowTransport implements FlowTransport {
629
+ private wt;
630
+ private writer;
631
+ private receiveHandler;
632
+ private closed;
633
+ private reassembler;
634
+ private fragmentGroups;
635
+ private nextFrameId;
636
+ private codec;
637
+ private constructor();
638
+ /**
639
+ * Connect to a WebTransport endpoint and return a FlowTransport.
640
+ */
641
+ static connect(url: string): Promise<WebTransportFlowTransport>;
642
+ send(data: Uint8Array): void;
643
+ onReceive(handler: (data: Uint8Array) => void): void;
644
+ close(): void;
645
+ private readLoop;
646
+ /**
647
+ * Attempt to upgrade to WASM codec without delaying transport startup.
648
+ */
649
+ private upgradeCodecInBackground;
650
+ }
651
+
652
+ /**
653
+ * TopologyAnalyzer — Compute Betti numbers and topological deficit for DAGs
654
+ *
655
+ * Given a computation graph (nodes + edges), computes:
656
+ * β₀ = connected components (independent computations)
657
+ * β₁ = independent cycles / parallel paths (parallelism)
658
+ * β₂ = voids (unreachable states)
659
+ *
660
+ * Then compares actual β₁ to the problem's intrinsic β₁* to produce
661
+ * the topological deficit Δβ — a quantitative measure of wasted parallelism.
662
+ *
663
+ * Zero dependencies. Works everywhere.
664
+ */
665
+ /** A node in the computation graph */
666
+ interface ComputationNode {
667
+ /** Unique identifier */
668
+ id: string;
669
+ /** Optional label for diagnostics */
670
+ label?: string;
671
+ /** Node type for structural analysis */
672
+ type?: 'source' | 'sink' | 'fork' | 'join' | 'process';
673
+ }
674
+ /** A directed edge in the computation graph */
675
+ interface ComputationEdge {
676
+ /** Source node ID */
677
+ from: string;
678
+ /** Target node ID */
679
+ to: string;
680
+ /** Optional label */
681
+ label?: string;
682
+ }
683
+ /** The computation graph to analyze */
684
+ interface ComputationGraph {
685
+ nodes: ComputationNode[];
686
+ edges: ComputationEdge[];
687
+ /** The problem's intrinsic Betti number — how parallel the problem COULD be */
688
+ intrinsicBeta1?: number;
689
+ }
690
+ /** Betti numbers of a computation graph */
691
+ interface BettiNumbers {
692
+ /** β₀: connected components (independent computations) */
693
+ beta0: number;
694
+ /** β₁: independent cycles (parallel paths through fork/join pairs) */
695
+ beta1: number;
696
+ /** β₂: voids (estimated from unreachable states in the DAG) */
697
+ beta2: number;
698
+ }
699
+ /** A detected fork/join pair in the graph */
700
+ interface ForkJoinPair {
701
+ /** The fork node (where paths diverge) */
702
+ forkNode: string;
703
+ /** The join node (where paths converge) */
704
+ joinNode: string;
705
+ /** Number of parallel paths between fork and join */
706
+ parallelPaths: number;
707
+ /** Contribution to β₁ (parallelPaths - 1) */
708
+ beta1Contribution: number;
709
+ }
710
+ /** Report on topological deficit */
711
+ interface DeficitReport {
712
+ /** The problem's intrinsic β₁* */
713
+ intrinsicBeta1: number;
714
+ /** The implementation's actual β₁ */
715
+ actualBeta1: number;
716
+ /** Δβ = β₁* - β₁ (0 = optimal, >0 = wasted parallelism). Measured in Bules. */
717
+ deficit: number;
718
+ /** Utilization ratio: β₁ / β₁* (1.0 = fully utilizing natural parallelism) */
719
+ utilization: number;
720
+ /** Human-readable assessment */
721
+ assessment: string;
722
+ }
723
+ /** Complete topology report */
724
+ interface TopologyReport {
725
+ /** Betti numbers */
726
+ betti: BettiNumbers;
727
+ /** Detected fork/join pairs */
728
+ forkJoinPairs: ForkJoinPair[];
729
+ /** Topological deficit (only if intrinsicBeta1 was provided) */
730
+ deficit?: DeficitReport;
731
+ /** Node count */
732
+ nodeCount: number;
733
+ /** Edge count */
734
+ edgeCount: number;
735
+ /** Is the graph a DAG? */
736
+ isDAG: boolean;
737
+ /** Pipeline Reynolds number estimate (stages / chunks) */
738
+ reynoldsEstimate?: number;
739
+ }
740
+ declare class TopologyAnalyzer {
741
+ /**
742
+ * Analyze a computation graph and produce a full topology report.
743
+ */
744
+ static analyze(graph: ComputationGraph): TopologyReport;
745
+ /**
746
+ * Quick deficit check — just the number, in Bules.
747
+ * Returns Δβ = intrinsicBeta1 - actualBeta1.
748
+ * 0 Bules = topology-matched. >0 Bules = wasted parallelism.
749
+ * Negative means the system has MORE parallelism than needed (over-forking).
750
+ */
751
+ static deficit(graph: ComputationGraph, intrinsicBeta1: number): number;
752
+ /**
753
+ * Build a computation graph from a fork/race/fold description.
754
+ * Convenience for common patterns.
755
+ */
756
+ static fromForkRaceFold(config: {
757
+ /** Number of forked paths */
758
+ forkWidth: number;
759
+ /** Number of pipeline stages per path */
760
+ stagesPerPath?: number;
761
+ /** The problem's intrinsic β₁* */
762
+ intrinsicBeta1?: number;
763
+ }): ComputationGraph;
764
+ /**
765
+ * Build a sequential pipeline graph (β₁ = 0).
766
+ * The degenerate case — Ford's assembly line.
767
+ */
768
+ static sequential(stages: number, intrinsicBeta1?: number): ComputationGraph;
769
+ }
770
+
771
+ /**
772
+ * TopologySampler — Runtime sampling of topological deficit
773
+ *
774
+ * Instruments a live system by recording fork/race/fold/vent events
775
+ * and periodically computing the topological deficit. Produces a
776
+ * time-series of Betti numbers and deficit measurements.
777
+ *
778
+ * Usage:
779
+ * const sampler = new TopologySampler({ intrinsicBeta1: 7 });
780
+ * sampler.fork('request-1', ['path-a', 'path-b', 'path-c']);
781
+ * sampler.race('request-1', 'path-a'); // path-a won
782
+ * sampler.vent('request-1', 'path-b');
783
+ * sampler.vent('request-1', 'path-c');
784
+ * sampler.fold('request-1');
785
+ * const report = sampler.report();
786
+ *
787
+ * Zero dependencies. Works everywhere.
788
+ */
789
+ interface SamplerConfig {
790
+ /** The problem's intrinsic β₁* */
791
+ intrinsicBeta1: number;
792
+ /** Maximum number of samples to retain (ring buffer). Default: 1000 */
793
+ maxSamples?: number;
794
+ }
795
+ /** A single point-in-time sample */
796
+ interface Sample {
797
+ /** Timestamp (ms since epoch) */
798
+ timestamp: number;
799
+ /** Number of active forks at this moment */
800
+ activeForks: number;
801
+ /** Total parallel paths across all active forks */
802
+ activeParallelPaths: number;
803
+ /** Instantaneous β₁ (sum of parallelPaths - 1 per active fork) */
804
+ beta1: number;
805
+ /** Instantaneous deficit: β₁* - β₁ */
806
+ deficit: number;
807
+ /** Instantaneous utilization: β₁ / β₁* */
808
+ utilization: number;
809
+ /** Cumulative forks emitted */
810
+ totalForks: number;
811
+ /** Cumulative folds completed */
812
+ totalFolds: number;
813
+ /** Cumulative vents */
814
+ totalVents: number;
815
+ /** Cumulative races won */
816
+ totalRaces: number;
817
+ }
818
+ /** Aggregate report over all samples */
819
+ interface SamplerReport {
820
+ /** Problem's intrinsic β₁* */
821
+ intrinsicBeta1: number;
822
+ /** Number of samples collected */
823
+ sampleCount: number;
824
+ /** Time-weighted average β₁ */
825
+ meanBeta1: number;
826
+ /** Peak β₁ observed */
827
+ peakBeta1: number;
828
+ /** Time-weighted average deficit */
829
+ meanDeficit: number;
830
+ /** Time-weighted average utilization (0–1) */
831
+ meanUtilization: number;
832
+ /** Peak utilization observed */
833
+ peakUtilization: number;
834
+ /** Total forks / folds / vents / races */
835
+ totals: {
836
+ forks: number;
837
+ folds: number;
838
+ vents: number;
839
+ races: number;
840
+ };
841
+ /** Vent ratio: vents / (vents + races). Higher = more exploration, lower = more exploitation */
842
+ ventRatio: number;
843
+ /** Thermodynamic efficiency estimate: races / (races + vents) ≈ W / (W + Q) */
844
+ efficiency: number;
845
+ /** Human-readable assessment */
846
+ assessment: string;
847
+ /** All retained samples (for plotting) */
848
+ samples: Sample[];
849
+ }
850
+ declare class TopologySampler {
851
+ private readonly config;
852
+ private readonly activeForks;
853
+ private readonly samples;
854
+ private totalForks;
855
+ private totalFolds;
856
+ private totalVents;
857
+ private totalRaces;
858
+ constructor(config: SamplerConfig);
859
+ /**
860
+ * Record a fork event: one computation splits into N parallel paths.
861
+ */
862
+ fork(id: string, paths: string[]): void;
863
+ /**
864
+ * Record a race result: one path won.
865
+ */
866
+ race(id: string, winnerPath: string): void;
867
+ /**
868
+ * Record a vent: a path was released (didn't win, errored, timed out).
869
+ */
870
+ vent(id: string, path: string): void;
871
+ /**
872
+ * Record a fold: computation merged to a single result.
873
+ */
874
+ fold(id: string): void;
875
+ /**
876
+ * Take a snapshot without recording an event (for periodic sampling).
877
+ */
878
+ sample(): Sample;
879
+ /**
880
+ * Get the current instantaneous deficit.
881
+ */
882
+ currentDeficit(): number;
883
+ /**
884
+ * Get the current instantaneous β₁.
885
+ */
886
+ currentBeta1(): number;
887
+ /**
888
+ * Generate the aggregate report.
889
+ */
890
+ report(): SamplerReport;
891
+ /**
892
+ * Reset all state.
893
+ */
894
+ reset(): void;
895
+ private recordSample;
896
+ }
897
+
898
+ interface WorthingtonWhipResult {
899
+ readonly shards: number;
900
+ readonly numerator: number;
901
+ readonly denominator: number;
902
+ readonly savingsFraction: number;
903
+ }
904
+ interface SpeculativeTreeResult {
905
+ readonly alpha: number;
906
+ readonly depth: number;
907
+ readonly expectedAccepted: number;
908
+ readonly denominator: number;
909
+ }
910
+ interface TurbulentIdleResult {
911
+ readonly stageCount: number;
912
+ readonly chunkCount: number;
913
+ readonly numerator: number;
914
+ readonly denominator: number;
915
+ readonly idleFraction: number;
916
+ }
917
+ interface FrontierFillResult {
918
+ readonly frontierByLayer: readonly number[];
919
+ readonly layerCount: number;
920
+ readonly frontierArea: number;
921
+ readonly peakFrontier: number;
922
+ readonly envelopeArea: number;
923
+ readonly frontierFill: number;
924
+ readonly wallaceNumber: number;
925
+ readonly wally: number;
926
+ readonly frontierDeficit: number;
927
+ }
928
+ interface PipelineOccupancyResult {
929
+ readonly stageCount: number;
930
+ readonly chunkCount: number;
931
+ readonly frontierArea: number;
932
+ readonly capacityArea: number;
933
+ readonly frontierFill: number;
934
+ readonly occupancyDeficit: number;
935
+ }
936
+ type PipelineRegime = 'laminar' | 'transitional' | 'turbulent';
937
+ type ParallelismAction = 'expand' | 'staggered-expand' | 'hold' | 'multiplex' | 'constrain';
938
+ interface AdaptiveParallelismPolicyResult {
939
+ readonly intrinsicBeta1: number;
940
+ readonly actualBeta1: number;
941
+ readonly topologyDeficit: number;
942
+ readonly stageCount: number;
943
+ readonly chunkCount: number;
944
+ readonly reynoldsEstimate: number;
945
+ readonly regime: PipelineRegime;
946
+ readonly frontierFill: number;
947
+ readonly occupancyDeficit: number;
948
+ readonly highOccupancyDeficit: boolean;
949
+ readonly action: ParallelismAction;
950
+ readonly rationale: string;
951
+ }
952
+ interface QuantumDeficitResult {
953
+ readonly sqrtN: number;
954
+ readonly searchSize: number;
955
+ readonly classicalDeficit: number;
956
+ readonly quantumDeficit: number;
957
+ readonly speedup: number;
958
+ }
959
+ interface ProtocolDeficitResult {
960
+ readonly streamCount: number;
961
+ readonly intrinsicBeta1: number;
962
+ readonly tcpDeficit: number;
963
+ readonly quicDeficit: number;
964
+ readonly flowDeficit: number;
965
+ }
966
+ interface SettlementDeficitResult {
967
+ readonly intrinsicBeta1: number;
968
+ readonly sequentialDeficit: number;
969
+ readonly parallelDeficit: number;
970
+ }
971
+ declare function worthingtonWhipSavings(shards: number): WorthingtonWhipResult;
972
+ declare function speculativeTreeExpectedAccepted(alpha: number, depth: number): SpeculativeTreeResult;
973
+ declare function turbulentIdleFraction(stageCount: number, chunkCount: number): TurbulentIdleResult;
974
+ declare function frontierFill(frontierByLayer: readonly number[]): FrontierFillResult;
975
+ declare function pipelineOccupancy(stageCount: number, chunkCount: number): PipelineOccupancyResult;
976
+ declare function classifyPipelineRegime(stageCount: number, chunkCount: number): PipelineRegime;
977
+ declare function adaptiveParallelismPolicy(config: {
978
+ intrinsicBeta1: number;
979
+ actualBeta1: number;
980
+ stageCount: number;
981
+ chunkCount: number;
982
+ }): AdaptiveParallelismPolicyResult;
983
+ declare function quantumDeficitIdentity(sqrtN: number): QuantumDeficitResult;
984
+ declare function protocolDeficits(streamCount: number): ProtocolDeficitResult;
985
+ declare function settlementDeficits(): SettlementDeficitResult;
986
+ declare function beta2FromBandGap(forbiddenEnergyCount: number): number;
987
+ declare function firstLawConserved(forkEnergy: number, foldWork: number, ventEnergy: number, tolerance?: number): boolean;
988
+
989
+ type GnosisImpossibleSystemId = 'edge-pipeline-parallelism' | 'audio-token-privacy' | 'crdt-split-brain-prevention' | 'webgpu-graph-flattening';
990
+ interface GnosisImpossibleSystemTopology {
991
+ readonly id: GnosisImpossibleSystemId;
992
+ readonly title: string;
993
+ readonly aeonSurface: 'flow' | 'topology' | 'federation';
994
+ readonly gnosisExamplePath: string;
995
+ readonly gnosisTestPath: string;
996
+ readonly summary: string;
997
+ readonly invariants: readonly string[];
998
+ }
999
+ declare const GNOSIS_IMPOSSIBLE_SYSTEM_TOPOLOGIES: readonly [{
1000
+ readonly id: "edge-pipeline-parallelism";
1001
+ readonly title: "Edge Pipeline Parallelism";
1002
+ readonly aeonSurface: "federation";
1003
+ readonly gnosisExamplePath: "open-source/gnosis/examples/edge-pipeline-parallelism.gg";
1004
+ readonly gnosisTestPath: "open-source/gnosis/examples/impossible-systems.test.gg";
1005
+ readonly summary: "Models a 13B request folding across layer-sharded workers that relay quantized hidden state and race a warm standby for failover.";
1006
+ readonly invariants: readonly ["no single worker shard exceeds its annotated capacity", "the request still reaches a folded response under warm-standby failover"];
1007
+ }, {
1008
+ readonly id: "audio-token-privacy";
1009
+ readonly title: "Audio Token Privacy";
1010
+ readonly aeonSurface: "flow";
1011
+ readonly gnosisExamplePath: "open-source/gnosis/examples/audio-token-privacy.gg";
1012
+ readonly gnosisTestPath: "open-source/gnosis/examples/impossible-systems.test.gg";
1013
+ readonly summary: "Models semantic, prosodic, and biometric token lanes, injecting noise into identity-bearing RVQ layers before anything is folded into the public mesh.";
1014
+ readonly invariants: readonly ["identity-bearing layers are noised before the public fold", "semantic and prosodic lanes remain part of the folded output"];
1015
+ }, {
1016
+ readonly id: "crdt-split-brain-prevention";
1017
+ readonly title: "CRDT Split-Brain Prevention";
1018
+ readonly aeonSurface: "topology";
1019
+ readonly gnosisExamplePath: "open-source/gnosis/examples/crdt-split-brain-prevention.gg";
1020
+ readonly gnosisTestPath: "open-source/gnosis/examples/impossible-systems.test.gg";
1021
+ readonly summary: "Models geographically separated replicas, nonce-scoped replay guards, and deterministic CRDT observation collapsing to one canonical state.";
1022
+ readonly invariants: readonly ["replica writes carry distinct nonce identities", "deterministic CRDT observation collapses to one canonical state"];
1023
+ }, {
1024
+ readonly id: "webgpu-graph-flattening";
1025
+ readonly title: "WebGPU Graph Flattening";
1026
+ readonly aeonSurface: "topology";
1027
+ readonly gnosisExamplePath: "open-source/gnosis/examples/webgpu-graph-flattening.gg";
1028
+ readonly gnosisTestPath: "open-source/gnosis/examples/impossible-systems.test.gg";
1029
+ readonly summary: "Models flattening a pointer-chasing object graph into a contiguous Float32Array path that races a scattered CPU walk.";
1030
+ readonly invariants: readonly ["the flattened buffer is contiguous Float32Array state", "the packed GPU path is explicit in the topology and races the scattered walk"];
1031
+ }];
1032
+ declare function getGnosisImpossibleSystemTopology(id: GnosisImpossibleSystemId): GnosisImpossibleSystemTopology | undefined;
1033
+
1034
+ /**
1035
+ * DashRelay Flow Transport
1036
+ *
1037
+ * FlowTransport adapter for DashRelay WebSocket relay.
1038
+ * THE backbone transport — all Aeon data flows through DashRelay.
1039
+ *
1040
+ * DashRelay provides:
1041
+ * - Room-based pub/sub (peers join rooms by name)
1042
+ * - Binary broadcast to all peers in a room
1043
+ * - Peer discovery (join/leave events)
1044
+ * - Auth via API key or UCAN token
1045
+ * - Automatic reconnection with exponential backoff
1046
+ *
1047
+ * This transport wraps DashRelay's broadcast/message system as a
1048
+ * FlowTransport interface, enabling flow protocol (fork/race/fold)
1049
+ * over the relay mesh. Every app in the stack — forge sites, shell,
1050
+ * inference, presence, CRDT sync — speaks Aeon flow protocol over
1051
+ * DashRelay internally. HTTP is just the normie projection.
1052
+ *
1053
+ * Two modes:
1054
+ * 1. **Room broadcast**: All peers in the room receive all flow frames.
1055
+ * Good for mesh networking, federated inference, presence.
1056
+ * 2. **Directed**: Flow frames include a target peer ID header.
1057
+ * Good for point-to-point within a room (shell ↔ specific forge site).
1058
+ *
1059
+ * The transport is DashRelay-client agnostic — it takes a minimal
1060
+ * interface so it works with any DashRelay client implementation.
1061
+ */
1062
+
1063
+ /**
1064
+ * Minimal DashRelay client interface.
1065
+ * Works with @dashrelay/client or any compatible implementation.
1066
+ */
1067
+ interface DashRelayLike {
1068
+ /** Broadcast binary data to all peers in the room */
1069
+ broadcast(payload: Uint8Array): void;
1070
+ /** Register handler for incoming messages */
1071
+ on(event: 'message', handler: (senderId: string, payload: Uint8Array) => void): void;
1072
+ /** Unregister handler */
1073
+ off(event: 'message', handler: (senderId: string, payload: Uint8Array) => void): void;
1074
+ /** Peer events */
1075
+ on(event: 'peerJoined', handler: (peerId: string) => void): void;
1076
+ on(event: 'peerLeft', handler: (peerId: string) => void): void;
1077
+ off(event: 'peerJoined', handler: (peerId: string) => void): void;
1078
+ off(event: 'peerLeft', handler: (peerId: string) => void): void;
1079
+ /** Connection events */
1080
+ on(event: 'connected', handler: () => void): void;
1081
+ on(event: 'disconnected', handler: () => void): void;
1082
+ off(event: 'connected', handler: () => void): void;
1083
+ off(event: 'disconnected', handler: () => void): void;
1084
+ }
1085
+ interface DashRelayFlowConfig {
1086
+ /** Target specific peer (directed mode) or broadcast to all (default) */
1087
+ targetPeerId?: string;
1088
+ /** This peer's ID (for filtering own messages) */
1089
+ localPeerId?: string;
1090
+ /** Channel tag for multiplexing multiple flow protocols in one room */
1091
+ channel?: string;
1092
+ }
1093
+ /**
1094
+ * FlowTransport over DashRelay broadcast.
1095
+ *
1096
+ * All peers in a DashRelay room receive flow frames.
1097
+ * In directed mode, frames include a target peer ID and
1098
+ * non-target peers ignore them.
1099
+ *
1100
+ * This is the primary transport for the Aeon stack.
1101
+ * Everything talks Aeon internally over DashRelay.
1102
+ */
1103
+ declare class DashRelayFlowTransport implements FlowTransport {
1104
+ private relay;
1105
+ private receiveHandler;
1106
+ private closed;
1107
+ private config;
1108
+ private peerHandler;
1109
+ /** Connected peers observed via relay events */
1110
+ private peers;
1111
+ private peerJoinHandler;
1112
+ private peerLeaveHandler;
1113
+ /** Optional handlers for peer lifecycle events */
1114
+ onPeerJoin: ((peerId: string) => void) | null;
1115
+ onPeerLeave: ((peerId: string) => void) | null;
1116
+ constructor(relay: DashRelayLike, config?: DashRelayFlowConfig);
1117
+ send(data: Uint8Array): void;
1118
+ onReceive(handler: (data: Uint8Array) => void): void;
1119
+ close(): void;
1120
+ /** Get all known peers in the room */
1121
+ getPeers(): string[];
1122
+ /** Number of peers in the room */
1123
+ get peerCount(): number;
1124
+ /** Whether the transport is still open */
1125
+ get isOpen(): boolean;
1126
+ /** Send to a specific peer (overrides config.targetPeerId for this call) */
1127
+ sendTo(peerId: string, data: Uint8Array): void;
1128
+ }
1129
+ /**
1130
+ * Create a FlowTransport connected to a DashRelay room.
1131
+ *
1132
+ * This is the standard way to establish Aeon flow protocol
1133
+ * over the relay mesh. Use channels to multiplex different
1134
+ * flow protocols within the same room.
1135
+ *
1136
+ * @param relay - Connected DashRelay client instance
1137
+ * @param channel - Optional channel tag for multiplexing
1138
+ * @param config - Optional transport configuration
1139
+ */
1140
+ declare function createDashRelayFlow(relay: DashRelayLike, channel?: string, config?: Omit<DashRelayFlowConfig, 'channel'>): DashRelayFlowTransport;
1141
+
1142
+ /**
1143
+ * Bluetooth Flow Transport
1144
+ *
1145
+ * FlowTransport adapter for Web Bluetooth API.
1146
+ * Enables flow protocol over BLE between nearby devices —
1147
+ * the mesh networking primitive for federated inference.
1148
+ *
1149
+ * Two devices running aeon-flux can fork/race inference across
1150
+ * both browsers via Bluetooth, zero cloud cost.
1151
+ *
1152
+ * Uses GATT characteristics for binary frame exchange:
1153
+ * - TX characteristic: this device writes flow frames
1154
+ * - RX characteristic: this device reads flow frames
1155
+ *
1156
+ * MTU-aware: fragments large FlowFrames across multiple BLE writes.
1157
+ */
1158
+
1159
+ declare global {
1160
+ interface BluetoothLEScanFilter {
1161
+ services?: BluetoothServiceUUID[];
1162
+ name?: string;
1163
+ namePrefix?: string;
1164
+ }
1165
+ type BluetoothServiceUUID = string | number;
1166
+ interface BluetoothDevice extends EventTarget {
1167
+ readonly id: string;
1168
+ readonly name?: string;
1169
+ readonly gatt?: BluetoothRemoteGATTServer;
1170
+ }
1171
+ interface BluetoothRemoteGATTServer {
1172
+ readonly connected: boolean;
1173
+ readonly device: BluetoothDevice;
1174
+ connect(): Promise<BluetoothRemoteGATTServer>;
1175
+ disconnect(): void;
1176
+ getPrimaryService(service: BluetoothServiceUUID): Promise<BluetoothRemoteGATTService>;
1177
+ }
1178
+ interface BluetoothRemoteGATTService {
1179
+ readonly device: BluetoothDevice;
1180
+ readonly uuid: string;
1181
+ getCharacteristic(characteristic: string): Promise<BluetoothRemoteGATTCharacteristic>;
1182
+ }
1183
+ interface BluetoothRemoteGATTCharacteristic extends EventTarget {
1184
+ readonly service: BluetoothRemoteGATTService;
1185
+ readonly uuid: string;
1186
+ readonly value: DataView | null;
1187
+ writeValueWithoutResponse(value: BufferSource): Promise<void>;
1188
+ startNotifications(): Promise<BluetoothRemoteGATTCharacteristic>;
1189
+ stopNotifications(): Promise<BluetoothRemoteGATTCharacteristic>;
1190
+ }
1191
+ interface RequestDeviceOptions {
1192
+ filters?: BluetoothLEScanFilter[];
1193
+ optionalServices?: BluetoothServiceUUID[];
1194
+ acceptAllDevices?: boolean;
1195
+ }
1196
+ interface Bluetooth {
1197
+ requestDevice(options: RequestDeviceOptions): Promise<BluetoothDevice>;
1198
+ }
1199
+ interface Navigator {
1200
+ bluetooth: Bluetooth;
1201
+ }
1202
+ }
1203
+ /** Aeon Flow BLE Service UUID */
1204
+ declare const AEON_FLOW_SERVICE_UUID = "0000af10-0000-1000-8000-00805f9b34fb";
1205
+ /** TX Characteristic — write flow frames */
1206
+ declare const AEON_FLOW_TX_UUID = "0000af11-0000-1000-8000-00805f9b34fb";
1207
+ /** RX Characteristic — receive flow frames (notify) */
1208
+ declare const AEON_FLOW_RX_UUID = "0000af12-0000-1000-8000-00805f9b34fb";
1209
+ interface BluetoothFlowConfig {
1210
+ /** BLE MTU (default: 509, negotiated at connection time) */
1211
+ mtu?: number;
1212
+ /** Service UUID override */
1213
+ serviceUuid?: string;
1214
+ /** Optional name filter for device discovery */
1215
+ namePrefix?: string;
1216
+ }
1217
+ /**
1218
+ * FlowTransport over Web Bluetooth GATT.
1219
+ *
1220
+ * Fragments flow frames to fit within BLE MTU, reassembles on receive.
1221
+ * Uses notifications on RX characteristic for incoming frames.
1222
+ */
1223
+ declare class BluetoothFlowTransport implements FlowTransport {
1224
+ private config;
1225
+ private device;
1226
+ private txChar;
1227
+ private rxChar;
1228
+ private receiveHandler;
1229
+ private mtu;
1230
+ private closed;
1231
+ /** Reassembly buffer for fragmented incoming frames */
1232
+ private rxBuffer;
1233
+ constructor(config?: BluetoothFlowConfig);
1234
+ /**
1235
+ * Scan for and connect to a nearby Aeon device.
1236
+ * Returns the connected device name.
1237
+ */
1238
+ connect(): Promise<string>;
1239
+ /**
1240
+ * Create from an already-connected GATT server (for peripheral/server mode).
1241
+ */
1242
+ static fromCharacteristics(tx: BluetoothRemoteGATTCharacteristic, rx: BluetoothRemoteGATTCharacteristic, config?: BluetoothFlowConfig): BluetoothFlowTransport;
1243
+ send(data: Uint8Array): void;
1244
+ onReceive(handler: (data: Uint8Array) => void): void;
1245
+ close(): void;
1246
+ /** Whether Bluetooth is connected */
1247
+ get isConnected(): boolean;
1248
+ private writeCharacteristic;
1249
+ private handleRxNotification;
1250
+ private endsWithBoundary;
1251
+ }
1252
+
1253
+ /**
1254
+ * WebRTC Flow Transport
1255
+ *
1256
+ * FlowTransport adapter for WebRTC DataChannel.
1257
+ * Enables flow protocol between browsers via DashRelay signaling —
1258
+ * the foundation for federated browser inference.
1259
+ *
1260
+ * Two devices open a DataChannel via DashRelay as the signaling layer,
1261
+ * then speak flow protocol directly peer-to-peer. The fork/race/fold
1262
+ * primitives work across the mesh — inference forked to N peers,
1263
+ * fastest result wins.
1264
+ *
1265
+ * Binary-mode DataChannel: no base64, no JSON wrapping.
1266
+ */
1267
+
1268
+ interface WebRTCFlowConfig {
1269
+ /** DashRelay signaling URL (default: wss://relay.dashrelay.com) */
1270
+ signalingUrl?: string;
1271
+ /** Room ID for peer discovery */
1272
+ roomId: string;
1273
+ /** This peer's ID */
1274
+ peerId?: string;
1275
+ /** ICE servers (default: Google STUN) */
1276
+ iceServers?: RTCIceServer[];
1277
+ /** DataChannel label */
1278
+ channelLabel?: string;
1279
+ /** Max buffered amount before backpressure (default: 16MB) */
1280
+ maxBufferedAmount?: number;
1281
+ }
1282
+ interface SignalingMessage {
1283
+ type: 'offer' | 'answer' | 'ice-candidate';
1284
+ from: string;
1285
+ to: string;
1286
+ payload: RTCSessionDescriptionInit | RTCIceCandidateInit;
1287
+ }
1288
+ /**
1289
+ * FlowTransport over WebRTC DataChannel.
1290
+ *
1291
+ * Uses DashRelay WebSocket for signaling (offer/answer/ICE exchange),
1292
+ * then establishes a direct peer-to-peer DataChannel for binary
1293
+ * flow frame exchange.
1294
+ */
1295
+ declare class WebRTCFlowTransport implements FlowTransport {
1296
+ private pc;
1297
+ private dc;
1298
+ private signalingWs;
1299
+ private receiveHandler;
1300
+ private closed;
1301
+ private peerId;
1302
+ private config;
1303
+ private maxBufferedAmount;
1304
+ constructor(config: WebRTCFlowConfig);
1305
+ /**
1306
+ * Initialize as the offering peer (initiator).
1307
+ * Connects to signaling, creates offer, waits for answer.
1308
+ */
1309
+ offer(): Promise<void>;
1310
+ /**
1311
+ * Initialize as the answering peer (responder).
1312
+ * Waits for an offer, creates answer.
1313
+ */
1314
+ answer(): Promise<void>;
1315
+ /**
1316
+ * Wait until the DataChannel is open and ready.
1317
+ */
1318
+ waitForOpen(): Promise<void>;
1319
+ send(data: Uint8Array): void;
1320
+ onReceive(handler: (data: Uint8Array) => void): void;
1321
+ close(): void;
1322
+ /** Whether the DataChannel is open */
1323
+ get isOpen(): boolean;
1324
+ /** Get this peer's ID */
1325
+ get id(): string;
1326
+ private wireDataChannel;
1327
+ private connectSignaling;
1328
+ private sendSignaling;
1329
+ }
1330
+ /**
1331
+ * Create a flow protocol connection between two peers via WebRTC.
1332
+ *
1333
+ * Uses DashRelay for signaling, then establishes a direct P2P
1334
+ * DataChannel for binary flow frame exchange.
1335
+ *
1336
+ * @param roomId - Shared room ID for peer discovery
1337
+ * @param role - 'initiator' creates the offer, 'responder' waits
1338
+ */
1339
+ declare function createP2PFlow(roomId: string, role: 'initiator' | 'responder', config?: Partial<WebRTCFlowConfig>): Promise<WebRTCFlowTransport>;
1340
+
1341
+ /**
1342
+ * TCP Flow Transport
1343
+ *
1344
+ * FlowTransport adapter for Node/Bun TCP sockets.
1345
+ * Enables flow protocol between server processes —
1346
+ * coordinator ↔ layer nodes, forge ↔ deploy targets.
1347
+ *
1348
+ * Uses length-prefixed framing over raw TCP to delineate
1349
+ * flow frame boundaries. Each message is:
1350
+ * [u32 length][payload bytes]
1351
+ *
1352
+ * This is the backbone transport for server-to-server
1353
+ * Aeon protocol communication.
1354
+ */
1355
+
1356
+ interface TCPFlowConfig {
1357
+ /** Host to connect to (client) or bind to (server) */
1358
+ host?: string;
1359
+ /** Port number */
1360
+ port: number;
1361
+ /** Connection timeout in ms (default: 10000) */
1362
+ connectTimeout?: number;
1363
+ /** Keep-alive interval in ms (default: 30000) */
1364
+ keepAliveMs?: number;
1365
+ }
1366
+ /** Minimal TCP socket interface — works with Node net.Socket and Bun */
1367
+ interface TCPSocket {
1368
+ write(data: Uint8Array): boolean;
1369
+ on(event: 'data', handler: (data: Buffer | Uint8Array) => void): void;
1370
+ on(event: 'close', handler: () => void): void;
1371
+ on(event: 'error', handler: (err: Error) => void): void;
1372
+ end(): void;
1373
+ destroy(): void;
1374
+ setKeepAlive?(enable: boolean, initialDelay?: number): void;
1375
+ setNoDelay?(noDelay?: boolean): void;
1376
+ }
1377
+ /**
1378
+ * FlowTransport over TCP with length-prefixed framing.
1379
+ *
1380
+ * Handles message boundary detection (TCP is a stream, not message-oriented).
1381
+ * Uses a u32 length prefix so the receiver knows exactly how many bytes
1382
+ * to read for each flow frame.
1383
+ */
1384
+ declare class TCPFlowTransport implements FlowTransport {
1385
+ private socket;
1386
+ private receiveHandler;
1387
+ private closed;
1388
+ /** Reassembly buffer for TCP stream → discrete messages */
1389
+ private rxBuffer;
1390
+ constructor(socket: TCPSocket, config?: Partial<TCPFlowConfig>);
1391
+ send(data: Uint8Array): void;
1392
+ onReceive(handler: (data: Uint8Array) => void): void;
1393
+ close(): void;
1394
+ /** Whether the transport is still open */
1395
+ get isOpen(): boolean;
1396
+ private onData;
1397
+ }
1398
+ /**
1399
+ * Create a TCP FlowTransport by connecting to a remote host.
1400
+ *
1401
+ * Uses dynamic import of 'net' so this module is tree-shakeable
1402
+ * in browser builds.
1403
+ *
1404
+ * @param host - Remote host
1405
+ * @param port - Remote port
1406
+ * @param config - Optional TCP configuration
1407
+ */
1408
+ declare function connectTCPFlow(host: string, port: number, config?: Partial<TCPFlowConfig>): Promise<TCPFlowTransport>;
1409
+ /**
1410
+ * Create a TCP flow server that accepts incoming connections.
1411
+ *
1412
+ * Each accepted connection becomes a FlowTransport.
1413
+ *
1414
+ * @param port - Port to listen on
1415
+ * @param host - Host to bind to (default: '0.0.0.0')
1416
+ * @param onConnection - Called for each new flow transport connection
1417
+ */
1418
+ declare function listenTCPFlow(port: number, host: string, onConnection: (transport: TCPFlowTransport) => void): Promise<{
1419
+ close: () => void;
1420
+ }>;
1421
+
1422
+ /**
1423
+ * IPC Flow Transport
1424
+ *
1425
+ * FlowTransport adapter for inter-process communication:
1426
+ * - MessagePort (Web Workers, SharedWorker, BroadcastChannel)
1427
+ * - MessageChannel (Node/Bun worker_threads)
1428
+ * - child_process IPC (Node fork)
1429
+ *
1430
+ * Enables flow protocol between:
1431
+ * - Main thread ↔ inference Web Worker (browser)
1432
+ * - Shell process ↔ forge daemon (local)
1433
+ * - Any two processes on the same machine
1434
+ *
1435
+ * Zero-copy when possible — transfers ArrayBuffers via
1436
+ * structured clone's transfer list.
1437
+ */
1438
+
1439
+ /**
1440
+ * Minimal MessagePort-like interface.
1441
+ * Covers Web Workers, worker_threads, BroadcastChannel.
1442
+ */
1443
+ interface MessagePortLike {
1444
+ postMessage(data: unknown, transfer?: Transferable[]): void;
1445
+ addEventListener?(type: 'message', handler: (event: MessageEvent) => void): void;
1446
+ removeEventListener?(type: 'message', handler: (event: MessageEvent) => void): void;
1447
+ onmessage?: ((event: MessageEvent) => void) | null;
1448
+ close?(): void;
1449
+ start?(): void;
1450
+ }
1451
+ /**
1452
+ * Minimal child_process-like interface for IPC.
1453
+ * Covers Node child_process.fork() results.
1454
+ */
1455
+ interface ChildProcessLike {
1456
+ send(data: unknown): boolean;
1457
+ on(event: 'message', handler: (data: unknown) => void): void;
1458
+ on(event: 'exit', handler: (code: number | null) => void): void;
1459
+ removeListener?(event: string, handler: (...args: unknown[]) => void): void;
1460
+ kill?(): void;
1461
+ }
1462
+ interface IPCFlowConfig {
1463
+ /** Whether to transfer ArrayBuffers (zero-copy but invalidates sender's ref) */
1464
+ transferBuffers?: boolean;
1465
+ }
1466
+ /**
1467
+ * FlowTransport over MessagePort (Web Workers, worker_threads, BroadcastChannel).
1468
+ *
1469
+ * Uses structured clone for binary transfer. When `transferBuffers` is true,
1470
+ * the ArrayBuffer backing the Uint8Array is transferred (zero-copy) rather
1471
+ * than cloned. This is faster but invalidates the sender's reference.
1472
+ */
1473
+ declare class MessagePortFlowTransport implements FlowTransport {
1474
+ private port;
1475
+ private receiveHandler;
1476
+ private closed;
1477
+ private transferBuffers;
1478
+ private messageHandler;
1479
+ constructor(port: MessagePortLike, config?: IPCFlowConfig);
1480
+ send(data: Uint8Array): void;
1481
+ onReceive(handler: (data: Uint8Array) => void): void;
1482
+ close(): void;
1483
+ /** Whether the transport is still open */
1484
+ get isOpen(): boolean;
1485
+ }
1486
+ /**
1487
+ * FlowTransport over Node child_process IPC.
1488
+ *
1489
+ * Uses process.send()/process.on('message') for fork()-based IPC.
1490
+ * Messages are serialized via V8's structured clone, so Uint8Array
1491
+ * arrives as a Buffer on the other side.
1492
+ */
1493
+ declare class ChildProcessFlowTransport implements FlowTransport {
1494
+ private process;
1495
+ private receiveHandler;
1496
+ private closed;
1497
+ private ipcHandler;
1498
+ constructor(childProcess: ChildProcessLike);
1499
+ send(data: Uint8Array): void;
1500
+ onReceive(handler: (data: Uint8Array) => void): void;
1501
+ close(): void;
1502
+ /** Whether the transport is still open */
1503
+ get isOpen(): boolean;
1504
+ }
1505
+ /**
1506
+ * Create a pair of linked MessagePort FlowTransports.
1507
+ *
1508
+ * Uses MessageChannel to create a bidirectional pair —
1509
+ * data sent on one arrives on the other.
1510
+ *
1511
+ * Works in browsers, Bun, and Node (with worker_threads).
1512
+ */
1513
+ declare function createIPCPair(config?: IPCFlowConfig): [MessagePortFlowTransport, MessagePortFlowTransport];
1514
+
1515
+ /**
1516
+ * USB Flow Transport
1517
+ *
1518
+ * FlowTransport adapter for WebUSB API.
1519
+ * Enables flow protocol between browser and USB devices —
1520
+ * the communication channel for Rabbit R1 and other
1521
+ * hardware endpoints.
1522
+ *
1523
+ * Uses bulk transfer endpoints for binary flow frame exchange.
1524
+ * Length-prefixed framing (u32) for message boundary detection
1525
+ * over the bulk pipe.
1526
+ *
1527
+ * The device must expose a vendor-specific interface with
1528
+ * IN and OUT bulk endpoints that speak Aeon flow frames.
1529
+ */
1530
+
1531
+ /** Aeon vendor-specific interface class */
1532
+ declare const AEON_USB_INTERFACE_CLASS = 255;
1533
+ /** Aeon vendor-specific subclass */
1534
+ declare const AEON_USB_SUBCLASS = 174;
1535
+ /** Aeon protocol ID within the interface */
1536
+ declare const AEON_USB_PROTOCOL = 1;
1537
+ interface USBFlowConfig {
1538
+ /** Interface number to claim (auto-detected if not specified) */
1539
+ interfaceNumber?: number;
1540
+ /** OUT endpoint number (auto-detected if not specified) */
1541
+ outEndpoint?: number;
1542
+ /** IN endpoint number (auto-detected if not specified) */
1543
+ inEndpoint?: number;
1544
+ /** Transfer size for bulk reads (default: 64KB) */
1545
+ transferSize?: number;
1546
+ /** USB vendor ID filter for device selection */
1547
+ vendorId?: number;
1548
+ /** USB product ID filter for device selection */
1549
+ productId?: number;
1550
+ }
1551
+ /**
1552
+ * FlowTransport over WebUSB bulk endpoints.
1553
+ *
1554
+ * Uses length-prefixed framing over bulk transfers to delineate
1555
+ * flow frame boundaries. Continuously polls the IN endpoint
1556
+ * for incoming data.
1557
+ */
1558
+ declare class USBFlowTransport implements FlowTransport {
1559
+ private device;
1560
+ private receiveHandler;
1561
+ private closed;
1562
+ private interfaceNum;
1563
+ private outEndpoint;
1564
+ private inEndpoint;
1565
+ private transferSize;
1566
+ private readLoopRunning;
1567
+ /** Reassembly buffer for length-prefixed framing */
1568
+ private rxBuffer;
1569
+ private constructor();
1570
+ /**
1571
+ * Connect to a USB device and create a FlowTransport.
1572
+ *
1573
+ * Requests device access, opens it, claims the Aeon interface,
1574
+ * and auto-detects bulk endpoints if not specified.
1575
+ */
1576
+ static connect(config?: USBFlowConfig): Promise<USBFlowTransport>;
1577
+ /**
1578
+ * Create from an already-opened USB device (for testing or manual setup).
1579
+ */
1580
+ static fromDevice(device: USBDevice, interfaceNum: number, outEndpoint: number, inEndpoint: number, config?: Partial<USBFlowConfig>): USBFlowTransport;
1581
+ send(data: Uint8Array): void;
1582
+ onReceive(handler: (data: Uint8Array) => void): void;
1583
+ close(): void;
1584
+ /** Whether the transport is still open */
1585
+ get isOpen(): boolean;
1586
+ /** Get the USB device info */
1587
+ get deviceInfo(): {
1588
+ vendorId: number;
1589
+ productId: number;
1590
+ name: string;
1591
+ };
1592
+ private startReadLoop;
1593
+ private processChunk;
1594
+ }
1595
+
1596
+ /**
1597
+ * HTTP Flow Transport (nginx Bridge)
1598
+ *
1599
+ * FlowTransport adapter that translates between HTTP and Aeon flow protocol.
1600
+ * This is the normie projection layer — external clients speak HTTP,
1601
+ * the nginx module translates to Aeon flow, and everything internal
1602
+ * speaks Aeon natively.
1603
+ *
1604
+ * Two sides:
1605
+ * 1. **Server-side (Aeon→HTTP)**: Receives flow frames from internal Aeon
1606
+ * services and translates them into HTTP responses for external clients.
1607
+ * 2. **Client-side (HTTP→Aeon)**: Receives HTTP requests from nginx and
1608
+ * translates them into flow frames for internal processing.
1609
+ *
1610
+ * The nginx module handles the C-level WebSocket↔HTTP translation.
1611
+ * This TypeScript module handles the flow frame↔HTTP semantic mapping:
1612
+ * - HTTP GET → flow stream open + await FIN
1613
+ * - HTTP POST → flow stream open + data frames + FIN
1614
+ * - HTTP response → flow frames + FIN
1615
+ * - HTTP streaming response → flow frames (no FIN until complete)
1616
+ * - HTTP error → VENT frame
1617
+ *
1618
+ * Wire format between nginx module and this bridge:
1619
+ * Control messages are length-prefixed JSON.
1620
+ * Data messages are raw flow frames.
1621
+ */
1622
+
1623
+ /** HTTP request as received from nginx */
1624
+ interface AeonHTTPRequest {
1625
+ /** HTTP method */
1626
+ method: string;
1627
+ /** Request path */
1628
+ path: string;
1629
+ /** Query string (without leading ?) */
1630
+ query?: string;
1631
+ /** Request headers */
1632
+ headers: Record<string, string>;
1633
+ /** Request body (for POST/PUT/PATCH) */
1634
+ body?: Uint8Array;
1635
+ /** Unique request ID assigned by nginx */
1636
+ requestId: string;
1637
+ }
1638
+ /** HTTP response to send back through nginx */
1639
+ interface AeonHTTPResponse {
1640
+ /** HTTP status code */
1641
+ status: number;
1642
+ /** Response headers */
1643
+ headers: Record<string, string>;
1644
+ /** Response body */
1645
+ body: Uint8Array;
1646
+ /** Whether this is a streaming response (more chunks follow) */
1647
+ streaming?: boolean;
1648
+ /** Request ID this response belongs to */
1649
+ requestId: string;
1650
+ }
1651
+ interface HTTPBridgeConfig {
1652
+ /** Default content type for responses (default: 'application/octet-stream') */
1653
+ defaultContentType?: string;
1654
+ /** Maximum request body size in bytes (default: 16MB) */
1655
+ maxBodySize?: number;
1656
+ /** Timeout for flow response in ms (default: 30000) */
1657
+ responseTimeout?: number;
1658
+ }
1659
+ /**
1660
+ * Encode an HTTP request into flow frame payload.
1661
+ *
1662
+ * Format:
1663
+ * [0-3] u32 method length
1664
+ * [4-7] u32 path length
1665
+ * [8-11] u32 headers JSON length
1666
+ * [12-15] u32 body length
1667
+ * [...] method bytes
1668
+ * [...] path bytes (includes query string)
1669
+ * [...] headers JSON bytes
1670
+ * [...] body bytes
1671
+ */
1672
+ declare function encodeHTTPRequest(req: AeonHTTPRequest): Uint8Array;
1673
+ /**
1674
+ * Decode a flow frame payload back into an HTTP request.
1675
+ */
1676
+ declare function decodeHTTPRequest(data: Uint8Array): AeonHTTPRequest;
1677
+ /**
1678
+ * Encode an HTTP response into flow frame payload.
1679
+ *
1680
+ * Format:
1681
+ * [0-1] u16 status code
1682
+ * [2-5] u32 headers JSON length
1683
+ * [6-9] u32 body length
1684
+ * [...] headers JSON bytes
1685
+ * [...] body bytes
1686
+ */
1687
+ declare function encodeHTTPResponse(res: Omit<AeonHTTPResponse, 'requestId'>): Uint8Array;
1688
+ /**
1689
+ * Decode a flow frame payload back into an HTTP response.
1690
+ */
1691
+ declare function decodeHTTPResponse(data: Uint8Array): Omit<AeonHTTPResponse, 'requestId'>;
1692
+ /**
1693
+ * Bidirectional HTTP↔Aeon flow protocol bridge.
1694
+ *
1695
+ * Sits between nginx (HTTP) and internal Aeon services (flow protocol).
1696
+ * Translates HTTP requests into flow streams and flow responses back
1697
+ * into HTTP responses.
1698
+ *
1699
+ * nginx module sends HTTP requests over a WebSocket to this bridge.
1700
+ * This bridge opens flow streams, forwards the request as flow frames,
1701
+ * collects the response frames, and sends the HTTP response back to nginx.
1702
+ */
1703
+ declare class HTTPAeonBridge {
1704
+ private transport;
1705
+ private config;
1706
+ /** Pending HTTP requests waiting for flow responses */
1707
+ private pending;
1708
+ /** Handler for incoming HTTP requests (from nginx side) */
1709
+ private requestHandler;
1710
+ constructor(transport: FlowTransport, config?: HTTPBridgeConfig);
1711
+ /**
1712
+ * Register a handler for incoming HTTP requests.
1713
+ * This is used on the Aeon side — the bridge receives HTTP requests
1714
+ * from nginx, translates them to flow, and calls this handler.
1715
+ */
1716
+ onRequest(handler: (req: AeonHTTPRequest) => Promise<AeonHTTPResponse>): void;
1717
+ /**
1718
+ * Send an HTTP request through the bridge (used by nginx side).
1719
+ * Translates the HTTP request into flow frames, waits for the
1720
+ * flow response, and returns it as an HTTP response.
1721
+ */
1722
+ sendRequest(req: AeonHTTPRequest): Promise<AeonHTTPResponse>;
1723
+ /**
1724
+ * Send an HTTP response back through the bridge (used by Aeon side).
1725
+ */
1726
+ sendResponse(res: AeonHTTPResponse): void;
1727
+ close(): void;
1728
+ private handleIncoming;
1729
+ private handleResponseFrame;
1730
+ private handleRequestFrame;
1731
+ }
1732
+
1733
+ /**
1734
+ * Federated Browser Inference
1735
+ *
1736
+ * Fork inference requests across N mesh peers via flow protocol,
1737
+ * race the results, winner provides the response. This turns
1738
+ * every browser tab with WASM inference into a federated compute node.
1739
+ *
1740
+ * The coordinator:
1741
+ * 1. Discovers peers via DashRelay room or Bluetooth/WebRTC mesh
1742
+ * 2. Forks a flow stream per peer for the same prompt
1743
+ * 3. Races all streams — fastest inference result wins
1744
+ * 4. Vents slower streams to free their resources
1745
+ * 5. Returns the winning result to the caller
1746
+ *
1747
+ * This is fork/race/fold at the network level —
1748
+ * the same primitive that handles ESI cache vs inference,
1749
+ * but applied across physical devices.
1750
+ *
1751
+ * Use cases:
1752
+ * - 3 phones in a room → fork prompt to all 3, fastest wins
1753
+ * - Laptop + tablet → laptop runs 7B, tablet runs 1B, race them
1754
+ * - Federated speculative decoding across device mesh
1755
+ */
1756
+
1757
+ interface FederatedPeer {
1758
+ /** Unique peer identifier */
1759
+ id: string;
1760
+ /** Flow transport to this peer */
1761
+ transport: FlowTransport;
1762
+ /** Peer's reported capabilities */
1763
+ capabilities: PeerCapabilities;
1764
+ /** Last seen timestamp */
1765
+ lastSeen: number;
1766
+ /** Whether peer is currently available for inference */
1767
+ available: boolean;
1768
+ }
1769
+ interface PeerCapabilities {
1770
+ /** Models available on this peer */
1771
+ models: string[];
1772
+ /** Acceleration type */
1773
+ acceleration: 'webgpu' | 'webnn' | 'wasm' | 'none';
1774
+ /** Estimated tokens/second */
1775
+ estimatedTps?: number;
1776
+ /** Available memory in MB */
1777
+ availableMemoryMB?: number;
1778
+ /** Whether peer is on battery */
1779
+ onBattery?: boolean;
1780
+ }
1781
+ interface FederatedInferenceRequest {
1782
+ /** Prompt text */
1783
+ prompt: string;
1784
+ /** Model preference (peers without this model are skipped) */
1785
+ model?: string;
1786
+ /** Maximum tokens to generate */
1787
+ maxTokens?: number;
1788
+ /** Temperature */
1789
+ temperature?: number;
1790
+ /** Whether to include all peer results or just the winner */
1791
+ collectAll?: boolean;
1792
+ }
1793
+ interface FederatedInferenceResult {
1794
+ /** The winning peer's ID */
1795
+ winnerId: string;
1796
+ /** Generated text */
1797
+ text: string;
1798
+ /** Time to first token (ms) */
1799
+ ttft: number;
1800
+ /** Total generation time (ms) */
1801
+ totalTime: number;
1802
+ /** Tokens per second achieved */
1803
+ tokensPerSecond: number;
1804
+ /** All peer results (if collectAll was true) */
1805
+ allResults?: Map<string, {
1806
+ text: string;
1807
+ time: number;
1808
+ }>;
1809
+ }
1810
+ interface FederatedInferenceConfig {
1811
+ /** Timeout for inference requests in ms (default: 60000) */
1812
+ timeout?: number;
1813
+ /** Minimum peers required to start federated inference (default: 1) */
1814
+ minPeers?: number;
1815
+ /** Maximum peers to fork to (default: 8) */
1816
+ maxPeers?: number;
1817
+ /** Whether to include local inference in the race (default: true) */
1818
+ includeLocal?: boolean;
1819
+ /** Local inference handler (if includeLocal is true) */
1820
+ localInference?: (prompt: string) => Promise<string>;
1821
+ }
1822
+ /**
1823
+ * Coordinates federated inference across a mesh of peers.
1824
+ *
1825
+ * Each peer runs its own WASM inference engine. The coordinator
1826
+ * forks the same prompt to multiple peers, races them, and returns
1827
+ * the fastest result.
1828
+ *
1829
+ * Uses AeonFlowProtocol for fork/race/fold:
1830
+ * - fork(root, N) creates N child streams, one per peer
1831
+ * - race(children) picks the first to complete
1832
+ * - Losers are automatically vented
1833
+ */
1834
+ declare class FederatedInferenceCoordinator {
1835
+ private peers;
1836
+ private config;
1837
+ private listeners;
1838
+ constructor(config?: FederatedInferenceConfig);
1839
+ /**
1840
+ * Register a peer with its flow transport.
1841
+ * The transport should already be connected.
1842
+ */
1843
+ addPeer(id: string, transport: FlowTransport, capabilities?: PeerCapabilities): void;
1844
+ /**
1845
+ * Remove a peer from the federation.
1846
+ */
1847
+ removePeer(id: string): void;
1848
+ /**
1849
+ * Get all available peers, optionally filtered by model support.
1850
+ */
1851
+ getAvailablePeers(model?: string): FederatedPeer[];
1852
+ /**
1853
+ * Run federated inference across available peers.
1854
+ *
1855
+ * Forks the prompt to N peers, races them, returns the fastest result.
1856
+ * This is the core fork/race primitive applied at the network level.
1857
+ */
1858
+ infer(request: FederatedInferenceRequest): Promise<FederatedInferenceResult>;
1859
+ /**
1860
+ * Create a handler for incoming inference requests.
1861
+ * Call this on the peer side to process requests from the coordinator.
1862
+ *
1863
+ * @param inferFn - The actual inference function on this peer
1864
+ * @returns A FlowTransport receive handler
1865
+ */
1866
+ static createPeerHandler(inferFn: (prompt: string, options?: {
1867
+ maxTokens?: number;
1868
+ temperature?: number;
1869
+ }) => Promise<string>): (data: Uint8Array) => void;
1870
+ /**
1871
+ * Set up a peer to respond to federated inference requests.
1872
+ *
1873
+ * @param transport - The FlowTransport connected to the coordinator
1874
+ * @param inferFn - The inference function to run
1875
+ * @param capabilities - This peer's capabilities to announce
1876
+ */
1877
+ static setupPeer(transport: FlowTransport, inferFn: (prompt: string, options?: {
1878
+ maxTokens?: number;
1879
+ temperature?: number;
1880
+ }) => Promise<string>, capabilities: PeerCapabilities): void;
1881
+ on(handler: (event: FederationEvent) => void): void;
1882
+ off(handler: (event: FederationEvent) => void): void;
1883
+ private emit;
1884
+ get peerCount(): number;
1885
+ get availablePeerCount(): number;
1886
+ destroy(): void;
1887
+ }
1888
+ type FederationEvent = {
1889
+ type: 'peer-added';
1890
+ peerId: string;
1891
+ } | {
1892
+ type: 'peer-removed';
1893
+ peerId: string;
1894
+ } | {
1895
+ type: 'peer-capabilities';
1896
+ peerId: string;
1897
+ capabilities: PeerCapabilities;
1898
+ } | {
1899
+ type: 'inference-start';
1900
+ peerCount: number;
1901
+ } | {
1902
+ type: 'inference-complete';
1903
+ winnerId: string;
1904
+ totalTime: number;
1905
+ } | {
1906
+ type: 'error';
1907
+ message: string;
1908
+ };
1909
+
1910
+ /**
1911
+ * Aeon - Distributed Synchronization & Versioning Library
1912
+ *
1913
+ * A comprehensive library for building distributed, collaborative applications
1914
+ * with real-time synchronization, schema versioning, and conflict resolution.
1915
+ *
1916
+ * @example
1917
+ * ```typescript
1918
+ * import { SyncCoordinator, SchemaVersionManager } from '@a0n/aeon';
1919
+ *
1920
+ * // Create a sync coordinator
1921
+ * const coordinator = new SyncCoordinator();
1922
+ *
1923
+ * // Register a node
1924
+ * coordinator.registerNode({
1925
+ * id: 'node-1',
1926
+ * address: 'localhost',
1927
+ * port: 3000,
1928
+ * status: 'online',
1929
+ * lastHeartbeat: new Date().toISOString(),
1930
+ * version: '1.0.0',
1931
+ * capabilities: ['sync', 'replicate'],
1932
+ * });
1933
+ *
1934
+ * // Create a sync session
1935
+ * const session = coordinator.createSyncSession('node-1', ['node-2', 'node-3']);
1936
+ * ```
1937
+ *
1938
+ * @packageDocumentation
1939
+ */
1940
+
1941
+ /**
1942
+ * STUBS for React components and hooks
1943
+ * These are normally provided by @a0n/aeon-flux-react but are
1944
+ * imported from @a0n/aeon in many legacy parts of edge-web-app.
1945
+ *
1946
+ * NOTE: Only stub things NOT exported by submodules above.
1947
+ * SchemaVersionManager, SyncCoordinator, getAdaptiveCompressionOptimizer,
1948
+ * and getAgentPresenceManager are real exports — do NOT shadow them here.
1949
+ */
1950
+ declare const Link: any;
1951
+ declare const useAeonPage: any;
1952
+
1953
+ export { ACK_FLAG, AEON_FLOW_RX_UUID, AEON_FLOW_SERVICE_UUID, AEON_FLOW_TX_UUID, AEON_USB_INTERFACE_CLASS, AEON_USB_PROTOCOL, AEON_USB_SUBCLASS, type AdaptiveParallelismPolicyResult, AeonFlowProtocol, type AeonHTTPRequest, type AeonHTTPResponse, type BettiNumbers, type BluetoothFlowConfig, BluetoothFlowTransport, ChildProcessFlowTransport, type ChildProcessLike, type ComputationEdge, type ComputationGraph, type ComputationNode, DEFAULT_FLOW_CONFIG, type DashRelayFlowConfig, DashRelayFlowTransport, type DashRelayLike, type DeficitReport, FIN, FOLD, FORK, FRAGMENT_HEADER_SIZE, type FederatedInferenceConfig, FederatedInferenceCoordinator, type FederatedInferenceRequest, type FederatedInferenceResult, type FederatedPeer, type FederationEvent, FlowCodec, type FlowFrame, type FlowProtocolConfig, type FlowProtocolEvents, type FlowStream, type FlowStreamState, type FlowTransport, type ForkJoinPair, FrameReassembler, type FrontierFillResult, GNOSIS_IMPOSSIBLE_SYSTEM_TOPOLOGIES, type GnosisImpossibleSystemId, type GnosisImpossibleSystemTopology, HEADER_SIZE, HTTPAeonBridge, type HTTPBridgeConfig, type IPCFlowConfig, Link, MAX_FRAGMENT_PAYLOAD, MAX_PAYLOAD_LENGTH, MessagePortFlowTransport, type MessagePortLike, POISON, type ParallelismAction, type PeerCapabilities, type PipelineOccupancyResult, type PipelineRegime, type ProtocolDeficitResult, type QuantumDeficitResult, RACE, type ReassemblerConfig, type ReassemblerStats, type Sample, type SamplerConfig, type SamplerReport, type SettlementDeficitResult, type SignalingMessage, type SpeculativeTreeResult, type TCPFlowConfig, TCPFlowTransport, TopologyAnalyzer, type TopologyReport, TopologySampler, type TurbulentIdleResult, UDPFlowTransport, type UDPFlowTransportConfig, UDP_MTU, type USBFlowConfig, USBFlowTransport, VENT, type WebRTCFlowConfig, WebRTCFlowTransport, WebTransportFlowTransport, type WorthingtonWhipResult, adaptiveParallelismPolicy, beta2FromBandGap, classifyPipelineRegime, connectTCPFlow, createDashRelayFlow, createIPCPair, createP2PFlow, decodeHTTPRequest, decodeHTTPResponse, encodeHTTPRequest, encodeHTTPResponse, firstLawConserved, frontierFill, getGnosisImpossibleSystemTopology, listenTCPFlow, pipelineOccupancy, protocolDeficits, quantumDeficitIdentity, settlementDeficits, speculativeTreeExpectedAccepted, turbulentIdleFraction, useAeonPage, worthingtonWhipSavings };