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.
- package/LICENSE +21 -0
- package/README.md +454 -0
- package/dist/ai/index.d.mts +123 -0
- package/dist/ai/index.d.ts +123 -0
- package/dist/ai/index.js +1141 -0
- package/dist/ai/index.mjs +173 -0
- package/dist/chunk-ZWEXRT33.mjs +2402 -0
- package/dist/coordinator-Df48t6yJ.d.mts +521 -0
- package/dist/coordinator-Df48t6yJ.d.ts +521 -0
- package/dist/index.d.mts +431 -0
- package/dist/index.d.ts +431 -0
- package/dist/index.js +2484 -0
- package/dist/index.mjs +118 -0
- package/package.json +82 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Harry Jiang
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
# adaptive-bitmask
|
|
2
|
+
|
|
3
|
+
**The Sub-10ms Shared Cognition Engine for Multi-Agent Systems.**
|
|
4
|
+
|
|
5
|
+
Achieve an **85x bandwidth reduction** (753 bytes -> exactly 24 bytes) for multi-agent coordination. Instead of shipping bloated JSON payloads between agents, `adaptive-bitmask` uses dynamically-pruned semantic bitmasks to achieve sub-10ms coordination latency.
|
|
6
|
+
|
|
7
|
+
**๐ Production-Ready v1.0.0-rc.1** - [93.3% production test pass rate](./PRODUCTION_ROADMAP.md) with sub-millisecond coordination for 1000+ agents.
|
|
8
|
+
|
|
9
|
+
**To view the paper: "Go to files" -> "Adaptive Protocol(5)"**
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install adaptive-bitmask
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## โจ Production Features
|
|
16
|
+
|
|
17
|
+
- **๐ Sub-10ms Coordination** - 0.08ms average latency, 1.26ms for 2000 agents
|
|
18
|
+
- **๐ฆ Zero Dependencies** - Core engine has no runtime dependencies
|
|
19
|
+
- **๐ก๏ธ Production Hardening** - Error handling, circuit breakers, graceful degradation
|
|
20
|
+
- **๐ Built-in Monitoring** - Health checks, metrics collection, structured logging
|
|
21
|
+
- **๐ Transport Layers** - WebSocket and HTTP with production features
|
|
22
|
+
- **๐ Enterprise Security** - Input validation, rate limiting, authentication hooks
|
|
23
|
+
|
|
24
|
+
## Quick Start (The "Instant Magic" Way)
|
|
25
|
+
|
|
26
|
+
With the high-level `SharedCognition` wrapper, you can coordinate a massive swarm in just 3 lines of code.
|
|
27
|
+
|
|
28
|
+
```typescript
|
|
29
|
+
import { SharedCognition } from 'adaptive-bitmask';
|
|
30
|
+
|
|
31
|
+
// 1. Initialize the engine (auto-manages schema, coordinator, and arbiter)
|
|
32
|
+
const cognition = new SharedCognition();
|
|
33
|
+
|
|
34
|
+
// 2. Feed it your agents' current observations
|
|
35
|
+
const { decision, activeFeatures, latencyMs } = cognition.processSwarmTick([
|
|
36
|
+
['price_up', 'volume_spike', 'momentum_strong'], // Agent 1
|
|
37
|
+
['price_up', 'breakout_detected'], // Agent 2
|
|
38
|
+
['volume_spike', 'EMERGENCY_halt'] // Agent 3
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
// 3. That's it.
|
|
42
|
+
console.log(`Swarm decided to ${decision} in ${latencyMs.toFixed(2)}ms`);
|
|
43
|
+
console.log(`Consensus features:`, activeFeatures);
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## ๐ Real-World Deployments
|
|
47
|
+
|
|
48
|
+
### High-Frequency Trading
|
|
49
|
+
```typescript
|
|
50
|
+
// 1000 trading bots coordinating in 0.66ms
|
|
51
|
+
const tradingCognition = new SharedCognition({
|
|
52
|
+
arbiter: { executeThreshold: 0.60, emergencyOverride: true }
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### IoT Sensor Networks
|
|
57
|
+
```typescript
|
|
58
|
+
// 200 sensors reaching consensus in 0.20ms
|
|
59
|
+
const iotCognition = new SharedCognition({
|
|
60
|
+
schema: { emergencyPrefix: 'EMERGENCY_' }
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Chat Moderation Systems
|
|
65
|
+
```typescript
|
|
66
|
+
// 150 moderation agents deciding in 0.07ms
|
|
67
|
+
const moderationCognition = new SharedCognition({
|
|
68
|
+
arbiter: { executeThreshold: 0.70 }
|
|
69
|
+
});
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## ๐ง Production Deployment
|
|
73
|
+
|
|
74
|
+
### Docker
|
|
75
|
+
```dockerfile
|
|
76
|
+
FROM node:20-alpine
|
|
77
|
+
WORKDIR /app
|
|
78
|
+
COPY . .
|
|
79
|
+
RUN npm ci --only=production
|
|
80
|
+
EXPOSE 8080 8081
|
|
81
|
+
CMD ["node", "dist/index.js"]
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### Kubernetes
|
|
85
|
+
```yaml
|
|
86
|
+
apiVersion: apps/v1
|
|
87
|
+
kind: Deployment
|
|
88
|
+
metadata:
|
|
89
|
+
name: adaptive-bitmask
|
|
90
|
+
spec:
|
|
91
|
+
replicas: 3
|
|
92
|
+
selector:
|
|
93
|
+
matchLabels:
|
|
94
|
+
app: adaptive-bitmask
|
|
95
|
+
template:
|
|
96
|
+
spec:
|
|
97
|
+
containers:
|
|
98
|
+
- name: adaptive-bitmask
|
|
99
|
+
image: adaptive-bitmask:latest
|
|
100
|
+
ports:
|
|
101
|
+
- containerPort: 8080 # WebSocket
|
|
102
|
+
- containerPort: 8081 # HTTP API
|
|
103
|
+
resources:
|
|
104
|
+
requests:
|
|
105
|
+
memory: "512Mi"
|
|
106
|
+
cpu: "250m"
|
|
107
|
+
limits:
|
|
108
|
+
memory: "1Gi"
|
|
109
|
+
cpu: "500m"
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Monitoring
|
|
113
|
+
```bash
|
|
114
|
+
# Health check
|
|
115
|
+
curl http://localhost:8081/api/health
|
|
116
|
+
|
|
117
|
+
# Metrics endpoint
|
|
118
|
+
curl http://localhost:8081/api/metrics
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## ๐ Performance Benchmarks
|
|
122
|
+
|
|
123
|
+
| Agent Count | Avg Latency | Max Latency | Memory Usage |
|
|
124
|
+
|-------------|-------------|-------------|--------------|
|
|
125
|
+
| 100 | 0.09ms | 0.75ms | ~50MB |
|
|
126
|
+
| 500 | 0.27ms | 2.05ms | ~120MB |
|
|
127
|
+
| 1000 | 0.66ms | 3.12ms | ~200MB |
|
|
128
|
+
| 2000 | 1.26ms | 5.84ms | ~350MB |
|
|
129
|
+
|
|
130
|
+
*All benchmarks run on M2 MacBook Pro with Node.js v20*
|
|
131
|
+
|
|
132
|
+
## ๐ ๏ธ Transport Layers
|
|
133
|
+
|
|
134
|
+
### WebSocket Transport
|
|
135
|
+
```typescript
|
|
136
|
+
import { createWebSocketTransport } from 'adaptive-bitmask';
|
|
137
|
+
|
|
138
|
+
const wsTransport = createWebSocketTransport({
|
|
139
|
+
port: 8080,
|
|
140
|
+
maxConnections: 1000,
|
|
141
|
+
enableCompression: true
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
// Real-time bidirectional coordination
|
|
145
|
+
wsTransport.on('message', ({ agentId, message }) => {
|
|
146
|
+
console.log(`Agent ${agentId}:`, message);
|
|
147
|
+
});
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### HTTP Transport
|
|
151
|
+
```typescript
|
|
152
|
+
import { createHttpTransport } from 'adaptive-bitmask';
|
|
153
|
+
|
|
154
|
+
const httpTransport = createHttpTransport({
|
|
155
|
+
port: 8081,
|
|
156
|
+
enableCors: true,
|
|
157
|
+
rateLimitPerMinute: 1000
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
// REST API for coordination
|
|
161
|
+
fetch('http://localhost:8081/api/coordinate', {
|
|
162
|
+
method: 'POST',
|
|
163
|
+
body: bitmaskMessage.toBytes()
|
|
164
|
+
});
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## ๐ Monitoring & Observability
|
|
168
|
+
|
|
169
|
+
### Health Checks
|
|
170
|
+
```json
|
|
171
|
+
{
|
|
172
|
+
"status": "HEALTHY",
|
|
173
|
+
"uptime": 3600000,
|
|
174
|
+
"version": "1.0.0-rc.1",
|
|
175
|
+
"metrics": {
|
|
176
|
+
"messagesProcessed": 1000000,
|
|
177
|
+
"memoryUsageMB": 256,
|
|
178
|
+
"avgLatencyUs": 85
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### Metrics Collection
|
|
184
|
+
```typescript
|
|
185
|
+
import { MetricsCollector, Logger } from 'adaptive-bitmask';
|
|
186
|
+
|
|
187
|
+
const metrics = new MetricsCollector();
|
|
188
|
+
const logger = Logger.getInstance();
|
|
189
|
+
|
|
190
|
+
// Automatic performance tracking
|
|
191
|
+
metrics.recordCoordinationLatency(85); // microseconds
|
|
192
|
+
logger.info('Coordination', 'Decision made', {
|
|
193
|
+
decision: 'EXECUTE',
|
|
194
|
+
agentCount: 1000
|
|
195
|
+
});
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
## ๐จ Error Handling & Recovery
|
|
199
|
+
|
|
200
|
+
```typescript
|
|
201
|
+
import {
|
|
202
|
+
ValidationError,
|
|
203
|
+
CircuitBreaker,
|
|
204
|
+
TimeoutManager,
|
|
205
|
+
RecoveryManager
|
|
206
|
+
} from 'adaptive-bitmask';
|
|
207
|
+
|
|
208
|
+
// Circuit breaker for resilience
|
|
209
|
+
const circuitBreaker = new CircuitBreaker(5); // 5 failures threshold
|
|
210
|
+
|
|
211
|
+
// Timeout protection
|
|
212
|
+
await TimeoutManager.withTimeout(
|
|
213
|
+
coordinationOperation(),
|
|
214
|
+
10000, // 10s timeout
|
|
215
|
+
'swarm-coordination'
|
|
216
|
+
);
|
|
217
|
+
|
|
218
|
+
// Retry with exponential backoff
|
|
219
|
+
await RecoveryManager.withRetry(
|
|
220
|
+
failingOperation,
|
|
221
|
+
3, // max retries
|
|
222
|
+
1000 // base delay
|
|
223
|
+
);
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
---
|
|
227
|
+
|
|
228
|
+
## Advanced Usage / Internal Engine
|
|
229
|
+
|
|
230
|
+
For hardcore engineers who want direct access to the raw mathematical primitives and binary serialization logic.
|
|
231
|
+
|
|
232
|
+
Based on the [Adaptive Bitmask Protocol paper](https://arxiv.org/abs/TODO) (Jiang, 2026):
|
|
233
|
+
|
|
234
|
+
```
|
|
235
|
+
Layer 0: SchemaManager โ Feature-to-bit mappings, frequency pruning
|
|
236
|
+
Layer 1: Worker Agents โ Encode observations as 64-bit bitmasks
|
|
237
|
+
Layer 2: Coordinator โ OR-aggregate, compute per-bit confidence
|
|
238
|
+
Layer 3: Arbiter โ Weighted scoring โ EXECUTE / SYNTHESIZE / REJECT
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
**24-byte wire format:**
|
|
242
|
+
| Offset | Type | Field |
|
|
243
|
+
|--------|------|-------|
|
|
244
|
+
| 0-7 | uint64 | Feature bitmask |
|
|
245
|
+
| 8-11 | uint32 | Agent ID |
|
|
246
|
+
| 12-19 | int64 | Timestamp (ms) |
|
|
247
|
+
| 20-23 | uint32 | Schema version |
|
|
248
|
+
|
|
249
|
+
## Key Features
|
|
250
|
+
|
|
251
|
+
**Schema Management** โ Dynamic feature-to-bit mapping with frequency-based pruning. Emergency features (bits 56-63) are never pruned regardless of activation frequency.
|
|
252
|
+
|
|
253
|
+
```typescript
|
|
254
|
+
const schema = new SchemaManager({ emergencyPrefix: 'EMERGENCY_' });
|
|
255
|
+
schema.registerAll(myFeatures);
|
|
256
|
+
schema.recordActivations(observedFeatures);
|
|
257
|
+
schema.prune(); // retains top-56 by frequency + all emergency features
|
|
258
|
+
|
|
259
|
+
// Paper-aligned collision math utilities
|
|
260
|
+
const p = schema.theoreticalCollisionRate;
|
|
261
|
+
// p = 1 - (1 - 1/64)^(m - 1), where m = activeFeatureCount
|
|
262
|
+
|
|
263
|
+
const excluded = schema.expectedExcludedFeatures(80);
|
|
264
|
+
// E[excluded] = m - 64 * (1 - (1 - 1/64)^m)
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
**Schema Distribution** โ Deterministic schema export/import with fingerprinting for cross-node compatibility checks.
|
|
268
|
+
|
|
269
|
+
```typescript
|
|
270
|
+
const exported = schema.exportSchema();
|
|
271
|
+
// Send exported JSON through your control plane
|
|
272
|
+
|
|
273
|
+
const replica = new SchemaManager();
|
|
274
|
+
replica.importSchema(exported);
|
|
275
|
+
// replica.fingerprint === schema.fingerprint
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
**Binary Serialization** โ Messages serialize to exactly 24 bytes. Round-trips through `serialize()` / `deserialize()` for any transport layer.
|
|
279
|
+
|
|
280
|
+
```typescript
|
|
281
|
+
const bytes = msg.toBytes(); // Uint8Array(24)
|
|
282
|
+
const restored = BitmaskMessage.deserialize(bytes);
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
**Weighted Scoring** โ Configurable importance weights per bit position. Domain-specific presets included.
|
|
286
|
+
|
|
287
|
+
```typescript
|
|
288
|
+
import { createFinancialArbiter, createRoboticArbiter } from 'adaptive-bitmask';
|
|
289
|
+
|
|
290
|
+
const arbiter = createFinancialArbiter(); // emergency bits weighted 0.45
|
|
291
|
+
const arbiter = createRoboticArbiter(); // obstacle detection weighted 0.30
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
**Paper-Canonical Strategy Arbitration (Section 6)** โ Rank strategy candidates by `s_final = 0.6*s_raw + 0.4*c`, then apply lead/synthesis thresholds.
|
|
295
|
+
|
|
296
|
+
```typescript
|
|
297
|
+
const result = arbiter.scoreStrategies([
|
|
298
|
+
{ id: 'trend', mask: trendMask, confidence: trendConf },
|
|
299
|
+
{ id: 'mean_revert', mask: mrMask, confidence: mrConf },
|
|
300
|
+
{ id: 'breakout', mask: boMask, confidence: boConf },
|
|
301
|
+
], {
|
|
302
|
+
leadThreshold: 0.15,
|
|
303
|
+
rejectThreshold: 0.40,
|
|
304
|
+
});
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
Legacy compatibility: `arbiter.score(mask, confidence?)` remains unchanged for existing integrations.
|
|
308
|
+
|
|
309
|
+
**Bitwise Primitives** โ Full suite of 64-bit operations using BigInt for precision.
|
|
310
|
+
|
|
311
|
+
```typescript
|
|
312
|
+
import { setBit, popcount, merge, delta, hammingDistance } from 'adaptive-bitmask';
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
**Strict Encoding Mode** โ Fail fast on unknown features to catch schema drift at ingestion time.
|
|
316
|
+
|
|
317
|
+
```typescript
|
|
318
|
+
const { mask } = encode(features, schema.featureToBit, {
|
|
319
|
+
throwOnUnknownFeatures: true,
|
|
320
|
+
});
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
**Stale Schema Policy** โ Choose how coordinators handle version-mismatched messages.
|
|
324
|
+
|
|
325
|
+
```typescript
|
|
326
|
+
const coordinator = new Coordinator({
|
|
327
|
+
schemaVersion: schema.version,
|
|
328
|
+
staleMessagePolicy: 'drop', // 'accept' | 'warn' | 'drop'
|
|
329
|
+
});
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
**Telemetry Hooks** โ Attach runtime callbacks for coordination and decision metrics.
|
|
333
|
+
|
|
334
|
+
```typescript
|
|
335
|
+
const coordinator = new Coordinator({
|
|
336
|
+
onTelemetry: (event) => {
|
|
337
|
+
if (event.type === 'round_aggregated') {
|
|
338
|
+
console.log(event.result.aggregationTimeUs);
|
|
339
|
+
}
|
|
340
|
+
},
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
const arbiter = new Arbiter({
|
|
344
|
+
onTelemetry: (event) => {
|
|
345
|
+
if (event.type === 'decision') {
|
|
346
|
+
console.log(event.result.finalScore);
|
|
347
|
+
}
|
|
348
|
+
},
|
|
349
|
+
});
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
## Performance
|
|
353
|
+
|
|
354
|
+
Measured on the protocol simulation (1,000 trials):
|
|
355
|
+
|
|
356
|
+
| Operation | Mean | p99 |
|
|
357
|
+
|-----------|------|-----|
|
|
358
|
+
| Encode features | 2.0ฮผs | 3.9ฮผs |
|
|
359
|
+
| Serialize message | 0.5ฮผs | 0.8ฮผs |
|
|
360
|
+
| Aggregate (10 agents) | 84ฮผs | 122ฮผs |
|
|
361
|
+
| Score (weighted linear) | 15ฮผs | 26ฮผs |
|
|
362
|
+
| **Full pipeline (no LLM)** | **110ฮผs** | **159ฮผs** |
|
|
363
|
+
|
|
364
|
+
The protocol overhead is negligible. LLM inference (6.8ms) accounts for 97.7% of end-to-end latency.
|
|
365
|
+
|
|
366
|
+
## Migration Notes (`0.1.x` -> `0.2.0-rc.0`)
|
|
367
|
+
|
|
368
|
+
`BitmaskMessage` validation is now strict:
|
|
369
|
+
- `deserialize()` now requires exactly `24` bytes (not "at least 24")
|
|
370
|
+
- constructor throws for out-of-range `mask`, `agentId`, `schemaVersion`, or unsafe `timestampMs`
|
|
371
|
+
|
|
372
|
+
Coordinator behavior adds explicit stale handling:
|
|
373
|
+
- new config: `staleMessagePolicy: 'accept' | 'warn' | 'drop'`
|
|
374
|
+
- aggregate output now includes `droppedStaleMessages`
|
|
375
|
+
|
|
376
|
+
Schema coordination helpers are now available:
|
|
377
|
+
- `schema.exportSchema()` / `schema.importSchema(...)`
|
|
378
|
+
- deterministic `schema.fingerprint` for compatibility checks
|
|
379
|
+
|
|
380
|
+
## Transport
|
|
381
|
+
|
|
382
|
+
This library is **transport-agnostic**. The 24-byte message format works with any transport layer:
|
|
383
|
+
|
|
384
|
+
```typescript
|
|
385
|
+
// WebSocket
|
|
386
|
+
ws.send(msg.toBytes());
|
|
387
|
+
|
|
388
|
+
// gRPC (as bytes field)
|
|
389
|
+
grpcStream.write({ payload: msg.toBytes() });
|
|
390
|
+
|
|
391
|
+
// HTTP (base64 or raw body)
|
|
392
|
+
fetch('/coordinate', { body: msg.serialize() });
|
|
393
|
+
|
|
394
|
+
// Vercel AI SDK (coming soon)
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
Optional helper for control-plane metadata:
|
|
398
|
+
|
|
399
|
+
```typescript
|
|
400
|
+
import { createEnvelope, decodeEnvelope } from 'adaptive-bitmask';
|
|
401
|
+
|
|
402
|
+
const envelope = createEnvelope(msg, schema.fingerprint, 'round-42');
|
|
403
|
+
const restored = decodeEnvelope(envelope, schema.fingerprint);
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
See [examples/transport.ts](/Users/hjiang/Developer/adaptive-bitmask/examples/transport.ts) for end-to-end transport payload patterns.
|
|
407
|
+
|
|
408
|
+
## Benchmarking
|
|
409
|
+
|
|
410
|
+
```bash
|
|
411
|
+
npm run benchmark
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
Writes benchmark results to `benchmarks/latest.json`.
|
|
415
|
+
|
|
416
|
+
```bash
|
|
417
|
+
npm run benchmark:run
|
|
418
|
+
npm run benchmark:check
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
`benchmark:check` fails if an operation regresses beyond both thresholds:
|
|
422
|
+
- relative: `BENCH_MAX_REGRESSION_PCT` (default `40`)
|
|
423
|
+
- absolute: `BENCH_MAX_ABS_REGRESSION_US` (default `1.5`)
|
|
424
|
+
- baseline file: `BENCH_BASELINE_PATH` (default `benchmarks/baseline.json`)
|
|
425
|
+
|
|
426
|
+
## API Reference
|
|
427
|
+
|
|
428
|
+
### Bitmask Primitives
|
|
429
|
+
|
|
430
|
+
`empty()` ยท `setBit(mask, pos)` ยท `clearBit(mask, pos)` ยท `testBit(mask, pos)` ยท `popcount(mask)` ยท `activeBits(mask)` ยท `forEachSetBit(mask, fn)` ยท `merge(a, b)` ยท `intersect(a, b)` ยท `delta(prev, next)` ยท `hammingDistance(a, b)` ยท `hasEmergency(mask)` ยท `toBytes(mask)` ยท `fromBytes(buf)` ยท `encode(features, schema, options?)` ยท `decode(mask, reverseSchema)`
|
|
431
|
+
|
|
432
|
+
### SchemaManager
|
|
433
|
+
|
|
434
|
+
`new SchemaManager(config?)` ยท `.register(feature)` ยท `.registerAll(features)` ยท `.recordActivations(features)` ยท `.prune()` ยท `.snapshot()` ยท `.exportSchema()` ยท `.importSchema(exported)` ยท `.expectedExcludedFeatures(featureCount?)` ยท `.theoreticalCollisionRate` ยท `.fingerprint` ยท `.featureToBit` ยท `.bitToFeatures` ยท `.version`
|
|
435
|
+
|
|
436
|
+
### BitmaskMessage
|
|
437
|
+
|
|
438
|
+
`new BitmaskMessage(data)` ยท `BitmaskMessage.now(mask, agentId, version)` ยท `.serialize()` ยท `.toBytes()` ยท `BitmaskMessage.deserialize(buf)` ยท `.sizeBytes` ยท `.compressionVsJson`
|
|
439
|
+
|
|
440
|
+
### Arbiter
|
|
441
|
+
|
|
442
|
+
`new Arbiter(config?)` ยท `.score(mask, confidence?)` (legacy) ยท `.scoreStrategies(candidates, options?)` (paper-canonical) ยท `.scoreMessages(messages, version?)` ยท `.setWeight(pos, weight)` ยท `createFinancialArbiter()` ยท `createRoboticArbiter()` (`onTelemetry`)
|
|
443
|
+
|
|
444
|
+
### Coordinator
|
|
445
|
+
|
|
446
|
+
`new Coordinator(config?)` ยท `.startRound()` ยท `.receive(msg)` ยท `.receiveAll(msgs)` ยท `.aggregate()` ยท `.schemaVersion` (`staleMessagePolicy`: `'accept' | 'warn' | 'drop'`, `onTelemetry`)
|
|
447
|
+
|
|
448
|
+
### Transport Envelope
|
|
449
|
+
|
|
450
|
+
`createEnvelope(msg, schemaFingerprint, roundId?)` ยท `decodeEnvelope(envelope, expectedSchemaFingerprint?)`
|
|
451
|
+
|
|
452
|
+
## License
|
|
453
|
+
|
|
454
|
+
MIT
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { S as SchemaManager, C as Coordinator, A as Arbiter, b as CoordinatorConfig, c as ArbiterConfig, D as Decision, d as ArbiterResult } from '../coordinator-Df48t6yJ.mjs';
|
|
2
|
+
import * as ai from 'ai';
|
|
3
|
+
import { LanguageModelV1Middleware } from 'ai';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* CoordinationSession โ Lifecycle manager for bitmask-based agent coordination.
|
|
8
|
+
*
|
|
9
|
+
* Wraps SchemaManager + Coordinator + Arbiter into a single object
|
|
10
|
+
* that AI SDK tools and middleware can reference.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
interface CoordinationSessionConfig {
|
|
14
|
+
/** Initial feature vocabulary to register. */
|
|
15
|
+
features: string[];
|
|
16
|
+
/** Prefix for emergency features. Default: 'EMERGENCY_' */
|
|
17
|
+
emergencyPrefix?: string;
|
|
18
|
+
/** Explicit emergency features (alternative to prefix). */
|
|
19
|
+
emergencyFeatures?: string[];
|
|
20
|
+
/** Coordinator configuration overrides. */
|
|
21
|
+
coordinatorConfig?: Partial<CoordinatorConfig>;
|
|
22
|
+
/** Arbiter configuration overrides. */
|
|
23
|
+
arbiterConfig?: Partial<ArbiterConfig>;
|
|
24
|
+
}
|
|
25
|
+
interface ReportResult {
|
|
26
|
+
accepted: boolean;
|
|
27
|
+
mapped: number;
|
|
28
|
+
unmapped: number;
|
|
29
|
+
}
|
|
30
|
+
interface DecisionResult {
|
|
31
|
+
decision: Decision;
|
|
32
|
+
aggregatedFeatures: string[];
|
|
33
|
+
confidence: Map<number, number>;
|
|
34
|
+
result: ArbiterResult;
|
|
35
|
+
}
|
|
36
|
+
declare class CoordinationSession {
|
|
37
|
+
readonly schema: SchemaManager;
|
|
38
|
+
readonly coordinator: Coordinator;
|
|
39
|
+
readonly arbiter: Arbiter;
|
|
40
|
+
private readonly _agentIds;
|
|
41
|
+
constructor(config: CoordinationSessionConfig);
|
|
42
|
+
/** Deterministic agent ID: FNV-1a hash of name โ uint32. */
|
|
43
|
+
agentId(name: string): number;
|
|
44
|
+
/** Start a new coordination round. Clears the coordinator buffer. */
|
|
45
|
+
startRound(): void;
|
|
46
|
+
/** Encode features + create message + receive in one call. */
|
|
47
|
+
report(agentName: string, features: string[]): ReportResult;
|
|
48
|
+
/** Aggregate current buffer + score via arbiter. */
|
|
49
|
+
decide(): DecisionResult;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
declare function createCoordinationTools(session: CoordinationSession): {
|
|
53
|
+
reportObservation: ai.Tool<z.ZodObject<{
|
|
54
|
+
agentName: z.ZodString;
|
|
55
|
+
features: z.ZodArray<z.ZodString, "many">;
|
|
56
|
+
}, "strip", z.ZodTypeAny, {
|
|
57
|
+
agentName: string;
|
|
58
|
+
features: string[];
|
|
59
|
+
}, {
|
|
60
|
+
agentName: string;
|
|
61
|
+
features: string[];
|
|
62
|
+
}>, {
|
|
63
|
+
accepted: boolean;
|
|
64
|
+
mapped: number;
|
|
65
|
+
unmapped: number;
|
|
66
|
+
}> & {
|
|
67
|
+
execute: (args: {
|
|
68
|
+
agentName: string;
|
|
69
|
+
features: string[];
|
|
70
|
+
}, options: ai.ToolExecutionOptions) => PromiseLike<{
|
|
71
|
+
accepted: boolean;
|
|
72
|
+
mapped: number;
|
|
73
|
+
unmapped: number;
|
|
74
|
+
}>;
|
|
75
|
+
};
|
|
76
|
+
getConsensus: ai.Tool<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>, {
|
|
77
|
+
features: string[];
|
|
78
|
+
confidence: Record<string, number>;
|
|
79
|
+
agentCount: number;
|
|
80
|
+
}> & {
|
|
81
|
+
execute: (args: {}, options: ai.ToolExecutionOptions) => PromiseLike<{
|
|
82
|
+
features: string[];
|
|
83
|
+
confidence: Record<string, number>;
|
|
84
|
+
agentCount: number;
|
|
85
|
+
}>;
|
|
86
|
+
};
|
|
87
|
+
requestDecision: ai.Tool<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>, {
|
|
88
|
+
decision: Decision;
|
|
89
|
+
score: number;
|
|
90
|
+
features: string[];
|
|
91
|
+
hasEmergency: boolean;
|
|
92
|
+
}> & {
|
|
93
|
+
execute: (args: {}, options: ai.ToolExecutionOptions) => PromiseLike<{
|
|
94
|
+
decision: Decision;
|
|
95
|
+
score: number;
|
|
96
|
+
features: string[];
|
|
97
|
+
hasEmergency: boolean;
|
|
98
|
+
}>;
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Coordination middleware for the Vercel AI SDK.
|
|
104
|
+
*
|
|
105
|
+
* Optionally injects consensus state into the system prompt and/or
|
|
106
|
+
* auto-encodes tool call names as bitmask observations.
|
|
107
|
+
*/
|
|
108
|
+
|
|
109
|
+
interface CoordinationMiddlewareOptions {
|
|
110
|
+
/** Inject current consensus into system prompt before each LLM call. Default: false. */
|
|
111
|
+
injectConsensus?: boolean;
|
|
112
|
+
/**
|
|
113
|
+
* Auto-encode tool call names as bitmask observations after generation. Default: false.
|
|
114
|
+
* When enabled, tool calls whose names match registered schema features are
|
|
115
|
+
* automatically reported to the coordinator. Requires agentName.
|
|
116
|
+
*/
|
|
117
|
+
autoEncodeToolCalls?: boolean;
|
|
118
|
+
/** Required when autoEncodeToolCalls is true. Identifies this agent in the coordinator. */
|
|
119
|
+
agentName?: string;
|
|
120
|
+
}
|
|
121
|
+
declare function createCoordinationMiddleware(session: CoordinationSession, options?: CoordinationMiddlewareOptions): LanguageModelV1Middleware;
|
|
122
|
+
|
|
123
|
+
export { type CoordinationMiddlewareOptions, CoordinationSession, type CoordinationSessionConfig, type DecisionResult, type ReportResult, createCoordinationMiddleware, createCoordinationTools };
|